diff --git a/.github/commands-readme.md b/.github/commands-readme.md index bf0e9e5ed20bb3085e6bbe3e59079372121167b1..793524e056f8e113b0803405f2d5a238a7c7b285 100644 --- a/.github/commands-readme.md +++ b/.github/commands-readme.md @@ -10,6 +10,7 @@ The current available command actions are: - [Command FMT](https://github.com/paritytech/polkadot-sdk/actions/workflows/command-fmt.yml) - [Command Update UI](https://github.com/paritytech/polkadot-sdk/actions/workflows/command-update-ui.yml) +- [Command Sync](https://github.com/paritytech/polkadot-sdk/actions/workflows/command-sync.yml) - [Command Bench](https://github.com/paritytech/polkadot-sdk/actions/workflows/command-bench.yml) - [Command Bench All](https://github.com/paritytech/polkadot-sdk/actions/workflows/command-bench-all.yml) - [Command Bench Overhead](https://github.com/paritytech/polkadot-sdk/actions/workflows/command-bench-overhead.yml) @@ -24,12 +25,36 @@ Each command will have the same two required values, but it could have more. GitHub's official documentation: [Manually running a workflow](https://docs.github.com/en/actions/using-workflows/manually-running-a-workflow) +#### Running from CLI + +You can use [`gh cli`](https://cli.github.com/) to run the commands too. Refers to the [`gh workflow run`](https://cli.github.com/manual/gh_workflow_run) section from the documentation for more information. + ### Number of the Pull Request The number of the pull request. Required so the action can fetch the correct branch and comment if it fails. ## Action configurations +### FMT + +For FMT you only need the PR number. + +You can use the following [`gh cli`](https://cli.github.com/) inside the repo: + +```bash +gh workflow run command-fmt.yml -f pr=1000 +``` + +### Update UI + +For Update UI you only need the PR number. + +You can use the following [`gh cli`](https://cli.github.com/) inside the repo: + +```bash +gh workflow run command-update-ui.yml -f pr=1000 +``` + ### Bench Runs `benchmark pallet` or `benchmark overhead` against your PR and commits back updated weights. @@ -135,6 +160,12 @@ Posible combinations based on the `benchmark` dropdown. - Requires `Runtime Dir` to be `testing` - Requires `Target Directory` to be `cumulus` +You can use the following [`gh cli`](https://cli.github.com/) inside the repo: + +```bash +gh workflow run command-bench.yml -f pr=1000 -f benchmark=polkadot-pallet -f subcommand=pallet -f runtime=rococo -f pallet=pallet_name -f target_dir=polkadot +``` + ### Bench-all This is a wrapper to run `bench` for all pallets. @@ -173,6 +204,12 @@ Posible combinations based on the `benchmark` dropdown. - `people-westend` - Requires `Target Directory` to be `cumulus` +You can use the following [`gh cli`](https://cli.github.com/) inside the repo: + +```bash +gh workflow run command-bench-all.yml -f pr=1000 -f benchmark=pallet -f pallet=pallet_name -f target_dir=polkadot -f runtime=rococo +``` + ### Bench-overhead Run benchmarks overhead and commit back results to PR. @@ -192,6 +229,35 @@ Posible combinations based on the `benchmark` dropdown. - `asset-hub-westend` - Requires `Target directory` to be `cumulus` +You can use the following [`gh cli`](https://cli.github.com/) inside the repo: + +```bash +gh workflow run command-bench-overheard.yml -f pr=1000 -f benchmark=substrate -f runtime=rococo -f target_dir=substrate +``` + +### Sync + +Run sync and commit back results to PR. + +Posible combinations based on the `benchmark` dropdown. + +- `chain` + - Requires one of the following: + - `rococo` + - `westend` +- `sync-type` + - Requires one of the following: + - `warp` + - `full` + - `fast` + - `fast-unsafe` + +You can use the following [`gh cli`](https://cli.github.com/) inside the repo: + +```bash +gh workflow run command-sync.yml -f pr=1000 -f chain=rococo -f sync-type=full +``` + ## How to modify an action If you want to modify an action and test it, you can do by simply pushing your changes and then selecting your branch in the `Use worflow from` option. diff --git a/.github/env b/.github/env index 162ce8af7c0ddbc1534b7d1ffb09cff4be012fc7..2e4d5b48100dfb3e976270efd155843e907687a8 100644 --- a/.github/env +++ b/.github/env @@ -1 +1 @@ -IMAGE="docker.io/paritytech/ci-unified:bullseye-1.77.0-2024-04-10-v20240408" \ No newline at end of file +IMAGE="docker.io/paritytech/ci-unified:bullseye-1.77.0-2024-04-10-v202407161507" diff --git a/.github/scripts/common/lib.sh b/.github/scripts/common/lib.sh index f844e962c41def7625fa3d45ae3cbf81ecb57147..33ef2d3e7eda4d6b4b5b7eacc2e3ed2b1a24c29f 100755 --- a/.github/scripts/common/lib.sh +++ b/.github/scripts/common/lib.sh @@ -444,3 +444,16 @@ get_latest_release_tag() { latest_release_tag=$(curl -s -H "$TOKEN" $api_base/paritytech/polkadot-sdk/releases/latest | jq -r '.tag_name') printf $latest_release_tag } + +function get_polkadot_node_version_from_code() { + # list all the files with node version + git grep -e "\(NODE_VERSION[^=]*= \)\".*\"" | + # fetch only the one we need + grep "primitives/src/lib.rs:" | + # Print only the version + awk '{ print $7 }' | + # Remove the quotes + sed 's/"//g' | + # Remove the semicolon + sed 's/;//g' +} diff --git a/.github/workflows/check-licenses.yml b/.github/workflows/check-licenses.yml index 3bc95305f7467ebbede90526eadb156b89b1e7f9..b77135805409d1fb869b9a061e681b582924e4b7 100644 --- a/.github/workflows/check-licenses.yml +++ b/.github/workflows/check-licenses.yml @@ -17,7 +17,7 @@ jobs: steps: - name: Checkout sources uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 - - uses: actions/setup-node@v4.0.1 + - uses: actions/setup-node@v4.0.3 with: node-version: "18.x" registry-url: "https://npm.pkg.github.com" diff --git a/.github/workflows/checks-quick.yml b/.github/workflows/checks-quick.yml index 1fcec5c80fd49a337fe84af6c3799ff20a081aaa..678bfb6f2058b98162c9a907efe48f0e770a4f38 100644 --- a/.github/workflows/checks-quick.yml +++ b/.github/workflows/checks-quick.yml @@ -109,7 +109,7 @@ jobs: - name: Checkout sources uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 - name: Setup Node.js - uses: actions/setup-node@v4.0.1 + uses: actions/setup-node@v4.0.3 with: node-version: "18.x" registry-url: "https://npm.pkg.github.com" diff --git a/.github/workflows/command-bench-all.yml b/.github/workflows/command-bench-all.yml index f1d1589bea29d2ab38b6a80bb0a1f60c88f4a632..4128f86fb7c82f76e658fd39fad3365395a244e2 100644 --- a/.github/workflows/command-bench-all.yml +++ b/.github/workflows/command-bench-all.yml @@ -63,9 +63,12 @@ jobs: run: cat .github/env >> $GITHUB_OUTPUT cmd-bench-all: needs: [set-image] - runs-on: arc-runners-polkadot-sdk-benchmark + runs-on: arc-runners-polkadot-sdk-weights container: image: ${{ needs.set-image.outputs.IMAGE }} + permissions: + contents: write + pull-requests: write steps: - name: Download repo uses: actions/checkout@v4 diff --git a/.github/workflows/command-bench-overhead.yml b/.github/workflows/command-bench-overhead.yml index 16cbcefcf26974f169d0cd5a1f946af766f18a21..fec8d37bb9ef80505c9569da08071ccee7275067 100644 --- a/.github/workflows/command-bench-overhead.yml +++ b/.github/workflows/command-bench-overhead.yml @@ -45,6 +45,9 @@ jobs: runs-on: arc-runners-polkadot-sdk-benchmark container: image: ${{ needs.set-image.outputs.IMAGE }} + permissions: + contents: write + pull-requests: write steps: - name: Download repo uses: actions/checkout@v4 diff --git a/.github/workflows/command-bench.yml b/.github/workflows/command-bench.yml index b23b06d1b3c043113c2f226b5e1cd32bf5f4b022..ac879f443755c65948c51f592dacc39ceb8f5c25 100644 --- a/.github/workflows/command-bench.yml +++ b/.github/workflows/command-bench.yml @@ -91,6 +91,9 @@ jobs: runs-on: arc-runners-polkadot-sdk-benchmark container: image: ${{ needs.set-image.outputs.IMAGE }} + permissions: + contents: write + pull-requests: write steps: - name: Download repo uses: actions/checkout@v4 diff --git a/.github/workflows/command-fmt.yml b/.github/workflows/command-fmt.yml index c949d0768d7a7d2560dbc154a18082600b8132b5..fc37a17ac549b06e6850ea8a209ec4b27db8fb3f 100644 --- a/.github/workflows/command-fmt.yml +++ b/.github/workflows/command-fmt.yml @@ -23,6 +23,9 @@ jobs: timeout-minutes: 20 container: image: ${{ needs.set-image.outputs.IMAGE }} + permissions: + contents: write + pull-requests: write steps: - name: Download repo uses: actions/checkout@v4 @@ -34,6 +37,13 @@ jobs: GH_TOKEN: ${{ github.token }} - name: Run FMT run: | + cargo --version + rustc --version + cargo +nightly --version + rustc +nightly --version + + cargo +nightly fmt + # format toml. # since paritytech/ci-unified:bullseye-1.73.0-2023-11-01-v20231204 includes taplo-cli taplo format --config .config/taplo.toml diff --git a/.github/workflows/command-inform.yml b/.github/workflows/command-inform.yml index 1c7323c998dfee3ba822f4bcb655c57a958fd80f..2825f4a604605fea8465ce0646d664c9ef5d38f5 100644 --- a/.github/workflows/command-inform.yml +++ b/.github/workflows/command-inform.yml @@ -7,9 +7,15 @@ on: jobs: comment: runs-on: ubuntu-latest + if: github.event.issue.pull_request && startsWith(github.event.comment.body, 'bot ') steps: - name: Inform that the new command exist - if: ${{ github.event.issue.pull_request && startsWith(github.event.comment.body, 'bot ') }} - run: gh pr comment ${{ github.event.issue.number }} --body 'We are migrating this bot to be a GitHub Action

Please, see the documentation on how to use it' - env: - GH_TOKEN: ${{ github.token }} + uses: actions/github-script@v7 + with: + script: | + github.rest.issues.createComment({ + issue_number: context.issue.number, + owner: context.repo.owner, + repo: context.repo.repo, + body: 'We are migrating the command bot to be a GitHub Action

Please, see the documentation on how to use it' + }) diff --git a/.github/workflows/command-sync.yml b/.github/workflows/command-sync.yml new file mode 100644 index 0000000000000000000000000000000000000000..c610f4066a873e3fe7304bebd2f4b866fe837a91 --- /dev/null +++ b/.github/workflows/command-sync.yml @@ -0,0 +1,71 @@ +name: Command Sync + +on: + workflow_dispatch: + inputs: + pr: + description: Number of the Pull Request + required: true + chain: + description: Chain + type: choice + required: true + options: + - westend + - rococo + sync-type: + description: Sync type + type: choice + required: true + options: + - warp + - full + - fast + - fast-unsafe + +jobs: + set-image: + runs-on: ubuntu-latest + outputs: + IMAGE: ${{ steps.set_image.outputs.IMAGE }} + steps: + - name: Checkout + uses: actions/checkout@v4 + - id: set_image + run: cat .github/env >> $GITHUB_OUTPUT + cmd-sync: + needs: [set-image] + runs-on: arc-runners-polkadot-sdk-warpsync + container: + image: ${{ needs.set-image.outputs.IMAGE }} + permissions: + contents: write + pull-requests: write + steps: + - name: Download repo + uses: actions/checkout@v4 + - name: Install gh cli + id: gh + uses: ./.github/actions/set-up-gh + with: + pr-number: ${{ inputs.pr }} + GH_TOKEN: ${{ github.token }} + - name: Run sync + run: | + "./scripts/sync.sh" --chain "${{ inputs.chain }}" --type "${{ inputs.sync-type }}" + - name: Report failure + if: ${{ failure() }} + run: gh pr comment ${{ inputs.pr }} --body "

Command failed ❌

Run by @${{ github.actor }} for ${{ github.workflow }} failed. See logs here." + env: + RUN: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + GH_TOKEN: ${{ github.token }} + - run: git pull --rebase + - uses: stefanzweifel/git-auto-commit-action@v5 + with: + commit_message: cmd-action - ${{ github.workflow }} + branch: ${{ steps.gh.outputs.branch }} + - name: Report succeed + run: gh pr comment ${{ inputs.pr }} --body "

Action completed 🎉🎉

Run by @${{ github.actor }} for ${{ github.workflow }} completed 🎉. See logs here." + env: + RUN: ${{ github.server_url }}/${{ github.repository }}/actions/runs/${{ github.run_id }} + GH_TOKEN: ${{ github.token }} diff --git a/.github/workflows/command-update-ui.yml b/.github/workflows/command-update-ui.yml index b6b0420e786899134a5693ca6992391a17d1d98f..860177adc8790c28f7cd5873f4f8e0adf24a044f 100644 --- a/.github/workflows/command-update-ui.yml +++ b/.github/workflows/command-update-ui.yml @@ -26,6 +26,9 @@ jobs: timeout-minutes: 90 container: image: ${{ needs.set-image.outputs.IMAGE }} + permissions: + contents: write + pull-requests: write steps: - name: Download repo uses: actions/checkout@v4 diff --git a/.github/workflows/misc-sync-templates.yml b/.github/workflows/misc-sync-templates.yml index d8027014863936ffd6c6a217f282dfa45bc2edd7..835a3116d446c3429a7249bc4822ab0a8faff443 100644 --- a/.github/workflows/misc-sync-templates.yml +++ b/.github/workflows/misc-sync-templates.yml @@ -90,7 +90,12 @@ jobs: "runtime", ] resolver = "2" + + [workspace.dependencies] EOF + + echo "$(toml get -r ./runtime/Cargo.toml 'package.name') = { path = \"./runtime\", default-features = false }" >> Cargo.toml + echo "$(toml get -r ./pallets/template/Cargo.toml 'package.name') = { path = \"./pallets/template\", default-features = false }" >> Cargo.toml shell: bash working-directory: polkadot-sdk/templates/${{ matrix.template }}/ - name: Update workspace configuration @@ -116,9 +121,12 @@ jobs: - name: Copy over the new changes run: | cp -r polkadot-sdk/templates/${{ matrix.template }}/* "${{ env.template-path }}/" + + - name: Run psvm on monorepo workspace dependencies + run: psvm -o -v ${{ github.event.inputs.crate_release_version }} -p ./Cargo.toml + working-directory: polkadot-sdk/ - name: Copy over required workspace dependencies run: | - echo -e "\n[workspace.dependencies]" >> Cargo.toml set +e # If a workspace dependency is required.. while cargo tree --depth 1 --prefix none --no-dedupe 2>&1 | grep 'was not found in `workspace.dependencies`'; do diff --git a/.github/workflows/release-10_rc-automation.yml b/.github/workflows/release-10_rc-automation.yml index 7231a8b75886d04ce18bb89fcef99029e3ab14c6..f5c5de8d0da97546d2adfbcdfabd4805d96e8a70 100644 --- a/.github/workflows/release-10_rc-automation.yml +++ b/.github/workflows/release-10_rc-automation.yml @@ -1,13 +1,18 @@ name: Release - RC automation on: - push: - branches: - # Catches release-polkadot-v1.2.3, release-v1.2.3-rc1, etc - - release-v[0-9]+.[0-9]+.[0-9]+* - - release-cumulus-v[0-9]+* - - release-polkadot-v[0-9]+* + # TODO: Activate it and delete old branches patterns, when the release process from stable is setteled + #push: + # branches: + # # Catches release-polkadot-v1.2.3, release-v1.2.3-rc1, etc + # - release-v[0-9]+.[0-9]+.[0-9]+* + # - release-cumulus-v[0-9]+* + # - release-polkadot-v[0-9]+* + # - stable workflow_dispatch: + inputs: + version: + description: Current release/rc version in format vX.X.X jobs: tag_rc: @@ -25,28 +30,19 @@ jobs: with: fetch-depth: 0 - - name: Get release product - id: get_rel_product - shell: bash - run: | - current_branch=$(git branch --show-current) - echo "Current branch: $current_branch" - if [[ "$current_branch" =~ "release-polkadot" ]]; then - echo "product=polkadot" >> $GITHUB_OUTPUT - elif [[ "$current_branch" =~ "release-cumulus" ]]; then - echo "product=polkadot-parachain" >> $GITHUB_OUTPUT - fi - - - - name: Compute next rc tag for polkadot - if: ${{ steps.get_rel_product.outputs.product == 'polkadot' }} - id: compute_tag_polkadot + - name: Compute next rc tag + # if: ${{ steps.get_rel_product.outputs.product == 'polkadot' }} + id: compute_tag shell: bash run: | . ./.github/scripts/common/lib.sh # Get last rc tag if exists, else set it to {version}-rc1 - version=$(get_version_from_ghref ${GITHUB_REF}) + if [[ -z "${{ inputs.version }}" ]]; then + version=v$(get_polkadot_node_version_from_code) + else + version=$(filter_version_from_input ${{ inputs.version }}) + fi echo "$version" echo "version=$version" >> $GITHUB_OUTPUT @@ -61,28 +57,6 @@ jobs: echo "first_rc=true" >> $GITHUB_OUTPUT fi - - name: Compute next rc tag for polkadot-parachain - if: ${{ steps.get_rel_product.outputs.product == 'polkadot-parachain' }} - id: compute_tag_cumulus - shell: bash - run: | - . ./.github/scripts/common/lib.sh - - # Get last rc tag if exists, else set it to polkadot-parachains-{version}-rc1 - version=$(get_version_from_ghref ${GITHUB_REF}) - echo "$version" - echo "version=$version" >> $GITHUB_OUTPUT - - last_rc=$(get_latest_rc_tag $version polkadot-parachain) - if [ -n "$last_rc" ]; then - suffix=$(increment_rc_tag $last_rc) - echo "new_tag=polkadot-parachains-$version-rc$suffix" >> $GITHUB_OUTPUT - echo "first_rc=false" >> $GITHUB_OUTPUT - else - echo "new_tag=polkadot-parachain-$version-rc1" >> $GITHUB_OUTPUT - echo "first_rc=true" >> $GITHUB_OUTPUT - fi - - name: Apply new tag uses: tvdias/github-tagger@ed7350546e3e503b5e942dffd65bc8751a95e49d # v0.0.2 with: @@ -90,17 +64,7 @@ jobs: # https://docs.github.com/en/actions/reference/events-that-trigger-workflows#triggering-new-workflows-using-a-personal-access-token # RELEASE_BRANCH_TOKEN requires public_repo OAuth scope repo-token: "${{ secrets.RELEASE_BRANCH_TOKEN }}" - tag: ${{ steps.compute_tag_polkadot.outputs.new_tag || steps.compute_tag_cumulus.outputs.new_tag }} - - # - id: create-issue - # uses: JasonEtco/create-an-issue@e27dddc79c92bc6e4562f268fffa5ed752639abd # v2.9.1 - # # Only create the issue if it's the first release candidate - # if: steps.compute_tag.outputs.first_rc == 'true' - # env: - # GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} - # VERSION: ${{ steps.compute_tag.outputs.version }} - # with: - # filename: .github/ISSUE_TEMPLATE/release.md + tag: ${{ steps.compute_tag.outputs.new_tag }} - name: Send Matrix message to ${{ matrix.channel.name }} uses: s3krit/matrix-message-action@70ad3fb812ee0e45ff8999d6af11cafad11a6ecf # v0.0.3 @@ -110,4 +74,4 @@ jobs: access_token: ${{ secrets.RELEASENOTES_MATRIX_V2_ACCESS_TOKEN }} server: m.parity.io message: | - Release process for polkadot ${{ steps.compute_tag_polkadot.outputs.new_tag || steps.compute_tag_cumulus.outputs.new_tag }} has been started.
+ Release process for polkadot ${{ steps.compute_tag.outputs.new_tag }} has been started.
diff --git a/.github/workflows/release-50_publish-docker.yml b/.github/workflows/release-50_publish-docker.yml index 4679f58578f7906b75e4a3d6d623ebc1d55df40d..723883eaf64cc4bc620ea306b8205aff4f1dc28b 100644 --- a/.github/workflows/release-50_publish-docker.yml +++ b/.github/workflows/release-50_publish-docker.yml @@ -179,6 +179,7 @@ jobs: release=$( echo $VERSION | cut -f1 -d- ) echo "tag=latest" >> $GITHUB_OUTPUT echo "release=${release}" >> $GITHUB_OUTPUT + echo "stable=stable" >> $GITHUB_OUTPUT - name: Build Injected Container image for polkadot rc or chain-spec-builder if: ${{ env.BINARY == 'polkadot' || env.BINARY == 'chain-spec-builder' }} @@ -294,6 +295,7 @@ jobs: # TODO: The owner should be used below but buildx does not resolve the VARs # TODO: It would be good to get rid of this GHA that we don't really need. tags: | + parity/polkadot:stable parity/polkadot:latest parity/polkadot:${{ needs.fetch-latest-debian-package-version.outputs.polkadot_container_tag }} build-args: | diff --git a/.github/workflows/release-srtool.yml b/.github/workflows/release-srtool.yml index 69a4bdbdda9ae87a188a23bceb9185d813424a98..e98269fecab0085f1fd6f32acb3aea9b98a5f235 100644 --- a/.github/workflows/release-srtool.yml +++ b/.github/workflows/release-srtool.yml @@ -5,11 +5,6 @@ env: TOML_CLI_VERSION: 0.2.4 on: - push: - branches: - - release-v[0-9]+.[0-9]+.[0-9]+* - - release-cumulus-v[0-9]+* - - release-polkadot-v[0-9]+* workflow_call: inputs: excluded_runtimes: diff --git a/.gitignore b/.gitignore index 2f1631fb4b9d14496021907cca96b4cdf4902eb8..e3e382af6195ed4692672285a14e1cf5f1600a85 100644 --- a/.gitignore +++ b/.gitignore @@ -14,6 +14,7 @@ *.orig *.rej *.swp +*.wasm **/._* **/.criterion/ **/*.rs.bk diff --git a/Cargo.lock b/Cargo.lock index 41915bf0feb17710eb7a90acbd2179c9f301de6d..ac007fdf9c30f1fbb040bd5a7e9190862dd32f62 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -158,7 +158,7 @@ dependencies = [ "heck 0.4.1", "proc-macro-error", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", "syn-solidity", "tiny-keccak", @@ -262,9 +262,9 @@ dependencies = [ [[package]] name = "anyhow" -version = "1.0.81" +version = "1.0.86" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0952808a6c2afd1aa8947271f3a60f1a6763c7b912d210184c5149b5cf147247" +checksum = "b3d1d046238990b9cf5bcde22a3fb3584ee5cf65fb2765f454ed428c7a0063da" [[package]] name = "approx" @@ -285,7 +285,7 @@ dependencies = [ "itertools 0.10.5", "proc-macro-error", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -484,7 +484,7 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db02d390bf6643fb404d3d22d31aee1c4bc4459600aef9113833d17e786c6e44" dependencies = [ - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", ] @@ -494,7 +494,7 @@ version = "0.4.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ed4aa4fe255d0bc6d79373f7e31d2ea147bcf486cba1be5ba7ea85abdb92348" dependencies = [ - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", ] @@ -506,7 +506,7 @@ checksum = "db2fd794a08ccb318058009eefdf15bcaaaaf6f8161eb3345f907222bac38b20" dependencies = [ "num-bigint", "num-traits", - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", ] @@ -519,7 +519,7 @@ dependencies = [ "num-bigint", "num-traits", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", ] @@ -621,7 +621,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ae3281bc6d0fd7e549af32b52511e1302185bd688fd3359fa36423346ff682ea" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", ] @@ -725,7 +725,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "726535892e8eae7e70657b4c8ea93d26b8553afb1ce617caee529ef96d7dee6c" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", "synstructure 0.12.6", ] @@ -737,7 +737,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7378575ff571966e99a744addeff0bff98b8ada0dedf1956d59e634db95eaac1" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", "synstructure 0.13.1", ] @@ -749,7 +749,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2777730b2039ac0f95f093556e61b6d26cebed5393ca6f152717777cec3a42ed" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", ] @@ -760,15 +760,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b18050c2cd6fe86c3a76584ef5e0baf286d038cda203eb6223df2cc413565f7" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] [[package]] name = "assert_cmd" -version = "2.0.12" +version = "2.0.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88903cb14723e4d4003335bb7f8a14f27691649105346a0f0957466c096adfe6" +checksum = "ed72493ac66d5804837f480ab3766c72bdfab91a65e565fc54fa9e42db0073a8" dependencies = [ "anstyle", "bstr", @@ -896,7 +896,6 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std 14.0.0", "sp-storage 19.0.0", "sp-transaction-pool", "sp-version", @@ -1026,7 +1025,6 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std 14.0.0", "sp-storage 19.0.0", "sp-transaction-pool", "sp-version", @@ -1062,7 +1060,6 @@ dependencies = [ "parity-scale-codec", "sp-io", "sp-runtime", - "sp-std 14.0.0", "staging-parachain-info", "staging-xcm", "staging-xcm-builder", @@ -1085,7 +1082,6 @@ dependencies = [ "scale-info", "sp-api", "sp-runtime", - "sp-std 14.0.0", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -1098,7 +1094,7 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a3203e79f4dd9bdda415ed03cf14dae5a2bf775c683a00f94e9cd1faf0f596e5" dependencies = [ - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", ] @@ -1210,7 +1206,7 @@ checksum = "ff6e472cdea888a4bd64f342f09b3f50e1886d32afe8df3d663c01140b811b18" dependencies = [ "event-listener 5.2.0", "event-listener-strategy", - "pin-project-lite 0.2.12", + "pin-project-lite", ] [[package]] @@ -1264,7 +1260,7 @@ dependencies = [ "log", "memchr", "once_cell", - "pin-project-lite 0.2.12", + "pin-project-lite", "pin-utils", "slab", "wasm-bindgen-futures", @@ -1278,7 +1274,7 @@ checksum = "cd56dd203fef61ac097dd65721a419ddccb106b2d2b70ba60a6b529f03961a51" dependencies = [ "async-stream-impl", "futures-core", - "pin-project-lite 0.2.12", + "pin-project-lite", ] [[package]] @@ -1288,7 +1284,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "16e62a023e7c117e27523144c5d2459f4397fcc3cab0085af8e2224f643a0193" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -1305,7 +1301,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c6fa2087f2753a7da8cc1c0dbfcf89579dd57458e36769de5ac750b4671737ca" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -1319,7 +1315,7 @@ dependencies = [ "futures-sink", "futures-util", "memchr", - "pin-project-lite 0.2.12", + "pin-project-lite", ] [[package]] @@ -1364,7 +1360,7 @@ checksum = "fee3da8ef1276b0bee5dd1c7258010d8fffd31801447323115a25560e1327b89" dependencies = [ "proc-macro-error", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", ] @@ -1512,7 +1508,7 @@ dependencies = [ "peeking_take_while", "prettyplease 0.2.12", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "regex", "rustc-hash", "shlex", @@ -2036,7 +2032,6 @@ dependencies = [ "snowbridge-core", "sp-core", "sp-runtime", - "sp-std 14.0.0", "staging-xcm", ] @@ -2216,7 +2211,6 @@ dependencies = [ "sp-io", "sp-keyring", "sp-runtime", - "sp-std 14.0.0", "sp-tracing 16.0.0", "staging-xcm", "staging-xcm-builder", @@ -2359,7 +2353,6 @@ dependencies = [ "bp-xcm-bridge-hub-router", "frame-support", "frame-system", - "hash-db", "log", "pallet-balances", "pallet-bridge-grandpa", @@ -2370,8 +2363,6 @@ dependencies = [ "pallet-utility", "parity-scale-codec", "scale-info", - "sp-api", - "sp-core", "sp-io", "sp-runtime", "sp-std 14.0.0", @@ -2619,7 +2610,6 @@ dependencies = [ "sp-genesis-builder", "sp-keyring", "sp-runtime", - "sp-std 14.0.0", "staging-chain-spec-builder", "substrate-wasm-builder", ] @@ -2765,12 +2755,12 @@ dependencies = [ [[package]] name = "clap" -version = "4.5.3" +version = "4.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "949626d00e063efc93b6dca932419ceb5432f99769911c0b995f7e884c778813" +checksum = "64acc1846d54c1fe936a78dc189c34e28d3f5afc348403f28ecf53660b9b8462" dependencies = [ "clap_builder", - "clap_derive 4.5.3", + "clap_derive 4.5.8", ] [[package]] @@ -2784,9 +2774,9 @@ dependencies = [ [[package]] name = "clap_builder" -version = "4.5.2" +version = "4.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ae129e2e766ae0ec03484e609954119f123cc1fe650337e155d03b022f24f7b4" +checksum = "6fb8393d67ba2e7bfaf28a23458e4e2b543cc73a99595511eb207fdb8aede942" dependencies = [ "anstream", "anstyle", @@ -2801,7 +2791,7 @@ version = "4.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "586a385f7ef2f8b4d86bddaa0c094794e7ccbfe5ffef1f434fe928143fc783a5" dependencies = [ - "clap 4.5.3", + "clap 4.5.9", ] [[package]] @@ -2813,19 +2803,19 @@ dependencies = [ "heck 0.4.1", "proc-macro-error", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", ] [[package]] name = "clap_derive" -version = "4.5.3" +version = "4.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90239a040c80f5e14809ca132ddc4176ab33d5e17e49691793296e3fcb34d72f" +checksum = "2bac35c6dafb060fd4d275d9a4ffae97917c13a6327903a8be2153cd964f7085" dependencies = [ "heck 0.5.0", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -2969,7 +2959,6 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std 14.0.0", "sp-storage 19.0.0", "sp-transaction-pool", "sp-version", @@ -3013,7 +3002,7 @@ checksum = "d51beaa537d73d2d1ff34ee70bc095f170420ab2ec5d687ecd3ec2b0d092514b" dependencies = [ "nom", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", ] @@ -3226,7 +3215,6 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std 14.0.0", "sp-storage 19.0.0", "sp-transaction-pool", "sp-version", @@ -3270,6 +3258,36 @@ dependencies = [ "memchr", ] +[[package]] +name = "coretime-rococo-emulated-chain" +version = "0.0.0" +dependencies = [ + "coretime-rococo-runtime", + "cumulus-primitives-core", + "emulated-integration-tests-common", + "frame-support", + "parachains-common", + "sp-core", + "testnet-parachains-constants", +] + +[[package]] +name = "coretime-rococo-integration-tests" +version = "0.1.0" +dependencies = [ + "emulated-integration-tests-common", + "frame-support", + "pallet-balances", + "pallet-identity", + "pallet-message-queue", + "polkadot-runtime-common", + "rococo-runtime-constants", + "rococo-system-emulated-network", + "sp-runtime", + "staging-xcm", + "staging-xcm-executor", +] + [[package]] name = "coretime-rococo-runtime" version = "0.1.0" @@ -3324,7 +3342,6 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std 14.0.0", "sp-storage 19.0.0", "sp-transaction-pool", "sp-version", @@ -3337,6 +3354,36 @@ dependencies = [ "xcm-runtime-apis", ] +[[package]] +name = "coretime-westend-emulated-chain" +version = "0.0.0" +dependencies = [ + "coretime-westend-runtime", + "cumulus-primitives-core", + "emulated-integration-tests-common", + "frame-support", + "parachains-common", + "sp-core", + "testnet-parachains-constants", +] + +[[package]] +name = "coretime-westend-integration-tests" +version = "0.1.0" +dependencies = [ + "emulated-integration-tests-common", + "frame-support", + "pallet-balances", + "pallet-identity", + "pallet-message-queue", + "polkadot-runtime-common", + "sp-runtime", + "staging-xcm", + "staging-xcm-executor", + "westend-runtime-constants", + "westend-system-emulated-network", +] + [[package]] name = "coretime-westend-runtime" version = "0.1.0" @@ -3389,7 +3436,6 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std 14.0.0", "sp-storage 19.0.0", "sp-transaction-pool", "sp-version", @@ -3571,7 +3617,7 @@ dependencies = [ "anes", "cast", "ciborium", - "clap 4.5.3", + "clap 4.5.9", "criterion-plot", "futures", "is-terminal", @@ -3705,7 +3751,7 @@ dependencies = [ name = "cumulus-client-cli" version = "0.7.0" dependencies = [ - "clap 4.5.3", + "clap 4.5.9", "parity-scale-codec", "sc-chain-spec", "sc-cli", @@ -3913,7 +3959,6 @@ dependencies = [ "sp-inherents", "sp-runtime", "sp-state-machine", - "sp-std 14.0.0", "sp-storage 19.0.0", "sp-trie", "tracing", @@ -4005,7 +4050,6 @@ dependencies = [ "sp-application-crypto", "sp-consensus-aura", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -4022,7 +4066,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", "sp-tracing 16.0.0", "staging-xcm", ] @@ -4082,7 +4125,7 @@ version = "0.6.0" dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -4096,7 +4139,6 @@ dependencies = [ "pallet-session", "parity-scale-codec", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -4111,7 +4153,6 @@ dependencies = [ "polkadot-primitives", "scale-info", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -4125,7 +4166,6 @@ dependencies = [ "scale-info", "sp-io", "sp-runtime", - "sp-std 14.0.0", "staging-xcm", ] @@ -4150,7 +4190,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -4167,10 +4206,27 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-runtime", - "sp-std 14.0.0", "staging-xcm", ] +[[package]] +name = "cumulus-pov-validator" +version = "0.1.0" +dependencies = [ + "anyhow", + "clap 4.5.9", + "parity-scale-codec", + "polkadot-node-primitives", + "polkadot-parachain-primitives", + "polkadot-primitives", + "sc-executor", + "sp-core", + "sp-io", + "sp-maybe-compressed-blob", + "tracing", + "tracing-subscriber 0.3.18", +] + [[package]] name = "cumulus-primitives-aura" version = "0.7.0" @@ -4181,7 +4237,6 @@ dependencies = [ "sp-api", "sp-consensus-aura", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -4195,7 +4250,6 @@ dependencies = [ "scale-info", "sp-api", "sp-runtime", - "sp-std 14.0.0", "sp-trie", "staging-xcm", ] @@ -4212,7 +4266,6 @@ dependencies = [ "sp-inherents", "sp-runtime", "sp-state-machine", - "sp-std 14.0.0", "sp-trie", ] @@ -4243,7 +4296,6 @@ dependencies = [ "scale-info", "sp-io", "sp-runtime", - "sp-std 14.0.0", "sp-trie", ] @@ -4255,7 +4307,6 @@ dependencies = [ "futures", "parity-scale-codec", "sp-inherents", - "sp-std 14.0.0", "sp-timestamp", ] @@ -4272,7 +4323,6 @@ dependencies = [ "polkadot-runtime-parachains", "sp-io", "sp-runtime", - "sp-std 14.0.0", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -4442,7 +4492,6 @@ dependencies = [ "polkadot-primitives", "sp-runtime", "sp-state-machine", - "sp-std 14.0.0", "sp-trie", ] @@ -4481,7 +4530,6 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std 14.0.0", "sp-transaction-pool", "sp-version", "staging-parachain-info", @@ -4493,7 +4541,7 @@ name = "cumulus-test-service" version = "0.1.0" dependencies = [ "async-trait", - "clap 4.5.3", + "clap 4.5.9", "criterion", "cumulus-client-cli", "cumulus-client-collator", @@ -4622,7 +4670,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "83fdaf97f4804dcebfa5862639bc9ce4121e82140bec2a987ac5140294865b5b" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -4661,7 +4709,7 @@ dependencies = [ "codespan-reporting", "once_cell", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "scratch", "syn 2.0.61", ] @@ -4679,7 +4727,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "50c49547d73ba8dcfd4ad7325d64c6d5391ff4224d498fc39a6f3f49825a530d" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -4782,7 +4830,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fcc3dd5e9e9c0b295d6e1e4d811fb6f157d5ffd784b8d202fc62eac8035a770b" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", ] @@ -4793,7 +4841,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d65d7ce8132b7c0e54497a4d9a55a1c2a0912a0d786cf894472ba818fba45762" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -4804,7 +4852,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "67e77553c4162a157adbf834ebae5b415acbecbeafc7a74b0e886657506a7611" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -4816,7 +4864,7 @@ checksum = "4fb810d30a7c1953f91334de7244731fc3f3c10d7fe163338a35b9f640960321" dependencies = [ "convert_case", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "rustc_version 0.4.0", "syn 1.0.109", ] @@ -4912,7 +4960,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "487585f4d0c6655fe74905e2504d8ad6908e4db67f744eb140876906c2f3175d" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -4972,7 +5020,7 @@ dependencies = [ "derive-syn-parse", "once_cell", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "regex", "syn 2.0.61", "termcolor", @@ -5021,7 +5069,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "558e40ea573c374cf53507fd240b7ee2f5477df7cfebdb97323ec61c719399c5" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", ] @@ -5167,7 +5215,7 @@ checksum = "c9720bba047d567ffc8a3cba48bf19126600e249ab7f128e9233e6376976a116" dependencies = [ "heck 0.4.1", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", ] @@ -5179,7 +5227,7 @@ checksum = "5ffccbb6966c05b32ef8fbac435df276c4ae4d3dc55a8cd0eb9745e6c12f546a" dependencies = [ "heck 0.4.1", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -5199,18 +5247,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e9a1f9f7d83e59740248a6e14ecf93929ade55027844dfcea78beafccc15745" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] [[package]] name = "enumn" -version = "0.1.12" +version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c2ad8cef1d801a4686bfd8919f0b30eac4c8e48968c437a6405ded4fb5272d2b" +checksum = "6fd000fd6988e73bbe993ea3db9b1aa64906ab88766d654973924340c8cddb42" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -5382,7 +5430,7 @@ checksum = "2b5fb89194fa3cad959b833185b3063ba881dbfc7030680b314250779fb4cc91" dependencies = [ "concurrent-queue", "parking", - "pin-project-lite 0.2.12", + "pin-project-lite", ] [[package]] @@ -5392,7 +5440,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0f214dc438f977e6d4e3500aaa277f5ad94ca83fbbd9b1a15713ce2344ccc5a1" dependencies = [ "event-listener 5.2.0", - "pin-project-lite 0.2.12", + "pin-project-lite", ] [[package]] @@ -5406,14 +5454,16 @@ dependencies = [ [[package]] name = "expander" -version = "2.0.0" +version = "2.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5f86a749cf851891866c10515ef6c299b5c69661465e9c3bbe7e07a2b77fb0f7" +checksum = "e2c470c71d91ecbd179935b24170459e926382eaaa86b590b78814e180d8a8e2" dependencies = [ "blake2 0.10.6", + "file-guard", "fs-err", + "prettyplease 0.2.12", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -5485,7 +5535,7 @@ dependencies = [ "indexmap 2.2.3", "proc-macro-crate 3.1.0", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -5544,6 +5594,16 @@ version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27573eac26f4dd11e2b1916c3fe1baa56407c83c71a773a8ba17ec0bca03b6b7" +[[package]] +name = "file-guard" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21ef72acf95ec3d7dbf61275be556299490a245f017cf084bd23b4f68cf9407c" +dependencies = [ + "libc", + "winapi", +] + [[package]] name = "file-per-thread-logger" version = "0.1.6" @@ -5677,9 +5737,9 @@ dependencies = [ [[package]] name = "form_urlencoded" -version = "1.2.0" +version = "1.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a62bc1cf6f830c2ec14a513a9fb124d0a213a629668a4186f329db21fe045652" +checksum = "e13624c2627564efccf4934284bdd98cbaa14e79b0b5a141218e507b3a823456" dependencies = [ "percent-encoding", ] @@ -5732,7 +5792,6 @@ dependencies = [ "sp-keystore", "sp-runtime", "sp-runtime-interface 24.0.0", - "sp-std 14.0.0", "sp-storage 19.0.0", "static_assertions", ] @@ -5744,7 +5803,7 @@ dependencies = [ "Inflector", "array-bytes", "chrono", - "clap 4.5.3", + "clap 4.5.9", "comfy-table", "frame-benchmarking", "frame-support", @@ -5797,7 +5856,6 @@ dependencies = [ "scale-info", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -5809,7 +5867,7 @@ dependencies = [ "parity-scale-codec", "proc-macro-crate 3.1.0", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "scale-info", "sp-arithmetic", "syn 2.0.61", @@ -5831,14 +5889,13 @@ dependencies = [ "sp-io", "sp-npos-elections", "sp-runtime", - "sp-std 14.0.0", ] [[package]] name = "frame-election-solution-type-fuzzer" version = "2.0.0-alpha.5" dependencies = [ - "clap 4.5.3", + "clap 4.5.9", "frame-election-provider-solution-type", "frame-election-provider-support", "frame-support", @@ -5869,7 +5926,6 @@ dependencies = [ "sp-inherents", "sp-io", "sp-runtime", - "sp-std 14.0.0", "sp-tracing 16.0.0", "sp-version", ] @@ -5911,7 +5967,7 @@ dependencies = [ name = "frame-omni-bencher" version = "0.1.0" dependencies = [ - "clap 4.5.3", + "clap 4.5.9", "cumulus-primitives-proof-size-hostfunction", "env_logger 0.11.3", "frame-benchmarking-cli", @@ -6001,7 +6057,7 @@ dependencies = [ "macro_magic", "proc-macro-warning 1.0.0", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "regex", "sp-crypto-hashing", "syn 2.0.61", @@ -6014,7 +6070,7 @@ dependencies = [ "frame-support-procedural-tools-derive", "proc-macro-crate 3.1.0", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -6023,7 +6079,7 @@ name = "frame-support-procedural-tools-derive" version = "11.0.0" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -6049,7 +6105,6 @@ dependencies = [ "sp-metadata-ir", "sp-runtime", "sp-state-machine", - "sp-std 14.0.0", "sp-version", "static_assertions", "trybuild", @@ -6124,7 +6179,6 @@ dependencies = [ "sp-externalities 0.25.0", "sp-io", "sp-runtime", - "sp-std 14.0.0", "sp-version", ] @@ -6145,7 +6199,6 @@ dependencies = [ "parity-scale-codec", "sp-api", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -6256,7 +6309,7 @@ dependencies = [ "futures-io", "memchr", "parking", - "pin-project-lite 0.2.12", + "pin-project-lite", "waker-fn", ] @@ -6267,7 +6320,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "52527eb5074e35e9339c6b4e8d12600c7128b68fb25dcb9fa9dec18f7c25f3a5" dependencies = [ "futures-core", - "pin-project-lite 0.2.12", + "pin-project-lite", ] [[package]] @@ -6277,7 +6330,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "87750cf4b7a4c0625b1529e4c543c2182106e4dedc60a2a6455e00d212c489ac" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -6322,7 +6375,7 @@ dependencies = [ "futures-sink", "futures-task", "memchr", - "pin-project-lite 0.2.12", + "pin-project-lite", "pin-utils", "slab", ] @@ -6483,7 +6536,6 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std 14.0.0", "sp-storage 19.0.0", "sp-transaction-pool", "sp-version", @@ -6781,7 +6833,7 @@ checksum = "d5f38f16d184e36f2408a55281cd658ecbd3ca05cce6d6510a176eca393e26d1" dependencies = [ "bytes", "http 0.2.9", - "pin-project-lite 0.2.12", + "pin-project-lite", ] [[package]] @@ -6804,7 +6856,7 @@ dependencies = [ "futures-util", "http 1.1.0", "http-body 1.0.0", - "pin-project-lite 0.2.12", + "pin-project-lite", ] [[package]] @@ -6841,7 +6893,7 @@ dependencies = [ "httparse", "httpdate", "itoa", - "pin-project-lite 0.2.12", + "pin-project-lite", "socket2 0.5.7", "tokio", "tower-service", @@ -6864,7 +6916,7 @@ dependencies = [ "httparse", "httpdate", "itoa", - "pin-project-lite 0.2.12", + "pin-project-lite", "smallvec", "tokio", "want", @@ -6916,7 +6968,7 @@ dependencies = [ "http 1.1.0", "http-body 1.0.0", "hyper 1.3.1", - "pin-project-lite 0.2.12", + "pin-project-lite", "socket2 0.5.7", "tokio", "tower", @@ -6968,6 +7020,16 @@ dependencies = [ "unicode-normalization", ] +[[package]] +name = "idna" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "634d9b1461af396cad843f47fdba5597a4f9e6ddd4bfb6ff5d85028c25cb12f6" +dependencies = [ + "unicode-bidi", + "unicode-normalization", +] + [[package]] name = "if-addrs" version = "0.10.2" @@ -7061,7 +7123,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "11d7a9f6330b71fea57921c9b61c47ee6e84f72d394754eff6163ae67e7395eb" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", ] @@ -7081,7 +7143,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b139284b5cf57ecfa712bcc66950bb635b31aff41c188e8a4cfc758eca374a3f" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", ] [[package]] @@ -7425,7 +7487,7 @@ dependencies = [ "heck 0.5.0", "proc-macro-crate 3.1.0", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -7622,9 +7684,9 @@ checksum = "884e2677b40cc8c339eaefcb701c32ef1fd2493d71118dc0ca4b6a736c93bd67" [[package]] name = "libc" -version = "0.2.153" +version = "0.2.155" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd" +checksum = "97b3888a4aecf77e811145cadf6eef5901f4782c53886191b2f693f24761847c" [[package]] name = "libflate" @@ -8013,7 +8075,7 @@ dependencies = [ "heck 0.4.1", "proc-macro-warning 0.4.2", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -8085,9 +8147,9 @@ dependencies = [ [[package]] name = "libp2p-websocket" -version = "0.42.1" +version = "0.42.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3facf0691bab65f571bc97c6c65ffa836248ca631d631b7691ac91deb7fceb5f" +checksum = "004ee9c4a4631435169aee6aad2f62e3984dc031c43b6d29731e8e82a016c538" dependencies = [ "either", "futures", @@ -8096,9 +8158,10 @@ dependencies = [ "libp2p-identity", "log", "parking_lot 0.12.3", - "quicksink", + "pin-project-lite", "rw-stream-sink", - "soketto 0.7.1", + "soketto 0.8.0", + "thiserror", "url", "webpki-roots 0.25.2", ] @@ -8339,9 +8402,9 @@ dependencies = [ [[package]] name = "log" -version = "0.4.21" +version = "0.4.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90ed8c1e510134f979dbc4f070f87d4313098b704861a105fe34231c70a3901c" +checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" dependencies = [ "serde", "value-bag", @@ -8426,7 +8489,7 @@ checksum = "cc33f9f0351468d26fbc53d9ce00a096c8522ecb42f19b50f34f2c422f76d21d" dependencies = [ "macro_magic_core", "macro_magic_macros", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -8440,7 +8503,7 @@ dependencies = [ "derive-syn-parse", "macro_magic_core_macros", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -8451,7 +8514,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b02abfe41815b5bd98dbd4260173db2c116dda171dc0fe7838cb206333b83308" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -8462,7 +8525,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "73ea28ee64b88876bf45277ed9a5817c1817df061a74f2b988971a12570e5869" dependencies = [ "macro_magic_core", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -8605,7 +8668,6 @@ dependencies = [ "async-std", "async-trait", "bp-messages", - "env_logger 0.11.3", "finality-relay", "futures", "hex", @@ -8656,7 +8718,7 @@ dependencies = [ name = "minimal-template-node" version = "0.0.0" dependencies = [ - "clap 4.5.3", + "clap 4.5.9", "docify", "futures", "futures-timer", @@ -8827,7 +8889,7 @@ checksum = "22ce75669015c4f47b289fd4d4f56e894e4c96003ffdf3ac51313126f94c6cbb" dependencies = [ "cfg-if", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", ] @@ -8839,7 +8901,7 @@ checksum = "af7cbce79ec385a1d4f54baa90a76401eb15d9cab93685f62e7e9f942aa00ae2" dependencies = [ "cfg-if", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -8951,7 +9013,7 @@ dependencies = [ "proc-macro-crate 1.3.1", "proc-macro-error", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", "synstructure 0.12.6", ] @@ -8999,7 +9061,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "91761aed67d03ad966ef783ae962ef9bbaca728d2dd7ceb7939ec110fffad998" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", ] @@ -9149,7 +9211,7 @@ name = "node-bench" version = "0.9.0-dev" dependencies = [ "array-bytes", - "clap 4.5.3", + "clap 4.5.9", "derive_more", "fs_extra", "futures", @@ -9228,7 +9290,7 @@ dependencies = [ name = "node-runtime-generate-bags" version = "3.0.0" dependencies = [ - "clap 4.5.3", + "clap 4.5.9", "generate-bags", "kitchensink-runtime", ] @@ -9237,7 +9299,7 @@ dependencies = [ name = "node-template-release" version = "3.0.0" dependencies = [ - "clap 4.5.3", + "clap 4.5.9", "flate2", "fs_extra", "glob", @@ -9386,7 +9448,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -9553,7 +9615,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -9593,9 +9655,9 @@ checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" [[package]] name = "orchestra" -version = "0.3.6" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "92829eef0328a3d1cd22a02c0e51deb92a5362df3e7d21a4e9bdc38934694e66" +checksum = "41f6bbacc8c189a3f2e45e0fd0436e5d97f194db888e721bdbc3973e7dbed4c2" dependencies = [ "async-trait", "dyn-clonable", @@ -9610,9 +9672,9 @@ dependencies = [ [[package]] name = "orchestra-proc-macro" -version = "0.3.6" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1344346d5af32c95bbddea91b18a88cc83eac394192d20ef2fc4c40a74332355" +checksum = "f7b1d40dd8f367db3c65bec8d3dd47d4a604ee8874480738f93191bddab4e0e0" dependencies = [ "expander", "indexmap 2.2.3", @@ -9620,7 +9682,7 @@ dependencies = [ "petgraph", "proc-macro-crate 3.1.0", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", ] @@ -9669,7 +9731,6 @@ dependencies = [ "sp-crypto-hashing", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -9690,7 +9751,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -9711,7 +9771,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -9729,7 +9788,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", "sp-storage 19.0.0", ] @@ -9746,7 +9804,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -9767,7 +9824,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", "sp-storage 19.0.0", ] @@ -9818,7 +9874,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -9836,7 +9891,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -9853,7 +9907,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -9868,7 +9921,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -9896,7 +9948,6 @@ dependencies = [ "sp-runtime", "sp-session", "sp-staking", - "sp-std 14.0.0", ] [[package]] @@ -9916,7 +9967,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", "sp-tracing 16.0.0", ] @@ -9964,7 +10014,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -9992,7 +10041,6 @@ dependencies = [ "sp-session", "sp-staking", "sp-state-machine", - "sp-std 14.0.0", ] [[package]] @@ -10017,7 +10065,6 @@ dependencies = [ "sp-runtime", "sp-staking", "sp-state-machine", - "sp-std 14.0.0", ] [[package]] @@ -10035,7 +10082,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -10069,7 +10115,6 @@ dependencies = [ "bp-header-chain", "bp-runtime", "bp-test-utils", - "finality-grandpa", "frame-benchmarking", "frame-support", "frame-system", @@ -10081,13 +10126,13 @@ dependencies = [ "sp-io", "sp-runtime", "sp-std 14.0.0", - "sp-trie", ] [[package]] name = "pallet-bridge-messages" version = "0.7.0" dependencies = [ + "bp-header-chain", "bp-messages", "bp-runtime", "bp-test-utils", @@ -10095,13 +10140,15 @@ dependencies = [ "frame-support", "frame-system", "log", - "num-traits", "pallet-balances", + "pallet-bridge-grandpa", "parity-scale-codec", "scale-info", + "sp-core", "sp-io", "sp-runtime", "sp-std 14.0.0", + "sp-trie", ] [[package]] @@ -10124,7 +10171,6 @@ dependencies = [ "sp-io", "sp-runtime", "sp-std 14.0.0", - "sp-trie", ] [[package]] @@ -10165,7 +10211,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", "sp-tracing 16.0.0", ] @@ -10185,7 +10230,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -10209,7 +10253,6 @@ dependencies = [ "sp-io", "sp-runtime", "sp-staking", - "sp-std 14.0.0", "sp-tracing 16.0.0", ] @@ -10226,7 +10269,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -10241,7 +10283,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -10334,7 +10375,6 @@ dependencies = [ "sp-io", "sp-keystore", "sp-runtime", - "sp-std 14.0.0", "sp-tracing 16.0.0", "staging-xcm", "staging-xcm-builder", @@ -10347,7 +10387,7 @@ name = "pallet-contracts-proc-macro" version = "18.0.0" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -10378,7 +10418,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -10396,7 +10435,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -10410,7 +10448,6 @@ dependencies = [ "scale-info", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -10431,7 +10468,6 @@ dependencies = [ "sp-io", "sp-runtime", "sp-staking", - "sp-std 14.0.0", "sp-tracing 16.0.0", "substrate-test-utils", ] @@ -10453,7 +10489,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -10469,7 +10504,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -10519,7 +10553,6 @@ dependencies = [ "sp-io", "sp-npos-elections", "sp-runtime", - "sp-std 14.0.0", "sp-tracing 16.0.0", "strum 0.26.2", ] @@ -10534,7 +10567,6 @@ dependencies = [ "parity-scale-codec", "sp-npos-elections", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -10553,7 +10585,6 @@ dependencies = [ "sp-npos-elections", "sp-runtime", "sp-staking", - "sp-std 14.0.0", "sp-tracing 16.0.0", "substrate-test-utils", ] @@ -10572,7 +10603,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -10598,7 +10628,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -10629,7 +10658,6 @@ dependencies = [ "sp-io", "sp-keystore", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -10648,7 +10676,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", "sp-version", ] @@ -10664,7 +10691,6 @@ dependencies = [ "scale-info", "sp-core", "sp-io", - "sp-std 14.0.0", ] [[package]] @@ -10680,7 +10706,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -10718,7 +10743,6 @@ dependencies = [ "sp-io", "sp-runtime", "sp-staking", - "sp-std 14.0.0", "sp-tracing 16.0.0", "substrate-test-utils", ] @@ -10739,7 +10763,6 @@ dependencies = [ "sp-inherents", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -10769,7 +10792,6 @@ dependencies = [ "sp-runtime", "sp-session", "sp-staking", - "sp-std 14.0.0", ] [[package]] @@ -10788,7 +10810,6 @@ dependencies = [ "sp-io", "sp-keystore", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -10808,7 +10829,6 @@ dependencies = [ "sp-io", "sp-runtime", "sp-staking", - "sp-std 14.0.0", ] [[package]] @@ -10825,7 +10845,6 @@ dependencies = [ "sp-io", "sp-keyring", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -10840,7 +10859,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -10857,7 +10875,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -10873,7 +10890,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -10895,7 +10911,6 @@ dependencies = [ "sp-crypto-hashing", "sp-io", "sp-runtime", - "sp-std 14.0.0", "sp-tracing 16.0.0", "sp-weights", ] @@ -10919,7 +10934,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", "sp-tracing 16.0.0", "sp-version", ] @@ -10949,7 +10963,6 @@ dependencies = [ "sp-io", "sp-mixnet", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -10969,7 +10982,6 @@ dependencies = [ "sp-io", "sp-mmr-primitives", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -10985,7 +10997,6 @@ dependencies = [ "scale-info", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -11023,7 +11034,6 @@ dependencies = [ "sp-io", "sp-keystore", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -11033,7 +11043,6 @@ dependencies = [ "pallet-nfts", "parity-scale-codec", "sp-api", - "sp-std 14.0.0", ] [[package]] @@ -11050,7 +11059,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -11065,7 +11073,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -11082,7 +11089,6 @@ dependencies = [ "sp-io", "sp-runtime", "sp-staking", - "sp-std 14.0.0", "sp-tracing 16.0.0", ] @@ -11108,7 +11114,6 @@ dependencies = [ "sp-runtime", "sp-runtime-interface 24.0.0", "sp-staking", - "sp-std 14.0.0", ] [[package]] @@ -11133,7 +11138,6 @@ dependencies = [ "pallet-nomination-pools", "parity-scale-codec", "sp-api", - "sp-std 14.0.0", ] [[package]] @@ -11200,7 +11204,6 @@ dependencies = [ "sp-io", "sp-runtime", "sp-staking", - "sp-std 14.0.0", ] [[package]] @@ -11227,7 +11230,6 @@ dependencies = [ "sp-io", "sp-runtime", "sp-staking", - "sp-std 14.0.0", ] [[package]] @@ -11244,7 +11246,6 @@ dependencies = [ "sp-io", "sp-metadata-ir", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -11270,7 +11271,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -11290,7 +11290,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -11307,7 +11306,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -11324,7 +11322,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -11342,7 +11339,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -11358,7 +11354,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -11380,7 +11375,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -11396,7 +11390,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -11431,7 +11424,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -11451,7 +11443,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -11469,7 +11460,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -11488,7 +11478,6 @@ dependencies = [ "sp-crypto-hashing", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -11506,7 +11495,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", "sp-weights", "substrate-test-utils", ] @@ -11523,7 +11511,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -11543,7 +11530,6 @@ dependencies = [ "sp-session", "sp-staking", "sp-state-machine", - "sp-std 14.0.0", "sp-trie", ] @@ -11567,7 +11553,6 @@ dependencies = [ "sp-io", "sp-runtime", "sp-session", - "sp-std 14.0.0", ] [[package]] @@ -11579,7 +11564,6 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -11600,7 +11584,6 @@ dependencies = [ "sp-crypto-hashing", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -11628,7 +11611,6 @@ dependencies = [ "sp-npos-elections", "sp-runtime", "sp-staking", - "sp-std 14.0.0", "sp-tracing 16.0.0", "substrate-test-utils", ] @@ -11639,7 +11621,7 @@ version = "11.0.0" dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "sp-runtime", "syn 2.0.61", ] @@ -11678,7 +11660,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", "sp-tracing 16.0.0", "substrate-state-trie-migration-rpc", "thousands", @@ -11701,7 +11682,6 @@ dependencies = [ "sp-io", "sp-runtime", "sp-statement-store", - "sp-std 14.0.0", ] [[package]] @@ -11717,7 +11697,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -11749,7 +11728,6 @@ dependencies = [ "sp-inherents", "sp-io", "sp-runtime", - "sp-std 14.0.0", "sp-storage 19.0.0", "sp-timestamp", ] @@ -11770,7 +11748,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", "sp-storage 19.0.0", ] @@ -11788,7 +11765,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -11834,7 +11810,6 @@ dependencies = [ "sp-inherents", "sp-io", "sp-runtime", - "sp-std 14.0.0", "sp-transaction-storage-proof", ] @@ -11855,7 +11830,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -11874,7 +11848,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -11910,7 +11883,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -11927,7 +11899,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -11945,7 +11916,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -11967,7 +11937,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -11991,7 +11960,6 @@ dependencies = [ "scale-info", "sp-io", "sp-runtime", - "sp-std 14.0.0", "sp-tracing 16.0.0", "staging-xcm", "staging-xcm-builder", @@ -12046,7 +12014,7 @@ dependencies = [ name = "parachain-template-node" version = "0.0.0" dependencies = [ - "clap 4.5.3", + "clap 4.5.9", "color-print", "cumulus-client-cli", "cumulus-client-collator", @@ -12152,7 +12120,6 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std 14.0.0", "sp-transaction-pool", "sp-version", "staging-parachain-info", @@ -12185,7 +12152,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", "staging-parachain-info", "staging-xcm", "staging-xcm-executor", @@ -12230,7 +12196,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", "sp-tracing 16.0.0", "staging-parachain-info", "staging-xcm", @@ -12300,7 +12265,7 @@ checksum = "d830939c76d294956402033aee57a6da7b438f2294eb94864c37b0569053a42c" dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", ] @@ -12412,9 +12377,9 @@ dependencies = [ [[package]] name = "paste" -version = "1.0.14" +version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "de3145af08024dea9fa9914f381a17b8fc6034dfb00f3a84013f7ff43f29ed4c" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" [[package]] name = "pbkdf2" @@ -12504,7 +12469,6 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std 14.0.0", "sp-storage 19.0.0", "sp-transaction-pool", "sp-version", @@ -12602,7 +12566,6 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std 14.0.0", "sp-storage 19.0.0", "sp-transaction-pool", "sp-version", @@ -12700,7 +12663,6 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std 14.0.0", "sp-storage 19.0.0", "sp-transaction-pool", "sp-version", @@ -12716,9 +12678,9 @@ dependencies = [ [[package]] name = "percent-encoding" -version = "2.3.0" +version = "2.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9b2a4787296e9989611394c33f193f676704af1686e70b8f8033ab5ba9a35a94" +checksum = "e3148f5046208a5d56bcfc03053e3ca6334e51da8dfb19b6cdc8b306fae3283e" [[package]] name = "pest" @@ -12749,7 +12711,7 @@ dependencies = [ "pest", "pest_meta", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -12790,21 +12752,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4359fd9c9171ec6e8c62926d6faaf553a8dc3f64e1507e76da7911b4f6a04405" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] [[package]] name = "pin-project-lite" -version = "0.1.12" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "257b64915a082f7811703966789728173279bdebb956b143dbcd23f6f970a777" - -[[package]] -name = "pin-project-lite" -version = "0.2.12" +version = "0.2.14" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12cc1b0bf1727a77a54b6654e7b5f1af8604923edc8b81885f8ec92f9e3f0a05" +checksum = "bda66fc9667c18cb2758a2ac84d1167245054bcf85d5d1aaa6923f45801bdd02" [[package]] name = "pin-utils" @@ -13018,7 +12974,7 @@ name = "polkadot-cli" version = "7.0.0" dependencies = [ "cfg-if", - "clap 4.5.3", + "clap 4.5.9", "frame-benchmarking-cli", "futures", "log", @@ -13081,7 +13037,6 @@ dependencies = [ "scale-info", "sp-core", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -13877,7 +13832,7 @@ dependencies = [ "async-trait", "bridge-hub-rococo-runtime", "bridge-hub-westend-runtime", - "clap 4.5.3", + "clap 4.5.9", "collectives-westend-runtime", "color-print", "contracts-rococo-runtime", @@ -13894,6 +13849,7 @@ dependencies = [ "cumulus-primitives-aura", "cumulus-primitives-core", "cumulus-relay-chain-interface", + "docify", "frame-benchmarking", "frame-benchmarking-cli", "frame-support", @@ -13976,7 +13932,6 @@ dependencies = [ "serde", "sp-core", "sp-runtime", - "sp-std 14.0.0", "sp-weights", ] @@ -14003,7 +13958,6 @@ dependencies = [ "sp-keystore", "sp-runtime", "sp-staking", - "sp-std 14.0.0", ] [[package]] @@ -14101,7 +14055,6 @@ dependencies = [ "sp-runtime", "sp-session", "sp-staking", - "sp-std 14.0.0", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", @@ -14116,7 +14069,6 @@ dependencies = [ "frame-benchmarking", "parity-scale-codec", "polkadot-primitives", - "sp-std 14.0.0", "sp-tracing 16.0.0", ] @@ -14142,6 +14094,7 @@ dependencies = [ "pallet-balances", "pallet-broker", "pallet-message-queue", + "pallet-mmr", "pallet-session", "pallet-staking", "pallet-timestamp", @@ -14677,7 +14630,6 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std 14.0.0", "sp-storage 19.0.0", "sp-transaction-pool", "sp-version", @@ -14864,7 +14816,7 @@ dependencies = [ "async-trait", "bincode", "bitvec", - "clap 4.5.3", + "clap 4.5.9", "clap-num", "color-eyre", "colored", @@ -14962,7 +14914,7 @@ version = "1.0.0" dependencies = [ "assert_matches", "async-trait", - "clap 4.5.3", + "clap 4.5.9", "color-eyre", "futures", "futures-timer", @@ -15037,7 +14989,6 @@ dependencies = [ "sp-runtime", "sp-session", "sp-staking", - "sp-std 14.0.0", "sp-transaction-pool", "sp-trie", "sp-version", @@ -15105,7 +15056,7 @@ dependencies = [ name = "polkadot-voter-bags" version = "7.0.0" dependencies = [ - "clap 4.5.3", + "clap 4.5.9", "generate-bags", "sp-io", "westend-runtime", @@ -15159,7 +15110,7 @@ checksum = "5c4fdfc49717fb9a196e74a5d28e0bc764eb394a2c803eb11133a31ac996c60c" dependencies = [ "polkavm-common", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -15206,7 +15157,7 @@ dependencies = [ "concurrent-queue", "libc", "log", - "pin-project-lite 0.2.12", + "pin-project-lite", "windows-sys 0.48.0", ] @@ -15218,7 +15169,7 @@ checksum = "30054e72317ab98eddd8561db0f6524df3367636884b7b21b703e4b280a84a14" dependencies = [ "cfg-if", "concurrent-queue", - "pin-project-lite 0.2.12", + "pin-project-lite", "rustix 0.38.21", "tracing", "windows-sys 0.52.0", @@ -15418,7 +15369,7 @@ checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" dependencies = [ "proc-macro-error-attr", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", "version_check", ] @@ -15430,7 +15381,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "version_check", ] @@ -15447,7 +15398,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d1eaa7fa0aa1929ffdf7eeb6eac234dde6268914a14ad44d23521ab6a9b258e" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -15458,7 +15409,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b698b0b09d40e9b7c1a47b132d66a8b54bcd20583d9b6d06e4535e383b4405c" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -15539,7 +15490,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "440f724eba9f6996b75d63681b0a92b06947f1457076d503a4d2e2c8f56442b8" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -15647,7 +15598,7 @@ dependencies = [ "anyhow", "itertools 0.10.5", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", ] @@ -15660,7 +15611,7 @@ dependencies = [ "anyhow", "itertools 0.11.0", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -15787,17 +15738,6 @@ dependencies = [ "rand", ] -[[package]] -name = "quicksink" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77de3c815e5a160b1539c6592796801df2043ae35e123b46d73380cfa57af858" -dependencies = [ - "futures-core", - "futures-sink", - "pin-project-lite 0.1.12", -] - [[package]] name = "quinn" version = "0.9.4" @@ -15805,7 +15745,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2e8b432585672228923edbbf64b8b12c14e1112f62e88737655b4a083dbcd78e" dependencies = [ "bytes", - "pin-project-lite 0.2.12", + "pin-project-lite", "quinn-proto 0.9.6", "quinn-udp 0.3.2", "rustc-hash", @@ -15824,7 +15764,7 @@ checksum = "8cc2c5017e4b43d5995dcea317bc46c1e09404c0a9664d2908f7f02dfe943d75" dependencies = [ "bytes", "futures-io", - "pin-project-lite 0.2.12", + "pin-project-lite", "quinn-proto 0.10.6", "quinn-udp 0.4.1", "rustc-hash", @@ -15906,9 +15846,9 @@ dependencies = [ [[package]] name = "quote" -version = "1.0.35" +version = "1.0.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" +checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" dependencies = [ "proc-macro2 1.0.82", ] @@ -16110,7 +16050,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7f7473c2cfcf90008193dd0e3e16599455cb601a9fce322b5bb55de799664925" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -16207,13 +16147,10 @@ dependencies = [ "bp-runtime", "finality-relay", "frame-support", - "frame-system", "futures", "jsonrpsee", "log", "num-traits", - "pallet-balances", - "pallet-bridge-messages", "pallet-transaction-payment", "pallet-transaction-payment-rpc-runtime-api", "pallet-utility", @@ -16268,7 +16205,7 @@ dependencies = [ name = "remote-ext-tests-bags-list" version = "1.0.0" dependencies = [ - "clap 4.5.3", + "clap 4.5.9", "frame-system", "log", "pallet-bags-list-remote-tests", @@ -16301,7 +16238,7 @@ dependencies = [ "mime", "once_cell", "percent-encoding", - "pin-project-lite 0.2.12", + "pin-project-lite", "rustls 0.21.7", "rustls-pemfile 1.0.3", "serde", @@ -16466,7 +16403,6 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std 14.0.0", "sp-transaction-pool", "sp-version", "staging-parachain-info", @@ -16568,7 +16504,6 @@ dependencies = [ "sp-runtime", "sp-session", "sp-staking", - "sp-std 14.0.0", "sp-storage 19.0.0", "sp-tracing 16.0.0", "sp-transaction-pool", @@ -16605,6 +16540,7 @@ version = "0.0.0" dependencies = [ "asset-hub-rococo-emulated-chain", "bridge-hub-rococo-emulated-chain", + "coretime-rococo-emulated-chain", "emulated-integration-tests-common", "penpal-emulated-chain", "people-rococo-emulated-chain", @@ -16663,7 +16599,7 @@ dependencies = [ "cfg-if", "glob", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "regex", "relative-path", "rustc_version 0.4.0", @@ -17118,7 +17054,7 @@ name = "sc-chain-spec" version = "28.0.0" dependencies = [ "array-bytes", - "clap 4.5.3", + "clap 4.5.9", "docify", "log", "memmap2 0.9.3", @@ -17151,7 +17087,7 @@ version = "11.0.0" dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -17161,7 +17097,7 @@ version = "0.36.0" dependencies = [ "array-bytes", "chrono", - "clap 4.5.3", + "clap 4.5.9", "fdlimit", "futures", "futures-timer", @@ -18207,7 +18143,6 @@ dependencies = [ "sp-io", "sp-runtime", "sp-runtime-interface 24.0.0", - "sp-std 14.0.0", "substrate-wasm-builder", ] @@ -18346,7 +18281,7 @@ dependencies = [ name = "sc-storage-monitor" version = "0.16.0" dependencies = [ - "clap 4.5.3", + "clap 4.5.9", "fs4", "log", "sp-core", @@ -18448,7 +18383,7 @@ version = "11.0.0" dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -18562,7 +18497,7 @@ checksum = "2d35494501194174bda522a32605929eefc9ecf7e0a326c26db1fdd85881eb62" dependencies = [ "proc-macro-crate 3.1.0", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", ] @@ -18600,7 +18535,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0f696e21e10fa546b7ffb1c9672c6de8fbc7a81acf59524386d8639bf12737" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "serde_derive_internals", "syn 1.0.109", ] @@ -18797,7 +18732,6 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std 14.0.0", "sp-transaction-pool", "sp-version", "staging-parachain-info", @@ -18869,9 +18803,9 @@ checksum = "f97841a747eef040fcd2e7b3b9a220a7205926e60488e673d9e4926d27772ce5" [[package]] name = "serde" -version = "1.0.197" +version = "1.0.204" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3fb1c873e1b9b056a4dc4c0c198b24c3ffa059243875552b2bd0933b1aee4ce2" +checksum = "bc76f558e0cbb2a839d37354c575f1dc3fdc6546b5be373ba43d95f231bf7c12" dependencies = [ "serde_derive", ] @@ -18896,12 +18830,12 @@ dependencies = [ [[package]] name = "serde_derive" -version = "1.0.197" +version = "1.0.204" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b" +checksum = "e0cd7e117be63d3c3678776753929474f3b04a43a080c744d6b0ae2a8c28e222" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -18912,7 +18846,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85bf8229e7920a9f636479437026331ce11aa132b4dde37d121944a44d6e5f3c" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", ] @@ -18927,9 +18861,9 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.114" +version = "1.0.120" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c5f09b1bd632ef549eaa9f60a1f8de742bdbc698e6cee2095fc84dde5f549ae0" +checksum = "4e0d21c9a8cae1235ad58a00c11cb40d4b1e5c784f1ef2c537876ed6ffd8b7c5" dependencies = [ "indexmap 2.2.3", "itoa", @@ -18960,9 +18894,9 @@ dependencies = [ [[package]] name = "serde_yaml" -version = "0.9.33" +version = "0.9.34+deprecated" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a0623d197252096520c6f2a5e1171ee436e5af99a5d7caa2891e55e61950e6d9" +checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" dependencies = [ "indexmap 2.2.3", "itoa", @@ -19002,7 +18936,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "91d129178576168c589c9ec973feedf7d3126c01ac2bf08795109aa35b69fb8f" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -19121,7 +19055,6 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std 14.0.0", "sp-transaction-pool", "sp-version", "staging-parachain-info", @@ -19228,7 +19161,6 @@ dependencies = [ "parity-scale-codec", "paste", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -19771,7 +19703,7 @@ dependencies = [ name = "solochain-template-node" version = "0.0.0" dependencies = [ - "clap 4.5.3", + "clap 4.5.9", "frame-benchmarking-cli", "frame-system", "futures", @@ -19837,7 +19769,6 @@ dependencies = [ "sp-offchain", "sp-runtime", "sp-session", - "sp-std 14.0.0", "sp-storage 19.0.0", "sp-transaction-pool", "sp-version", @@ -19860,7 +19791,6 @@ dependencies = [ "sp-runtime", "sp-runtime-interface 24.0.0", "sp-state-machine", - "sp-std 14.0.0", "sp-test-primitives", "sp-trie", "sp-version", @@ -19877,7 +19807,7 @@ dependencies = [ "expander", "proc-macro-crate 3.1.0", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -19913,7 +19843,6 @@ dependencies = [ "serde", "sp-core", "sp-io", - "sp-std 14.0.0", ] [[package]] @@ -19941,7 +19870,6 @@ dependencies = [ "scale-info", "serde", "sp-crypto-hashing", - "sp-std 14.0.0", "static_assertions", ] @@ -19999,7 +19927,6 @@ name = "sp-blockchain" version = "28.0.0" dependencies = [ "futures", - "log", "parity-scale-codec", "parking_lot 0.12.3", "schnellru", @@ -20010,6 +19937,7 @@ dependencies = [ "sp-runtime", "sp-state-machine", "thiserror", + "tracing", ] [[package]] @@ -20262,7 +20190,7 @@ dependencies = [ name = "sp-crypto-hashing-proc-macro" version = "0.1.0" dependencies = [ - "quote 1.0.35", + "quote 1.0.36", "sp-crypto-hashing", "syn 2.0.61", ] @@ -20281,7 +20209,7 @@ version = "8.0.0" source = "git+https://github.com/paritytech/polkadot-sdk#82912acb33a9030c0ef3bf590a34fca09b72dc5f" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -20290,7 +20218,7 @@ name = "sp-debug-derive" version = "14.0.0" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -20357,7 +20285,6 @@ dependencies = [ "sp-keystore", "sp-runtime-interface 24.0.0", "sp-state-machine", - "sp-std 14.0.0", "sp-tracing 16.0.0", "sp-trie", "tracing", @@ -20447,7 +20374,7 @@ dependencies = [ name = "sp-npos-elections-fuzzer" version = "2.0.0-alpha.5" dependencies = [ - "clap 4.5.3", + "clap 4.5.9", "honggfuzz", "rand", "sp-npos-elections", @@ -20563,7 +20490,7 @@ dependencies = [ "Inflector", "proc-macro-crate 1.3.1", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -20575,7 +20502,7 @@ dependencies = [ "expander", "proc-macro-crate 3.1.0", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -20603,7 +20530,6 @@ dependencies = [ "sp-core", "sp-io", "sp-runtime-interface 24.0.0", - "sp-std 14.0.0", "substrate-wasm-builder", ] @@ -20837,7 +20763,7 @@ version = "13.0.0" dependencies = [ "parity-scale-codec", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "sp-version", "syn 2.0.61", ] @@ -20922,7 +20848,7 @@ dependencies = [ "Inflector", "num-format", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "serde", "serde_json", "unicode-xid 0.2.4", @@ -20947,7 +20873,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f07d54c4d01a1713eb363b55ba51595da15f6f1211435b71466460da022aa140" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", ] @@ -20961,7 +20887,7 @@ checksum = "a8f112729512f8e442d81f95a8a7ddf2b7c6b8a1a6f509a95864142b30cab2d3" name = "staging-chain-spec-builder" version = "1.6.1" dependencies = [ - "clap 4.5.3", + "clap 4.5.9", "log", "sc-chain-spec", "serde_json", @@ -20974,7 +20900,7 @@ version = "3.0.0-dev" dependencies = [ "array-bytes", "assert_cmd", - "clap 4.5.3", + "clap 4.5.9", "clap_complete", "criterion", "futures", @@ -20988,6 +20914,7 @@ dependencies = [ "parity-scale-codec", "platforms", "polkadot-sdk", + "pretty_assertions", "rand", "regex", "sc-service-test", @@ -21008,7 +20935,7 @@ dependencies = [ name = "staging-node-inspect" version = "0.12.0" dependencies = [ - "clap 4.5.3", + "clap 4.5.9", "parity-scale-codec", "sc-cli", "sc-client-api", @@ -21031,7 +20958,6 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-runtime", - "sp-std 14.0.0", ] [[package]] @@ -21055,6 +20981,7 @@ dependencies = [ "schemars", "serde", "sp-io", + "sp-runtime", "sp-weights", "xcm-procedural", ] @@ -21083,7 +21010,6 @@ dependencies = [ "sp-arithmetic", "sp-io", "sp-runtime", - "sp-std 14.0.0", "sp-weights", "staging-xcm", "staging-xcm-executor", @@ -21097,16 +21023,15 @@ dependencies = [ "frame-benchmarking", "frame-support", "impl-trait-for-tuples", - "log", "parity-scale-codec", "scale-info", "sp-arithmetic", "sp-core", "sp-io", "sp-runtime", - "sp-std 14.0.0", "sp-weights", "staging-xcm", + "tracing", ] [[package]] @@ -21139,7 +21064,7 @@ dependencies = [ "cfg_aliases", "memchr", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", ] @@ -21212,7 +21137,7 @@ dependencies = [ "heck 0.3.3", "proc-macro-error", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", ] @@ -21248,7 +21173,7 @@ checksum = "1e385be0d24f186b4ce2f9982191e7101bb737312ad61c1f2f984f34bcf85d59" dependencies = [ "heck 0.4.1", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "rustversion", "syn 1.0.109", ] @@ -21261,7 +21186,7 @@ checksum = "23dc1fa9ac9c169a78ba62f0b841814b7abae11bdd047b9c58f893439e309ea0" dependencies = [ "heck 0.4.1", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "rustversion", "syn 2.0.61", ] @@ -21274,7 +21199,7 @@ checksum = "c6cf59daf282c0a494ba14fd21610a0325f9f90ec9d1231dea26bcb1d696c946" dependencies = [ "heck 0.4.1", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "rustversion", "syn 2.0.61", ] @@ -21283,7 +21208,7 @@ dependencies = [ name = "subkey" version = "9.0.0" dependencies = [ - "clap 4.5.3", + "clap 4.5.9", "sc-cli", ] @@ -21388,9 +21313,7 @@ dependencies = [ "bp-polkadot-core", "bp-relayers", "bp-runtime", - "bridge-runtime-common", "equivocation-detector", - "finality-grandpa", "finality-relay", "frame-support", "frame-system", @@ -21410,9 +21333,11 @@ dependencies = [ "rbtag", "relay-substrate-client", "relay-utils", + "scale-info", "sp-consensus-grandpa", "sp-core", "sp-runtime", + "sp-trie", "structopt", "strum 0.26.2", "thiserror", @@ -21723,7 +21648,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "unicode-ident", ] @@ -21734,7 +21659,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c993ed8ccba56ae856363b1845da7266a7cb78e1d146c8a32d54b45a8b831fc9" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "unicode-ident", ] @@ -21746,7 +21671,7 @@ checksum = "86b837ef12ab88835251726eb12237655e61ec8dc8a280085d1961cdc3dfd047" dependencies = [ "paste", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -21757,7 +21682,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f36bdaa60a83aca3921b5259d5400cbf5e90fc51931376a9bd4a0eb79aa7210f" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", "unicode-xid 0.2.4", ] @@ -21769,7 +21694,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c8af7666ab7b6390ab78131fb5b0fce11d6b7a6951602017c35fa82800708971" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -21888,7 +21813,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5999e24eaa32083191ba4e425deb75cdf25efefabe5aaccb7446dd0d4122a3f5" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -21900,7 +21825,6 @@ dependencies = [ "parity-scale-codec", "polkadot-parachain-primitives", "sp-io", - "sp-std 14.0.0", "substrate-wasm-builder", "tiny-keccak", ] @@ -21909,7 +21833,7 @@ dependencies = [ name = "test-parachain-adder-collator" version = "1.0.0" dependencies = [ - "clap 4.5.3", + "clap 4.5.9", "futures", "futures-timer", "log", @@ -21948,7 +21872,6 @@ dependencies = [ "parity-scale-codec", "polkadot-parachain-primitives", "sp-io", - "sp-std 14.0.0", "substrate-wasm-builder", "tiny-keccak", ] @@ -21957,7 +21880,7 @@ dependencies = [ name = "test-parachain-undying-collator" version = "1.0.0" dependencies = [ - "clap 4.5.3", + "clap 4.5.9", "futures", "futures-timer", "log", @@ -22054,7 +21977,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "10ac1c5050e43014d16b2f94d0d2ce79e65ffdd8b38d8048f9c8f6a8a6da62ac" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 1.0.109", ] @@ -22065,7 +21988,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "46c3384250002a6d5af4d114f2845d37b57521033f30d5c3f46c4d70e1197533" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -22214,7 +22137,7 @@ dependencies = [ "mio", "num_cpus", "parking_lot 0.12.3", - "pin-project-lite 0.2.12", + "pin-project-lite", "signal-hook-registry", "socket2 0.5.7", "tokio-macros", @@ -22228,7 +22151,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b8a1e28f2deaa14e508979454cb3a223b10b938b45af148bc0986de36f1923b" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -22271,7 +22194,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "397c988d37662c7dda6d2208364a706264bf3d6138b11d436cbac0ad38832842" dependencies = [ "futures-core", - "pin-project-lite 0.2.12", + "pin-project-lite", "tokio", "tokio-util", ] @@ -22314,7 +22237,7 @@ dependencies = [ "futures-core", "futures-io", "futures-sink", - "pin-project-lite 0.2.12", + "pin-project-lite", "tokio", ] @@ -22381,7 +22304,7 @@ dependencies = [ "futures-core", "futures-util", "pin-project", - "pin-project-lite 0.2.12", + "pin-project-lite", "tokio", "tower-layer", "tower-service", @@ -22399,7 +22322,7 @@ dependencies = [ "http 1.1.0", "http-body 1.0.0", "http-body-util", - "pin-project-lite 0.2.12", + "pin-project-lite", "tower-layer", "tower-service", ] @@ -22423,7 +22346,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3523ab5a71916ccf420eebdf5521fcef02141234bbc0b8a49f2fdc4544364ef" dependencies = [ "log", - "pin-project-lite 0.2.12", + "pin-project-lite", "tracing-attributes", "tracing-core", ] @@ -22435,7 +22358,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34704c8d6ebcbc939824180af020566b01a7c01f80641264eba0999f6c2b6be7" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -22477,7 +22400,7 @@ dependencies = [ "expander", "proc-macro-crate 3.1.0", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -22867,12 +22790,12 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.4.0" +version = "2.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "50bff7831e19200a85b17131d085c25d7811bc4e186efdaf54bbd132994a88cb" +checksum = "22784dbdf76fdde8af1aeda5622b546b422b6fc585325248a2bf9f5e41e94d6c" dependencies = [ "form_urlencoded", - "idna 0.4.0", + "idna 0.5.0", "percent-encoding", ] @@ -23026,9 +22949,9 @@ checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" -version = "0.2.87" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7706a72ab36d8cb1f80ffbf0e071533974a60d0a308d01a5d0375bf60499a342" +checksum = "4be2531df63900aeb2bca0daaaddec08491ee64ceecbee5076636a3b026795a8" dependencies = [ "cfg-if", "serde", @@ -23038,15 +22961,15 @@ dependencies = [ [[package]] name = "wasm-bindgen-backend" -version = "0.2.87" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ef2b6d3c510e9625e5fe6f509ab07d66a760f0885d858736483c32ed7809abd" +checksum = "614d787b966d3989fa7bb98a654e369c762374fd3213d212cfc0251257e747da" dependencies = [ "bumpalo", "log", "once_cell", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", "wasm-bindgen-shared", ] @@ -23065,22 +22988,22 @@ dependencies = [ [[package]] name = "wasm-bindgen-macro" -version = "0.2.87" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dee495e55982a3bd48105a7b947fd2a9b4a8ae3010041b9e0faab3f9cd028f1d" +checksum = "a1f8823de937b71b9460c0c34e25f3da88250760bec0ebac694b49997550d726" dependencies = [ - "quote 1.0.35", + "quote 1.0.36", "wasm-bindgen-macro-support", ] [[package]] name = "wasm-bindgen-macro-support" -version = "0.2.87" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "54681b18a46765f095758388f2d0cf16eb8d4169b639ab575a8f5693af210c7b" +checksum = "e94f17b526d0a461a191c78ea52bbce64071ed5c04c9ffe424dcb38f74171bb7" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", "wasm-bindgen-backend", "wasm-bindgen-shared", @@ -23088,9 +23011,9 @@ dependencies = [ [[package]] name = "wasm-bindgen-shared" -version = "0.2.87" +version = "0.2.92" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ca6ad05a4870b2bf5fe995117d3728437bd27d7cd5f06f13c17443ef369775a1" +checksum = "af190c94f2773fdb3729c55b007a722abb5384da03bc0986df4c289bf5567e96" [[package]] name = "wasm-bindgen-test" @@ -23113,7 +23036,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ecb993dd8c836930ed130e020e77d9b2e65dd0fbab1b67c790b0f5d80b11a575" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", ] [[package]] @@ -23647,7 +23570,6 @@ dependencies = [ "sp-runtime", "sp-session", "sp-staking", - "sp-std 14.0.0", "sp-storage 19.0.0", "sp-tracing 16.0.0", "sp-transaction-pool", @@ -23684,6 +23606,7 @@ dependencies = [ "asset-hub-westend-emulated-chain", "bridge-hub-westend-emulated-chain", "collectives-westend-emulated-chain", + "coretime-westend-emulated-chain", "emulated-integration-tests-common", "penpal-emulated-chain", "people-westend-emulated-chain", @@ -24179,7 +24102,7 @@ version = "7.0.0" dependencies = [ "Inflector", "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "staging-xcm", "syn 2.0.61", "trybuild", @@ -24202,7 +24125,6 @@ dependencies = [ "scale-info", "sp-api", "sp-io", - "sp-std 14.0.0", "sp-weights", "staging-xcm", "staging-xcm-builder", @@ -24346,7 +24268,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ce1b18ccd8e73a9321186f97e46f9f04b778851177567b1975109d26a08d2a6" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] @@ -24366,7 +24288,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" dependencies = [ "proc-macro2 1.0.82", - "quote 1.0.35", + "quote 1.0.36", "syn 2.0.61", ] diff --git a/Cargo.toml b/Cargo.toml index 5c2677fffeb225888a1ac8af392c287634cf59e6..3886014dc2b439b2594e360ceb6d844b779ebd82 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -61,6 +61,7 @@ members = [ "bridges/snowbridge/primitives/router", "bridges/snowbridge/runtime/runtime-common", "bridges/snowbridge/runtime/test-common", + "cumulus/bin/pov-validator", "cumulus/client/cli", "cumulus/client/collator", "cumulus/client/consensus/aura", @@ -90,6 +91,8 @@ members = [ "cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-rococo", "cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-westend", "cumulus/parachains/integration-tests/emulated/chains/parachains/collectives/collectives-westend", + "cumulus/parachains/integration-tests/emulated/chains/parachains/coretime/coretime-rococo", + "cumulus/parachains/integration-tests/emulated/chains/parachains/coretime/coretime-westend", "cumulus/parachains/integration-tests/emulated/chains/parachains/people/people-rococo", "cumulus/parachains/integration-tests/emulated/chains/parachains/people/people-westend", "cumulus/parachains/integration-tests/emulated/chains/parachains/testing/penpal", @@ -104,6 +107,8 @@ members = [ "cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo", "cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend", "cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend", + "cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-rococo", + "cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-westend", "cumulus/parachains/integration-tests/emulated/tests/people/people-rococo", "cumulus/parachains/integration-tests/emulated/tests/people/people-westend", "cumulus/parachains/pallets/collective-content", @@ -589,7 +594,7 @@ ark-ed-on-bls12-381-bandersnatch-ext = { version = "0.4.1", default-features = f ark-scale = { version = "0.0.12", default-features = false } array-bytes = { version = "6.2.2", default-features = false } arrayvec = { version = "0.7.4" } -assert_cmd = { version = "2.0.10" } +assert_cmd = { version = "2.0.14" } assert_matches = { version = "1.5.0" } asset-hub-rococo-emulated-chain = { path = "cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-rococo" } asset-hub-rococo-runtime = { path = "cumulus/parachains/runtimes/assets/asset-hub-rococo", default-features = false } @@ -654,7 +659,7 @@ chain-spec-builder = { path = "substrate/bin/utils/chain-spec-builder", default- chain-spec-guide-runtime = { path = "docs/sdk/src/reference_docs/chain_spec_runtime" } chrono = { version = "0.4.31" } cid = { version = "0.9.0" } -clap = { version = "4.5.3" } +clap = { version = "4.5.9" } clap-num = { version = "1.0.2" } clap_complete = { version = "4.0.2" } coarsetime = { version = "0.1.22" } @@ -667,7 +672,9 @@ colored = { version = "2.0.4" } comfy-table = { version = "7.1.0", default-features = false } console = { version = "0.15.8" } contracts-rococo-runtime = { path = "cumulus/parachains/runtimes/contracts/contracts-rococo" } +coretime-rococo-emulated-chain = { path = "cumulus/parachains/integration-tests/emulated/chains/parachains/coretime/coretime-rococo" } coretime-rococo-runtime = { path = "cumulus/parachains/runtimes/coretime/coretime-rococo" } +coretime-westend-emulated-chain = { path = "cumulus/parachains/integration-tests/emulated/chains/parachains/coretime/coretime-westend" } coretime-westend-runtime = { path = "cumulus/parachains/runtimes/coretime/coretime-westend" } cpu-time = { version = "1.0.0" } criterion = { version = "0.5.1", default-features = false } @@ -720,7 +727,7 @@ ed25519-zebra = { version = "4.0.3", default-features = false } either = { version = "1.8.1", default-features = false } emulated-integration-tests-common = { path = "cumulus/parachains/integration-tests/emulated/common", default-features = false } enumflags2 = { version = "0.7.7" } -enumn = { version = "0.1.12" } +enumn = { version = "0.1.13" } env_logger = { version = "0.11.3" } environmental = { version = "1.1.4", default-features = false } equivocation-detector = { path = "bridges/relays/equivocation" } @@ -808,7 +815,7 @@ kvdb-rocksdb = { version = "0.19.0" } kvdb-shared-tests = { version = "0.11.0" } landlock = { version = "0.3.0" } lazy_static = { version = "1.4.0" } -libc = { version = "0.2.153" } +libc = { version = "0.2.155" } libfuzzer-sys = { version = "0.4" } libp2p = { version = "0.52.4" } libp2p-identity = { version = "0.2.3" } @@ -818,7 +825,7 @@ linked_hash_set = { version = "0.1.4" } linregress = { version = "0.5.1" } lite-json = { version = "0.2.0", default-features = false } litep2p = { version = "0.6.2" } -log = { version = "0.4.21", default-features = false } +log = { version = "0.4.22", default-features = false } macro_magic = { version = "0.5.1" } maplit = { version = "1.0.2" } memmap2 = { version = "0.9.3" } @@ -855,7 +862,7 @@ num-rational = { version = "0.4.1" } num-traits = { version = "0.2.17", default-features = false } num_cpus = { version = "1.13.1" } once_cell = { version = "1.19.0" } -orchestra = { version = "0.3.5", default-features = false } +orchestra = { version = "0.4.0", default-features = false } pallet-alliance = { path = "substrate/frame/alliance", default-features = false } pallet-asset-conversion = { path = "substrate/frame/asset-conversion", default-features = false } pallet-asset-conversion-ops = { path = "substrate/frame/asset-conversion/ops", default-features = false } @@ -986,7 +993,7 @@ parity-util-mem = { version = "0.12.0" } parity-wasm = { version = "0.45.0" } parking_lot = { version = "0.12.1", default-features = false } partial_sort = { version = "0.2.0" } -paste = { version = "1.0.14", default-features = false } +paste = { version = "1.0.15", default-features = false } pbkdf2 = { version = "0.12.2", default-features = false } penpal-emulated-chain = { path = "cumulus/parachains/integration-tests/emulated/chains/parachains/testing/penpal" } penpal-runtime = { path = "cumulus/parachains/runtimes/testing/penpal" } @@ -1069,7 +1076,7 @@ pyroscope = { version = "0.5.7" } pyroscope_pprofrs = { version = "0.2.7" } quick_cache = { version = "0.3" } quickcheck = { version = "1.0.3", default-features = false } -quote = { version = "1.0.33" } +quote = { version = "1.0.36" } rand = { version = "0.8.5", default-features = false } rand_chacha = { version = "0.3.1", default-features = false } rand_core = { version = "0.6.2" } @@ -1164,10 +1171,10 @@ secp256k1 = { version = "0.28.0", default-features = false } secrecy = { version = "0.8.0", default-features = false } seedling-runtime = { path = "cumulus/parachains/runtimes/starters/seedling" } separator = { version = "0.4.1" } -serde = { version = "1.0.197", default-features = false } +serde = { version = "1.0.204", default-features = false } serde-big-array = { version = "0.3.2" } serde_derive = { version = "1.0.117" } -serde_json = { version = "1.0.114", default-features = false } +serde_json = { version = "1.0.120", default-features = false } serde_yaml = { version = "0.9" } serial_test = { version = "2.0.0" } sha1 = { version = "0.10.6" } diff --git a/bridges/bin/runtime-common/Cargo.toml b/bridges/bin/runtime-common/Cargo.toml index d69a064aab81a41c946b073f232ebb8c778b9609..36f27b6aa0358fcb8027bbfe6e571bc1a50962e6 100644 --- a/bridges/bin/runtime-common/Cargo.toml +++ b/bridges/bin/runtime-common/Cargo.toml @@ -12,14 +12,12 @@ workspace = true [dependencies] codec = { features = ["derive"], workspace = true } -hash-db = { workspace = true } log = { workspace = true } scale-info = { features = ["derive"], workspace = true } static_assertions = { optional = true, workspace = true, default-features = true } tuplex = { workspace = true } # Bridge dependencies - bp-header-chain = { workspace = true } bp-messages = { workspace = true } bp-parachains = { workspace = true } @@ -34,25 +32,23 @@ pallet-bridge-parachains = { workspace = true } pallet-bridge-relayers = { workspace = true } # Substrate dependencies - frame-support = { workspace = true } frame-system = { workspace = true } pallet-transaction-payment = { workspace = true } pallet-utility = { workspace = true } -sp-api = { workspace = true } -sp-core = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } sp-std = { workspace = true } -sp-trie = { workspace = true } +sp-trie = { optional = true, workspace = true } # Polkadot dependencies xcm = { workspace = true } xcm-builder = { workspace = true } [dev-dependencies] -bp-test-utils = { workspace = true, default-features = true } -pallet-balances = { workspace = true, default-features = true } +bp-test-utils = { workspace = true } +pallet-balances = { workspace = true } +pallet-bridge-messages = { features = ["std", "test-helpers"], workspace = true } [features] default = ["std"] @@ -63,13 +59,14 @@ std = [ "bp-polkadot-core/std", "bp-relayers/std", "bp-runtime/std", + "bp-test-utils/std", "bp-xcm-bridge-hub-router/std", "bp-xcm-bridge-hub/std", "codec/std", "frame-support/std", "frame-system/std", - "hash-db/std", "log/std", + "pallet-balances/std", "pallet-bridge-grandpa/std", "pallet-bridge-messages/std", "pallet-bridge-parachains/std", @@ -77,8 +74,6 @@ std = [ "pallet-transaction-payment/std", "pallet-utility/std", "scale-info/std", - "sp-api/std", - "sp-core/std", "sp-io/std", "sp-runtime/std", "sp-std/std", @@ -88,15 +83,22 @@ std = [ "xcm/std", ] runtime-benchmarks = [ + "bp-runtime/test-helpers", "frame-support/runtime-benchmarks", "frame-system/runtime-benchmarks", "pallet-balances/runtime-benchmarks", "pallet-bridge-grandpa/runtime-benchmarks", "pallet-bridge-messages/runtime-benchmarks", + "pallet-bridge-messages/test-helpers", "pallet-bridge-parachains/runtime-benchmarks", "pallet-bridge-relayers/runtime-benchmarks", "pallet-utility/runtime-benchmarks", "sp-runtime/runtime-benchmarks", + "sp-trie", "xcm-builder/runtime-benchmarks", ] integrity-test = ["static_assertions"] +test-helpers = [ + "bp-runtime/test-helpers", + "sp-trie", +] diff --git a/bridges/bin/runtime-common/src/extensions/priority_calculator.rs b/bridges/bin/runtime-common/src/extensions/priority_calculator.rs index 92810290f95e77a7fdc04cafaa1e6ab290e1661a..9f559dc13b64d3912f0d1679c21fa682034bdb8e 100644 --- a/bridges/bin/runtime-common/src/extensions/priority_calculator.rs +++ b/bridges/bin/runtime-common/src/extensions/priority_calculator.rs @@ -319,6 +319,7 @@ mod integrity_tests { pub mod per_message { use super::*; + use bp_messages::ChainWithMessages; use pallet_bridge_messages::WeightInfoExt; /// Ensures that the value of `PriorityBoostPerMessage` matches the value of @@ -339,7 +340,7 @@ mod integrity_tests { BalanceOf: Send + Sync + FixedPointOperand, { let maximal_messages_in_delivery_transaction = - Runtime::MaxUnconfirmedMessagesAtInboundLane::get(); + Runtime::BridgedChain::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX; super::ensure_priority_boost_is_sane::>( "PriorityBoostPerMessage", maximal_messages_in_delivery_transaction, diff --git a/bridges/bin/runtime-common/src/extensions/refund_relayer_extension.rs b/bridges/bin/runtime-common/src/extensions/refund_relayer_extension.rs index 5aa7f1c095d540a4ee5050aeb7d694c98b744683..6ba3506377d0e602bf9ee706b13c248efd6afaca 100644 --- a/bridges/bin/runtime-common/src/extensions/refund_relayer_extension.rs +++ b/bridges/bin/runtime-common/src/extensions/refund_relayer_extension.rs @@ -22,9 +22,9 @@ use crate::messages_call_ext::{ CallHelper as MessagesCallHelper, CallInfo as MessagesCallInfo, MessagesCallSubType, }; -use bp_messages::{LaneId, MessageNonce}; +use bp_messages::{ChainWithMessages, LaneId, MessageNonce}; use bp_relayers::{ExplicitOrAccountParams, RewardsAccountOwner, RewardsAccountParams}; -use bp_runtime::{Parachain, RangeInclusiveExt, StaticStrProvider}; +use bp_runtime::{Chain, Parachain, RangeInclusiveExt, StaticStrProvider}; use codec::{Codec, Decode, Encode}; use frame_support::{ dispatch::{CallableCallFor, DispatchInfo, PostDispatchInfo}, @@ -293,7 +293,7 @@ pub trait RefundSignedExtension: ::Id::get(), ::Instance, - >>::BridgedChainId::get(), + >>::BridgedChain::ID, if call_info.is_receive_messages_proof_call() { RewardsAccountOwner::ThisChain } else { @@ -406,8 +406,7 @@ pub trait RefundSignedExtension: // a quick check to avoid invalid high-priority transactions let max_unconfirmed_messages_in_confirmation_tx = ::Instance, - >>::MaxUnconfirmedMessagesAtInboundLane::get( - ); + >>::BridgedChain::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX; if bundled_messages > max_unconfirmed_messages_in_confirmation_tx { return None } @@ -935,9 +934,6 @@ where pub(crate) mod tests { use super::*; use crate::{ - messages::{ - source::FromBridgedChainMessagesDeliveryProof, target::FromBridgedChainMessagesProof, - }, messages_call_ext::{ BaseMessagesProofInfo, ReceiveMessagesDeliveryProofInfo, ReceiveMessagesProofInfo, UnrewardedRelayerOccupation, @@ -946,8 +942,10 @@ pub(crate) mod tests { }; use bp_header_chain::StoredHeaderDataBuilder; use bp_messages::{ - DeliveredMessages, InboundLaneData, MessageNonce, MessagesOperatingMode, OutboundLaneData, - UnrewardedRelayer, UnrewardedRelayersState, + source_chain::FromBridgedChainMessagesDeliveryProof, + target_chain::FromBridgedChainMessagesProof, DeliveredMessages, InboundLaneData, + MessageNonce, MessagesOperatingMode, OutboundLaneData, UnrewardedRelayer, + UnrewardedRelayersState, }; use bp_parachains::{BestParaHeadHash, ParaInfo}; use bp_polkadot_core::parachains::{ParaHeadsProof, ParaId}; @@ -1123,7 +1121,7 @@ pub(crate) mod tests { ParaId(BridgedUnderlyingParachain::PARACHAIN_ID), [parachain_head_at_relay_header_number as u8; 32].into(), )], - parachain_heads_proof: ParaHeadsProof { storage_proof: vec![] }, + parachain_heads_proof: ParaHeadsProof { storage_proof: Default::default() }, }) } @@ -1136,7 +1134,7 @@ pub(crate) mod tests { ParaId(BridgedUnderlyingParachain::PARACHAIN_ID), [parachain_head_at_relay_header_number as u8; 32].into(), )], - parachain_heads_proof: ParaHeadsProof { storage_proof: vec![] }, + parachain_heads_proof: ParaHeadsProof { storage_proof: Default::default() }, is_free_execution_expected: false, }) } @@ -1144,9 +1142,9 @@ pub(crate) mod tests { fn message_delivery_call(best_message: MessageNonce) -> RuntimeCall { RuntimeCall::BridgeMessages(MessagesCall::receive_messages_proof { relayer_id_at_bridged_chain: relayer_account_at_bridged_chain(), - proof: FromBridgedChainMessagesProof { + proof: Box::new(FromBridgedChainMessagesProof { bridged_header_hash: Default::default(), - storage_proof: vec![], + storage_proof: Default::default(), lane: TestLaneId::get(), nonces_start: pallet_bridge_messages::InboundLanes::::get( TEST_LANE_ID, @@ -1154,7 +1152,7 @@ pub(crate) mod tests { .last_delivered_nonce() + 1, nonces_end: best_message, - }, + }), messages_count: 1, dispatch_weight: Weight::zero(), }) @@ -1164,7 +1162,7 @@ pub(crate) mod tests { RuntimeCall::BridgeMessages(MessagesCall::receive_messages_delivery_proof { proof: FromBridgedChainMessagesDeliveryProof { bridged_header_hash: Default::default(), - storage_proof: vec![], + storage_proof: Default::default(), lane: TestLaneId::get(), }, relayers_state: UnrewardedRelayersState { @@ -1327,8 +1325,10 @@ pub(crate) mod tests { best_stored_nonce: 100, }, unrewarded_relayers: UnrewardedRelayerOccupation { - free_relayer_slots: MaxUnrewardedRelayerEntriesAtInboundLane::get(), - free_message_slots: MaxUnconfirmedMessagesAtInboundLane::get(), + free_relayer_slots: + BridgedUnderlyingChain::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX, + free_message_slots: + BridgedUnderlyingChain::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX, }, }), ), @@ -1397,8 +1397,10 @@ pub(crate) mod tests { best_stored_nonce: 100, }, unrewarded_relayers: UnrewardedRelayerOccupation { - free_relayer_slots: MaxUnrewardedRelayerEntriesAtInboundLane::get(), - free_message_slots: MaxUnconfirmedMessagesAtInboundLane::get(), + free_relayer_slots: + BridgedUnderlyingChain::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX, + free_message_slots: + BridgedUnderlyingChain::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX, }, }), ), @@ -1459,8 +1461,10 @@ pub(crate) mod tests { best_stored_nonce: 100, }, unrewarded_relayers: UnrewardedRelayerOccupation { - free_relayer_slots: MaxUnrewardedRelayerEntriesAtInboundLane::get(), - free_message_slots: MaxUnconfirmedMessagesAtInboundLane::get(), + free_relayer_slots: + BridgedUnderlyingChain::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX, + free_message_slots: + BridgedUnderlyingChain::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX, }, }), ), @@ -1499,8 +1503,10 @@ pub(crate) mod tests { best_stored_nonce: 100, }, unrewarded_relayers: UnrewardedRelayerOccupation { - free_relayer_slots: MaxUnrewardedRelayerEntriesAtInboundLane::get(), - free_message_slots: MaxUnconfirmedMessagesAtInboundLane::get(), + free_relayer_slots: + BridgedUnderlyingChain::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX, + free_message_slots: + BridgedUnderlyingChain::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX, }, }, )), @@ -1735,14 +1741,16 @@ pub(crate) mod tests { let fns = [run_validate, run_grandpa_validate, run_messages_validate]; for f in fns { - let priority_of_max_messages_delivery = - f(message_delivery_call(100 + MaxUnconfirmedMessagesAtInboundLane::get())) - .unwrap() - .priority; - let priority_of_more_than_max_messages_delivery = - f(message_delivery_call(100 + MaxUnconfirmedMessagesAtInboundLane::get() + 1)) - .unwrap() - .priority; + let priority_of_max_messages_delivery = f(message_delivery_call( + 100 + BridgedUnderlyingChain::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX, + )) + .unwrap() + .priority; + let priority_of_more_than_max_messages_delivery = f(message_delivery_call( + 100 + BridgedUnderlyingChain::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX + 1, + )) + .unwrap() + .priority; assert!( priority_of_max_messages_delivery > priority_of_more_than_max_messages_delivery, @@ -2103,7 +2111,7 @@ pub(crate) mod tests { [1u8; 32].into(), ), ], - parachain_heads_proof: ParaHeadsProof { storage_proof: vec![] }, + parachain_heads_proof: ParaHeadsProof { storage_proof: Default::default() }, }), message_delivery_call(200), ], @@ -2865,7 +2873,8 @@ pub(crate) mod tests { #[test] fn does_not_panic_on_boosting_priority_of_empty_message_delivery_transaction() { run_test(|| { - let best_delivered_message = MaxUnconfirmedMessagesAtInboundLane::get(); + let best_delivered_message = + BridgedUnderlyingChain::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX; initialize_environment(100, 100, best_delivered_message); // register relayer so it gets priority boost diff --git a/bridges/bin/runtime-common/src/integrity.rs b/bridges/bin/runtime-common/src/integrity.rs index d3827a14dd6cc24e088a8d05d26aba9d769eb213..f661db8a22057ecf6c8b217336e5a98660344cb2 100644 --- a/bridges/bin/runtime-common/src/integrity.rs +++ b/bridges/bin/runtime-common/src/integrity.rs @@ -19,10 +19,9 @@ //! Most of the tests in this module assume that the bridge is using standard (see `crate::messages` //! module for details) configuration. -use crate::{messages, messages::MessageBridge}; - -use bp_messages::{InboundLaneData, MessageNonce}; -use bp_runtime::{Chain, ChainId}; +use bp_header_chain::ChainWithGrandpa; +use bp_messages::{ChainWithMessages, InboundLaneData, MessageNonce}; +use bp_runtime::Chain; use codec::Encode; use frame_support::{storage::generator::StorageValue, traits::Get, weights::Weight}; use frame_system::limits; @@ -50,23 +49,6 @@ macro_rules! assert_chain_types( } ); -/// Macro that ensures that the bridge GRANDPA pallet is configured properly to bridge with given -/// chain. -#[macro_export] -macro_rules! assert_bridge_grandpa_pallet_types( - ( runtime: $r:path, with_bridged_chain_grandpa_instance: $i:path, bridged_chain: $bridged:path ) => { - { - // if one of asserts fail, then either bridge isn't configured properly (or alternatively - non-standard - // configuration is used), or something has broke existing configuration (meaning that all bridged chains - // and relays will stop functioning) - use pallet_bridge_grandpa::Config as GrandpaConfig; - use static_assertions::assert_type_eq_all; - - assert_type_eq_all!(<$r as GrandpaConfig<$i>>::BridgedChain, $bridged); - } - } -); - /// Macro that ensures that the bridge messages pallet is configured properly to bridge using given /// configuration. #[macro_export] @@ -74,32 +56,30 @@ macro_rules! assert_bridge_messages_pallet_types( ( runtime: $r:path, with_bridged_chain_messages_instance: $i:path, - bridge: $bridge:path + this_chain: $this:path, + bridged_chain: $bridged:path, ) => { { // if one of asserts fail, then either bridge isn't configured properly (or alternatively - non-standard // configuration is used), or something has broke existing configuration (meaning that all bridged chains // and relays will stop functioning) - use $crate::messages::{ - source::{FromThisChainMessagePayload, TargetHeaderChainAdapter}, - target::{FromBridgedChainMessagePayload, SourceHeaderChainAdapter}, - AccountIdOf, BalanceOf, BridgedChain, ThisChain, - }; + use $crate::messages_xcm_extension::XcmAsPlainPayload; + use bp_messages::ChainWithMessages; + use bp_runtime::Chain; use pallet_bridge_messages::Config as MessagesConfig; use static_assertions::assert_type_eq_all; - assert_type_eq_all!(<$r as MessagesConfig<$i>>::OutboundPayload, FromThisChainMessagePayload); + assert_type_eq_all!(<$r as MessagesConfig<$i>>::ThisChain, $this); + assert_type_eq_all!(<$r as MessagesConfig<$i>>::BridgedChain, $bridged); - assert_type_eq_all!(<$r as MessagesConfig<$i>>::InboundRelayer, AccountIdOf>); - - assert_type_eq_all!(<$r as MessagesConfig<$i>>::TargetHeaderChain, TargetHeaderChainAdapter<$bridge>); - assert_type_eq_all!(<$r as MessagesConfig<$i>>::SourceHeaderChain, SourceHeaderChainAdapter<$bridge>); + assert_type_eq_all!(<$r as MessagesConfig<$i>>::OutboundPayload, XcmAsPlainPayload); + assert_type_eq_all!(<$r as MessagesConfig<$i>>::InboundPayload, XcmAsPlainPayload); } } ); /// Macro that combines four other macro calls - `assert_chain_types`, `assert_bridge_types`, -/// `assert_bridge_grandpa_pallet_types` and `assert_bridge_messages_pallet_types`. It may be used +/// and `assert_bridge_messages_pallet_types`. It may be used /// at the chain that is implementing complete standard messages bridge (i.e. with bridge GRANDPA /// and messages pallets deployed). #[macro_export] @@ -108,20 +88,15 @@ macro_rules! assert_complete_bridge_types( runtime: $r:path, with_bridged_chain_grandpa_instance: $gi:path, with_bridged_chain_messages_instance: $mi:path, - bridge: $bridge:path, this_chain: $this:path, bridged_chain: $bridged:path, ) => { $crate::assert_chain_types!(runtime: $r, this_chain: $this); - $crate::assert_bridge_grandpa_pallet_types!( - runtime: $r, - with_bridged_chain_grandpa_instance: $gi, - bridged_chain: $bridged - ); $crate::assert_bridge_messages_pallet_types!( runtime: $r, with_bridged_chain_messages_instance: $mi, - bridge: $bridge + this_chain: $this, + bridged_chain: $bridged, ); } ); @@ -184,20 +159,8 @@ where ); } -/// Parameters for asserting messages pallet constants. -#[derive(Debug)] -pub struct AssertBridgeMessagesPalletConstants { - /// Maximal number of unrewarded relayer entries in a confirmation transaction at the bridged - /// chain. - pub max_unrewarded_relayers_in_bridged_confirmation_tx: MessageNonce, - /// Maximal number of unconfirmed messages in a confirmation transaction at the bridged chain. - pub max_unconfirmed_messages_in_bridged_confirmation_tx: MessageNonce, - /// Identifier of the bridged chain. - pub bridged_chain_id: ChainId, -} - /// Test that the constants, used in messages pallet configuration are valid. -pub fn assert_bridge_messages_pallet_constants(params: AssertBridgeMessagesPalletConstants) +pub fn assert_bridge_messages_pallet_constants() where R: pallet_bridge_messages::Config, MI: 'static, @@ -207,27 +170,22 @@ where "ActiveOutboundLanes ({:?}) must not be empty", R::ActiveOutboundLanes::get(), ); + assert!( - R::MaxUnrewardedRelayerEntriesAtInboundLane::get() <= params.max_unrewarded_relayers_in_bridged_confirmation_tx, - "MaxUnrewardedRelayerEntriesAtInboundLane ({}) must be <= than the hardcoded value for bridged chain: {}", - R::MaxUnrewardedRelayerEntriesAtInboundLane::get(), - params.max_unrewarded_relayers_in_bridged_confirmation_tx, - ); - assert!( - R::MaxUnconfirmedMessagesAtInboundLane::get() <= params.max_unconfirmed_messages_in_bridged_confirmation_tx, - "MaxUnrewardedRelayerEntriesAtInboundLane ({}) must be <= than the hardcoded value for bridged chain: {}", - R::MaxUnconfirmedMessagesAtInboundLane::get(), - params.max_unconfirmed_messages_in_bridged_confirmation_tx, + pallet_bridge_messages::BridgedChainOf::::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX + <= pallet_bridge_messages::BridgedChainOf::::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX, + "MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX ({}) of {:?} is larger than \ + its MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX ({}). This makes \ + no sense", + pallet_bridge_messages::BridgedChainOf::::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX, + pallet_bridge_messages::BridgedChainOf::::ID, + pallet_bridge_messages::BridgedChainOf::::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX, ); - assert_eq!(R::BridgedChainId::get(), params.bridged_chain_id); } /// Parameters for asserting bridge pallet names. #[derive(Debug)] pub struct AssertBridgePalletNames<'a> { - /// Name of the messages pallet, deployed at the bridged chain and used to bridge with this - /// chain. - pub with_this_chain_messages_pallet_name: &'a str, /// Name of the GRANDPA pallet, deployed at this chain and used to bridge with the bridged /// chain. pub with_bridged_chain_grandpa_pallet_name: &'a str, @@ -238,18 +196,22 @@ pub struct AssertBridgePalletNames<'a> { /// Tests that bridge pallet names used in `construct_runtime!()` macro call are matching constants /// from chain primitives crates. -pub fn assert_bridge_pallet_names(params: AssertBridgePalletNames) +fn assert_bridge_pallet_names(params: AssertBridgePalletNames) where - B: MessageBridge, R: pallet_bridge_grandpa::Config + pallet_bridge_messages::Config, GI: 'static, MI: 'static, { - assert_eq!(B::BRIDGED_MESSAGES_PALLET_NAME, params.with_this_chain_messages_pallet_name); + // check that the bridge GRANDPA pallet has required name assert_eq!( pallet_bridge_grandpa::PalletOwner::::storage_value_final_key().to_vec(), - bp_runtime::storage_value_key(params.with_bridged_chain_grandpa_pallet_name, "PalletOwner",).0, + bp_runtime::storage_value_key( + params.with_bridged_chain_grandpa_pallet_name, + "PalletOwner", + ).0, ); + + // check that the bridge messages pallet has required name assert_eq!( pallet_bridge_messages::PalletOwner::::storage_value_final_key().to_vec(), bp_runtime::storage_value_key( @@ -262,35 +224,58 @@ where /// Parameters for asserting complete standard messages bridge. #[derive(Debug)] -pub struct AssertCompleteBridgeConstants<'a> { +pub struct AssertCompleteBridgeConstants { /// Parameters to assert this chain constants. pub this_chain_constants: AssertChainConstants, - /// Parameters to assert messages pallet constants. - pub messages_pallet_constants: AssertBridgeMessagesPalletConstants, - /// Parameters to assert pallet names constants. - pub pallet_names: AssertBridgePalletNames<'a>, } -/// All bridge-related constants tests for the complete standard messages bridge (i.e. with bridge -/// GRANDPA and messages pallets deployed). -pub fn assert_complete_bridge_constants(params: AssertCompleteBridgeConstants) -where +/// All bridge-related constants tests for the complete standard relay-chain messages bridge +/// (i.e. with bridge GRANDPA and messages pallets deployed). +pub fn assert_complete_with_relay_chain_bridge_constants( + params: AssertCompleteBridgeConstants, +) where + R: frame_system::Config + + pallet_bridge_grandpa::Config + + pallet_bridge_messages::Config, + GI: 'static, + MI: 'static, +{ + assert_chain_constants::(params.this_chain_constants); + assert_bridge_grandpa_pallet_constants::(); + assert_bridge_messages_pallet_constants::(); + assert_bridge_pallet_names::(AssertBridgePalletNames { + with_bridged_chain_grandpa_pallet_name: + >::BridgedChain::WITH_CHAIN_GRANDPA_PALLET_NAME, + with_bridged_chain_messages_pallet_name: + >::BridgedChain::WITH_CHAIN_MESSAGES_PALLET_NAME, + }); +} + +/// All bridge-related constants tests for the complete standard parachain messages bridge +/// (i.e. with bridge GRANDPA, parachains and messages pallets deployed). +pub fn assert_complete_with_parachain_bridge_constants( + params: AssertCompleteBridgeConstants, +) where R: frame_system::Config + pallet_bridge_grandpa::Config + pallet_bridge_messages::Config, GI: 'static, MI: 'static, - B: MessageBridge, + RelayChain: ChainWithGrandpa, { assert_chain_constants::(params.this_chain_constants); assert_bridge_grandpa_pallet_constants::(); - assert_bridge_messages_pallet_constants::(params.messages_pallet_constants); - assert_bridge_pallet_names::(params.pallet_names); + assert_bridge_messages_pallet_constants::(); + assert_bridge_pallet_names::(AssertBridgePalletNames { + with_bridged_chain_grandpa_pallet_name: RelayChain::WITH_CHAIN_GRANDPA_PALLET_NAME, + with_bridged_chain_messages_pallet_name: + >::BridgedChain::WITH_CHAIN_MESSAGES_PALLET_NAME, + }); } /// Check that the message lane weights are correct. pub fn check_message_lane_weights< - C: Chain, + C: ChainWithMessages, T: frame_system::Config + pallet_bridge_messages::Config, MessagesPalletInstance: 'static, >( @@ -308,14 +293,20 @@ pub fn check_message_lane_weights< // check basic weight assumptions pallet_bridge_messages::ensure_weights_are_correct::>(); + // check that the maximal message dispatch weight is below hardcoded limit + pallet_bridge_messages::ensure_maximal_message_dispatch::>( + C::maximal_incoming_message_size(), + C::maximal_incoming_message_dispatch_weight(), + ); + // check that weights allow us to receive messages - let max_incoming_message_proof_size = bridged_chain_extra_storage_proof_size - .saturating_add(messages::target::maximal_incoming_message_size(C::max_extrinsic_size())); + let max_incoming_message_proof_size = + bridged_chain_extra_storage_proof_size.saturating_add(C::maximal_incoming_message_size()); pallet_bridge_messages::ensure_able_to_receive_message::>( C::max_extrinsic_size(), C::max_extrinsic_weight(), max_incoming_message_proof_size, - messages::target::maximal_incoming_message_dispatch_weight(C::max_extrinsic_weight()), + C::maximal_incoming_message_dispatch_weight(), ); // check that weights allow us to receive delivery confirmations diff --git a/bridges/bin/runtime-common/src/lib.rs b/bridges/bin/runtime-common/src/lib.rs index 5679acd6006ccb8540f940f0f90363f902d643f7..b65bb6041d5610ce2bdfb63f923f3f24b21dcd7f 100644 --- a/bridges/bin/runtime-common/src/lib.rs +++ b/bridges/bin/runtime-common/src/lib.rs @@ -20,11 +20,10 @@ #![cfg_attr(not(feature = "std"), no_std)] pub mod extensions; -pub mod messages; + pub mod messages_api; pub mod messages_benchmarking; pub mod messages_call_ext; -pub mod messages_generation; pub mod messages_xcm_extension; pub mod parachains_benchmarking; diff --git a/bridges/bin/runtime-common/src/messages.rs b/bridges/bin/runtime-common/src/messages.rs deleted file mode 100644 index 03801d5279d0a8453542336d8089f5c887a3d005..0000000000000000000000000000000000000000 --- a/bridges/bin/runtime-common/src/messages.rs +++ /dev/null @@ -1,704 +0,0 @@ -// Copyright (C) Parity Technologies (UK) Ltd. -// This file is part of Parity Bridges Common. - -// Parity Bridges Common is free software: you can redistribute it and/or modify -// it under the terms of the GNU General Public License as published by -// the Free Software Foundation, either version 3 of the License, or -// (at your option) any later version. - -// Parity Bridges Common is distributed in the hope that it will be useful, -// but WITHOUT ANY WARRANTY; without even the implied warranty of -// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// GNU General Public License for more details. - -// You should have received a copy of the GNU General Public License -// along with Parity Bridges Common. If not, see . - -//! Types that allow runtime to act as a source/target endpoint of message lanes. -//! -//! Messages are assumed to be encoded `Call`s of the target chain. Call-dispatch -//! pallet is used to dispatch incoming messages. Message identified by a tuple -//! of to elements - message lane id and message nonce. - -pub use bp_runtime::{RangeInclusiveExt, UnderlyingChainOf, UnderlyingChainProvider}; - -use bp_header_chain::HeaderChain; -use bp_messages::{ - source_chain::TargetHeaderChain, - target_chain::{ProvedLaneMessages, ProvedMessages, SourceHeaderChain}, - InboundLaneData, LaneId, Message, MessageKey, MessageNonce, MessagePayload, OutboundLaneData, - VerificationError, -}; -use bp_runtime::{Chain, RawStorageProof, Size, StorageProofChecker}; -use codec::{Decode, Encode}; -use frame_support::{traits::Get, weights::Weight}; -use hash_db::Hasher; -use scale_info::TypeInfo; -use sp_runtime::RuntimeDebug; -use sp_std::{marker::PhantomData, vec::Vec}; - -/// Bidirectional message bridge. -pub trait MessageBridge { - /// Name of the paired messages pallet instance at the Bridged chain. - /// - /// Should be the name that is used in the `construct_runtime!()` macro. - const BRIDGED_MESSAGES_PALLET_NAME: &'static str; - - /// This chain in context of message bridge. - type ThisChain: ThisChainWithMessages; - /// Bridged chain in context of message bridge. - type BridgedChain: BridgedChainWithMessages; - /// Bridged header chain. - type BridgedHeaderChain: HeaderChain>; -} - -/// This chain that has `pallet-bridge-messages` module. -pub trait ThisChainWithMessages: UnderlyingChainProvider { - /// Call origin on the chain. - type RuntimeOrigin; -} - -/// Bridged chain that has `pallet-bridge-messages` module. -pub trait BridgedChainWithMessages: UnderlyingChainProvider {} - -/// This chain in context of message bridge. -pub type ThisChain = ::ThisChain; -/// Bridged chain in context of message bridge. -pub type BridgedChain = ::BridgedChain; -/// Hash used on the chain. -pub type HashOf = bp_runtime::HashOf<::Chain>; -/// Hasher used on the chain. -pub type HasherOf = bp_runtime::HasherOf>; -/// Account id used on the chain. -pub type AccountIdOf = bp_runtime::AccountIdOf>; -/// Type of balances that is used on the chain. -pub type BalanceOf = bp_runtime::BalanceOf>; - -/// Sub-module that is declaring types required for processing This -> Bridged chain messages. -pub mod source { - use super::*; - - /// Message payload for This -> Bridged chain messages. - pub type FromThisChainMessagePayload = crate::messages_xcm_extension::XcmAsPlainPayload; - - /// Maximal size of outbound message payload. - pub struct FromThisChainMaximalOutboundPayloadSize(PhantomData); - - impl Get for FromThisChainMaximalOutboundPayloadSize { - fn get() -> u32 { - maximal_message_size::() - } - } - - /// Messages delivery proof from bridged chain: - /// - /// - hash of finalized header; - /// - storage proof of inbound lane state; - /// - lane id. - #[derive(Clone, Decode, Encode, Eq, PartialEq, RuntimeDebug, TypeInfo)] - pub struct FromBridgedChainMessagesDeliveryProof { - /// Hash of the bridge header the proof is for. - pub bridged_header_hash: BridgedHeaderHash, - /// Storage trie proof generated for [`Self::bridged_header_hash`]. - pub storage_proof: RawStorageProof, - /// Lane id of which messages were delivered and the proof is for. - pub lane: LaneId, - } - - impl Size for FromBridgedChainMessagesDeliveryProof { - fn size(&self) -> u32 { - u32::try_from( - self.storage_proof - .iter() - .fold(0usize, |sum, node| sum.saturating_add(node.len())), - ) - .unwrap_or(u32::MAX) - } - } - - /// 'Parsed' message delivery proof - inbound lane id and its state. - pub type ParsedMessagesDeliveryProofFromBridgedChain = - (LaneId, InboundLaneData>>); - - /// Return maximal message size of This -> Bridged chain message. - pub fn maximal_message_size() -> u32 { - super::target::maximal_incoming_message_size( - UnderlyingChainOf::>::max_extrinsic_size(), - ) - } - - /// `TargetHeaderChain` implementation that is using default types and perform default checks. - pub struct TargetHeaderChainAdapter(PhantomData); - - impl TargetHeaderChain>> - for TargetHeaderChainAdapter - { - type MessagesDeliveryProof = FromBridgedChainMessagesDeliveryProof>>; - - fn verify_message(payload: &FromThisChainMessagePayload) -> Result<(), VerificationError> { - verify_chain_message::(payload) - } - - fn verify_messages_delivery_proof( - proof: Self::MessagesDeliveryProof, - ) -> Result<(LaneId, InboundLaneData>>), VerificationError> { - verify_messages_delivery_proof::(proof) - } - } - - /// Do basic Bridged-chain specific verification of This -> Bridged chain message. - /// - /// Ok result from this function means that the delivery transaction with this message - /// may be 'mined' by the target chain. - pub fn verify_chain_message( - payload: &FromThisChainMessagePayload, - ) -> Result<(), VerificationError> { - // IMPORTANT: any error that is returned here is fatal for the bridge, because - // this code is executed at the bridge hub and message sender actually lives - // at some sibling parachain. So we are failing **after** the message has been - // sent and we can't report it back to sender (unless error report mechanism is - // embedded into message and its dispatcher). - - // apart from maximal message size check (see below), we should also check the message - // dispatch weight here. But we assume that the bridged chain will just push the message - // to some queue (XCMP, UMP, DMP), so the weight is constant and fits the block. - - // The maximal size of extrinsic at Substrate-based chain depends on the - // `frame_system::Config::MaximumBlockLength` and - // `frame_system::Config::AvailableBlockRatio` constants. This check is here to be sure that - // the lane won't stuck because message is too large to fit into delivery transaction. - // - // **IMPORTANT NOTE**: the delivery transaction contains storage proof of the message, not - // the message itself. The proof is always larger than the message. But unless chain state - // is enormously large, it should be several dozens/hundreds of bytes. The delivery - // transaction also contains signatures and signed extensions. Because of this, we reserve - // 1/3 of the the maximal extrinsic size for this data. - if payload.len() > maximal_message_size::() as usize { - return Err(VerificationError::MessageTooLarge) - } - - Ok(()) - } - - /// Verify proof of This -> Bridged chain messages delivery. - /// - /// This function is used when Bridged chain is directly using GRANDPA finality. For Bridged - /// parachains, please use the `verify_messages_delivery_proof_from_parachain`. - pub fn verify_messages_delivery_proof( - proof: FromBridgedChainMessagesDeliveryProof>>, - ) -> Result, VerificationError> { - let FromBridgedChainMessagesDeliveryProof { bridged_header_hash, storage_proof, lane } = - proof; - let mut storage = - B::BridgedHeaderChain::storage_proof_checker(bridged_header_hash, storage_proof) - .map_err(VerificationError::HeaderChain)?; - // Messages delivery proof is just proof of single storage key read => any error - // is fatal. - let storage_inbound_lane_data_key = bp_messages::storage_keys::inbound_lane_data_key( - B::BRIDGED_MESSAGES_PALLET_NAME, - &lane, - ); - let inbound_lane_data = storage - .read_and_decode_mandatory_value(storage_inbound_lane_data_key.0.as_ref()) - .map_err(VerificationError::InboundLaneStorage)?; - - // check that the storage proof doesn't have any untouched trie nodes - storage.ensure_no_unused_nodes().map_err(VerificationError::StorageProof)?; - - Ok((lane, inbound_lane_data)) - } -} - -/// Sub-module that is declaring types required for processing Bridged -> This chain messages. -pub mod target { - use super::*; - - /// Decoded Bridged -> This message payload. - pub type FromBridgedChainMessagePayload = crate::messages_xcm_extension::XcmAsPlainPayload; - - /// Messages proof from bridged chain: - /// - /// - hash of finalized header; - /// - storage proof of messages and (optionally) outbound lane state; - /// - lane id; - /// - nonces (inclusive range) of messages which are included in this proof. - #[derive(Clone, Decode, Encode, Eq, PartialEq, RuntimeDebug, TypeInfo)] - pub struct FromBridgedChainMessagesProof { - /// Hash of the finalized bridged header the proof is for. - pub bridged_header_hash: BridgedHeaderHash, - /// A storage trie proof of messages being delivered. - pub storage_proof: RawStorageProof, - /// Messages in this proof are sent over this lane. - pub lane: LaneId, - /// Nonce of the first message being delivered. - pub nonces_start: MessageNonce, - /// Nonce of the last message being delivered. - pub nonces_end: MessageNonce, - } - - impl Size for FromBridgedChainMessagesProof { - fn size(&self) -> u32 { - u32::try_from( - self.storage_proof - .iter() - .fold(0usize, |sum, node| sum.saturating_add(node.len())), - ) - .unwrap_or(u32::MAX) - } - } - - /// Return maximal dispatch weight of the message we're able to receive. - pub fn maximal_incoming_message_dispatch_weight(maximal_extrinsic_weight: Weight) -> Weight { - maximal_extrinsic_weight / 2 - } - - /// Return maximal message size given maximal extrinsic size. - pub fn maximal_incoming_message_size(maximal_extrinsic_size: u32) -> u32 { - maximal_extrinsic_size / 3 * 2 - } - - /// `SourceHeaderChain` implementation that is using default types and perform default checks. - pub struct SourceHeaderChainAdapter(PhantomData); - - impl SourceHeaderChain for SourceHeaderChainAdapter { - type MessagesProof = FromBridgedChainMessagesProof>>; - - fn verify_messages_proof( - proof: Self::MessagesProof, - messages_count: u32, - ) -> Result, VerificationError> { - verify_messages_proof::(proof, messages_count) - } - } - - /// Verify proof of Bridged -> This chain messages. - /// - /// This function is used when Bridged chain is directly using GRANDPA finality. For Bridged - /// parachains, please use the `verify_messages_proof_from_parachain`. - /// - /// The `messages_count` argument verification (sane limits) is supposed to be made - /// outside of this function. This function only verifies that the proof declares exactly - /// `messages_count` messages. - pub fn verify_messages_proof( - proof: FromBridgedChainMessagesProof>>, - messages_count: u32, - ) -> Result, VerificationError> { - let FromBridgedChainMessagesProof { - bridged_header_hash, - storage_proof, - lane, - nonces_start, - nonces_end, - } = proof; - let storage = - B::BridgedHeaderChain::storage_proof_checker(bridged_header_hash, storage_proof) - .map_err(VerificationError::HeaderChain)?; - let mut parser = StorageProofCheckerAdapter::<_, B> { storage, _dummy: Default::default() }; - let nonces_range = nonces_start..=nonces_end; - - // receiving proofs where end < begin is ok (if proof includes outbound lane state) - let messages_in_the_proof = nonces_range.checked_len().unwrap_or(0); - if messages_in_the_proof != MessageNonce::from(messages_count) { - return Err(VerificationError::MessagesCountMismatch) - } - - // Read messages first. All messages that are claimed to be in the proof must - // be in the proof. So any error in `read_value`, or even missing value is fatal. - // - // Mind that we allow proofs with no messages if outbound lane state is proved. - let mut messages = Vec::with_capacity(messages_in_the_proof as _); - for nonce in nonces_range { - let message_key = MessageKey { lane_id: lane, nonce }; - let message_payload = parser.read_and_decode_message_payload(&message_key)?; - messages.push(Message { key: message_key, payload: message_payload }); - } - - // Now let's check if proof contains outbound lane state proof. It is optional, so - // we simply ignore `read_value` errors and missing value. - let proved_lane_messages = ProvedLaneMessages { - lane_state: parser.read_and_decode_outbound_lane_data(&lane)?, - messages, - }; - - // Now we may actually check if the proof is empty or not. - if proved_lane_messages.lane_state.is_none() && proved_lane_messages.messages.is_empty() { - return Err(VerificationError::EmptyMessageProof) - } - - // check that the storage proof doesn't have any untouched trie nodes - parser - .storage - .ensure_no_unused_nodes() - .map_err(VerificationError::StorageProof)?; - - // We only support single lane messages in this generated_schema - let mut proved_messages = ProvedMessages::new(); - proved_messages.insert(lane, proved_lane_messages); - - Ok(proved_messages) - } - - struct StorageProofCheckerAdapter { - storage: StorageProofChecker, - _dummy: sp_std::marker::PhantomData, - } - - impl StorageProofCheckerAdapter { - fn read_and_decode_outbound_lane_data( - &mut self, - lane_id: &LaneId, - ) -> Result, VerificationError> { - let storage_outbound_lane_data_key = bp_messages::storage_keys::outbound_lane_data_key( - B::BRIDGED_MESSAGES_PALLET_NAME, - lane_id, - ); - - self.storage - .read_and_decode_opt_value(storage_outbound_lane_data_key.0.as_ref()) - .map_err(VerificationError::OutboundLaneStorage) - } - - fn read_and_decode_message_payload( - &mut self, - message_key: &MessageKey, - ) -> Result { - let storage_message_key = bp_messages::storage_keys::message_key( - B::BRIDGED_MESSAGES_PALLET_NAME, - &message_key.lane_id, - message_key.nonce, - ); - self.storage - .read_and_decode_mandatory_value(storage_message_key.0.as_ref()) - .map_err(VerificationError::MessageStorage) - } - } -} - -/// The `BridgeMessagesCall` used by a chain. -pub type BridgeMessagesCallOf = bp_messages::BridgeMessagesCall< - bp_runtime::AccountIdOf, - target::FromBridgedChainMessagesProof>, - source::FromBridgedChainMessagesDeliveryProof>, ->; - -#[cfg(test)] -mod tests { - use super::*; - use crate::{ - messages_generation::{ - encode_all_messages, encode_lane_data, prepare_messages_storage_proof, - }, - mock::*, - }; - use bp_header_chain::{HeaderChainError, StoredHeaderDataBuilder}; - use bp_runtime::{HeaderId, StorageProofError}; - use codec::Encode; - use sp_core::H256; - use sp_runtime::traits::Header as _; - use sp_trie::accessed_nodes_tracker::Error as AccessedNodesTrackerError; - - #[test] - fn verify_chain_message_rejects_message_with_too_large_declared_weight() { - assert!(source::verify_chain_message::(&vec![ - 42; - BRIDGED_CHAIN_MAX_EXTRINSIC_WEIGHT - - 1 - ]) - .is_err()); - } - - #[test] - fn verify_chain_message_rejects_message_too_large_message() { - assert!(source::verify_chain_message::(&vec![ - 0; - source::maximal_message_size::() - as usize + 1 - ],) - .is_err()); - } - - #[test] - fn verify_chain_message_accepts_maximal_message() { - assert_eq!( - source::verify_chain_message::(&vec![ - 0; - source::maximal_message_size::() - as _ - ],), - Ok(()), - ); - } - - fn using_messages_proof( - nonces_end: MessageNonce, - outbound_lane_data: Option, - encode_message: impl Fn(MessageNonce, &MessagePayload) -> Option>, - encode_outbound_lane_data: impl Fn(&OutboundLaneData) -> Vec, - test: impl Fn(target::FromBridgedChainMessagesProof) -> R, - ) -> R { - let (state_root, storage_proof) = prepare_messages_storage_proof::( - TEST_LANE_ID, - 1..=nonces_end, - outbound_lane_data, - bp_runtime::StorageProofSize::Minimal(0), - vec![42], - encode_message, - encode_outbound_lane_data, - ); - - sp_io::TestExternalities::new(Default::default()).execute_with(move || { - let bridged_header = BridgedChainHeader::new( - 0, - Default::default(), - state_root, - Default::default(), - Default::default(), - ); - let bridged_header_hash = bridged_header.hash(); - - pallet_bridge_grandpa::BestFinalized::::put(HeaderId( - 0, - bridged_header_hash, - )); - pallet_bridge_grandpa::ImportedHeaders::::insert( - bridged_header_hash, - bridged_header.build(), - ); - test(target::FromBridgedChainMessagesProof { - bridged_header_hash, - storage_proof, - lane: TEST_LANE_ID, - nonces_start: 1, - nonces_end, - }) - }) - } - - #[test] - fn messages_proof_is_rejected_if_declared_less_than_actual_number_of_messages() { - assert_eq!( - using_messages_proof(10, None, encode_all_messages, encode_lane_data, |proof| { - target::verify_messages_proof::(proof, 5) - }), - Err(VerificationError::MessagesCountMismatch), - ); - } - - #[test] - fn messages_proof_is_rejected_if_declared_more_than_actual_number_of_messages() { - assert_eq!( - using_messages_proof(10, None, encode_all_messages, encode_lane_data, |proof| { - target::verify_messages_proof::(proof, 15) - }), - Err(VerificationError::MessagesCountMismatch), - ); - } - - #[test] - fn message_proof_is_rejected_if_header_is_missing_from_the_chain() { - assert_eq!( - using_messages_proof(10, None, encode_all_messages, encode_lane_data, |proof| { - let bridged_header_hash = - pallet_bridge_grandpa::BestFinalized::::get().unwrap().1; - pallet_bridge_grandpa::ImportedHeaders::::remove(bridged_header_hash); - target::verify_messages_proof::(proof, 10) - }), - Err(VerificationError::HeaderChain(HeaderChainError::UnknownHeader)), - ); - } - - #[test] - fn message_proof_is_rejected_if_header_state_root_mismatches() { - assert_eq!( - using_messages_proof(10, None, encode_all_messages, encode_lane_data, |proof| { - let bridged_header_hash = - pallet_bridge_grandpa::BestFinalized::::get().unwrap().1; - pallet_bridge_grandpa::ImportedHeaders::::insert( - bridged_header_hash, - BridgedChainHeader::new( - 0, - Default::default(), - Default::default(), - Default::default(), - Default::default(), - ) - .build(), - ); - target::verify_messages_proof::(proof, 10) - }), - Err(VerificationError::HeaderChain(HeaderChainError::StorageProof( - StorageProofError::StorageRootMismatch - ))), - ); - } - - #[test] - fn message_proof_is_rejected_if_it_has_duplicate_trie_nodes() { - assert_eq!( - using_messages_proof(10, None, encode_all_messages, encode_lane_data, |mut proof| { - let node = proof.storage_proof.pop().unwrap(); - proof.storage_proof.push(node.clone()); - proof.storage_proof.push(node); - target::verify_messages_proof::(proof, 10) - },), - Err(VerificationError::HeaderChain(HeaderChainError::StorageProof( - StorageProofError::StorageProof(sp_trie::StorageProofError::DuplicateNodes.into()) - ))), - ); - } - - #[test] - fn message_proof_is_rejected_if_it_has_unused_trie_nodes() { - assert_eq!( - using_messages_proof(10, None, encode_all_messages, encode_lane_data, |mut proof| { - proof.storage_proof.push(vec![42]); - target::verify_messages_proof::(proof, 10) - },), - Err(VerificationError::StorageProof(StorageProofError::AccessedNodesTracker( - AccessedNodesTrackerError::UnusedNodes.into() - ))), - ); - } - - #[test] - fn message_proof_is_rejected_if_required_message_is_missing() { - matches!( - using_messages_proof( - 10, - None, - |n, m| if n != 5 { Some(m.encode()) } else { None }, - encode_lane_data, - |proof| target::verify_messages_proof::(proof, 10) - ), - Err(VerificationError::MessageStorage(StorageProofError::StorageValueEmpty)), - ); - } - - #[test] - fn message_proof_is_rejected_if_message_decode_fails() { - matches!( - using_messages_proof( - 10, - None, - |n, m| { - let mut m = m.encode(); - if n == 5 { - m = vec![42] - } - Some(m) - }, - encode_lane_data, - |proof| target::verify_messages_proof::(proof, 10), - ), - Err(VerificationError::MessageStorage(StorageProofError::StorageValueDecodeFailed(_))), - ); - } - - #[test] - fn message_proof_is_rejected_if_outbound_lane_state_decode_fails() { - matches!( - using_messages_proof( - 10, - Some(OutboundLaneData { - oldest_unpruned_nonce: 1, - latest_received_nonce: 1, - latest_generated_nonce: 1, - }), - encode_all_messages, - |d| { - let mut d = d.encode(); - d.truncate(1); - d - }, - |proof| target::verify_messages_proof::(proof, 10), - ), - Err(VerificationError::OutboundLaneStorage( - StorageProofError::StorageValueDecodeFailed(_) - )), - ); - } - - #[test] - fn message_proof_is_rejected_if_it_is_empty() { - assert_eq!( - using_messages_proof(0, None, encode_all_messages, encode_lane_data, |proof| { - target::verify_messages_proof::(proof, 0) - },), - Err(VerificationError::EmptyMessageProof), - ); - } - - #[test] - fn non_empty_message_proof_without_messages_is_accepted() { - assert_eq!( - using_messages_proof( - 0, - Some(OutboundLaneData { - oldest_unpruned_nonce: 1, - latest_received_nonce: 1, - latest_generated_nonce: 1, - }), - encode_all_messages, - encode_lane_data, - |proof| target::verify_messages_proof::(proof, 0), - ), - Ok(vec![( - TEST_LANE_ID, - ProvedLaneMessages { - lane_state: Some(OutboundLaneData { - oldest_unpruned_nonce: 1, - latest_received_nonce: 1, - latest_generated_nonce: 1, - }), - messages: Vec::new(), - }, - )] - .into_iter() - .collect()), - ); - } - - #[test] - fn non_empty_message_proof_is_accepted() { - assert_eq!( - using_messages_proof( - 1, - Some(OutboundLaneData { - oldest_unpruned_nonce: 1, - latest_received_nonce: 1, - latest_generated_nonce: 1, - }), - encode_all_messages, - encode_lane_data, - |proof| target::verify_messages_proof::(proof, 1), - ), - Ok(vec![( - TEST_LANE_ID, - ProvedLaneMessages { - lane_state: Some(OutboundLaneData { - oldest_unpruned_nonce: 1, - latest_received_nonce: 1, - latest_generated_nonce: 1, - }), - messages: vec![Message { - key: MessageKey { lane_id: TEST_LANE_ID, nonce: 1 }, - payload: vec![42], - }], - }, - )] - .into_iter() - .collect()), - ); - } - - #[test] - fn verify_messages_proof_does_not_panic_if_messages_count_mismatches() { - assert_eq!( - using_messages_proof(1, None, encode_all_messages, encode_lane_data, |mut proof| { - proof.nonces_end = u64::MAX; - target::verify_messages_proof::(proof, u32::MAX) - },), - Err(VerificationError::MessagesCountMismatch), - ); - } -} diff --git a/bridges/bin/runtime-common/src/messages_benchmarking.rs b/bridges/bin/runtime-common/src/messages_benchmarking.rs index 74494f7908045fac601b4c3f64a456ad12dacd6f..1880e65547fe6d5e0af71e6ec7c6e0e214f20866 100644 --- a/bridges/bin/runtime-common/src/messages_benchmarking.rs +++ b/bridges/bin/runtime-common/src/messages_benchmarking.rs @@ -19,23 +19,22 @@ #![cfg(feature = "runtime-benchmarks")] -use crate::{ - messages::{ - source::FromBridgedChainMessagesDeliveryProof, target::FromBridgedChainMessagesProof, - AccountIdOf, BridgedChain, HashOf, MessageBridge, ThisChain, - }, +use bp_messages::{ + source_chain::FromBridgedChainMessagesDeliveryProof, + target_chain::FromBridgedChainMessagesProof, MessagePayload, +}; +use bp_polkadot_core::parachains::ParaHash; +use bp_runtime::{AccountIdOf, Chain, HashOf, Parachain}; +use codec::Encode; +use frame_support::weights::Weight; +use pallet_bridge_messages::{ + benchmarking::{MessageDeliveryProofParams, MessageProofParams}, messages_generation::{ encode_all_messages, encode_lane_data, prepare_message_delivery_storage_proof, prepare_messages_storage_proof, }, + BridgedChainOf, ThisChainOf, }; - -use bp_messages::MessagePayload; -use bp_polkadot_core::parachains::ParaHash; -use bp_runtime::{Chain, Parachain, StorageProofSize, UnderlyingChainOf}; -use codec::Encode; -use frame_support::weights::Weight; -use pallet_bridge_messages::benchmarking::{MessageDeliveryProofParams, MessageProofParams}; use sp_runtime::traits::{Header, Zero}; use sp_std::prelude::*; use xcm::latest::prelude::*; @@ -45,11 +44,7 @@ fn prepare_inbound_message( params: &MessageProofParams, successful_dispatch_message_generator: impl Fn(usize) -> MessagePayload, ) -> MessagePayload { - // we only care about **this** message size when message proof needs to be `Minimal` - let expected_size = match params.size { - StorageProofSize::Minimal(size) => size as usize, - _ => 0, - }; + let expected_size = params.proof_params.db_size.unwrap_or(0) as usize; // if we don't need a correct message, then we may just return some random blob if !params.is_successful_dispatch_expected { @@ -75,25 +70,32 @@ fn prepare_inbound_message( /// This method is intended to be used when benchmarking pallet, linked to the chain that /// uses GRANDPA finality. For parachains, please use the `prepare_message_proof_from_parachain` /// function. -pub fn prepare_message_proof_from_grandpa_chain( +pub fn prepare_message_proof_from_grandpa_chain( params: MessageProofParams, message_generator: impl Fn(usize) -> MessagePayload, -) -> (FromBridgedChainMessagesProof>>, Weight) +) -> (FromBridgedChainMessagesProof>>, Weight) where - R: pallet_bridge_grandpa::Config>>, + R: pallet_bridge_grandpa::Config> + + pallet_bridge_messages::Config< + MI, + BridgedHeaderChain = pallet_bridge_grandpa::Pallet, + >, FI: 'static, - B: MessageBridge, + MI: 'static, { // prepare storage proof - let (state_root, storage_proof) = prepare_messages_storage_proof::( - params.lane, - params.message_nonces.clone(), - params.outbound_lane_data.clone(), - params.size, - prepare_inbound_message(¶ms, message_generator), - encode_all_messages, - encode_lane_data, - ); + let (state_root, storage_proof) = + prepare_messages_storage_proof::, ThisChainOf>( + params.lane, + params.message_nonces.clone(), + params.outbound_lane_data.clone(), + params.proof_params, + |_| prepare_inbound_message(¶ms, &message_generator), + encode_all_messages, + encode_lane_data, + false, + false, + ); // update runtime storage let (_, bridged_header_hash) = insert_header_to_grandpa_pallet::(state_root); @@ -118,30 +120,33 @@ where /// This method is intended to be used when benchmarking pallet, linked to the chain that /// uses parachain finality. For GRANDPA chains, please use the /// `prepare_message_proof_from_grandpa_chain` function. -pub fn prepare_message_proof_from_parachain( +pub fn prepare_message_proof_from_parachain( params: MessageProofParams, message_generator: impl Fn(usize) -> MessagePayload, -) -> (FromBridgedChainMessagesProof>>, Weight) +) -> (FromBridgedChainMessagesProof>>, Weight) where - R: pallet_bridge_parachains::Config, + R: pallet_bridge_parachains::Config + pallet_bridge_messages::Config, PI: 'static, - B: MessageBridge, - UnderlyingChainOf>: Chain + Parachain, + MI: 'static, + BridgedChainOf: Chain + Parachain, { // prepare storage proof - let (state_root, storage_proof) = prepare_messages_storage_proof::( - params.lane, - params.message_nonces.clone(), - params.outbound_lane_data.clone(), - params.size, - prepare_inbound_message(¶ms, message_generator), - encode_all_messages, - encode_lane_data, - ); + let (state_root, storage_proof) = + prepare_messages_storage_proof::, ThisChainOf>( + params.lane, + params.message_nonces.clone(), + params.outbound_lane_data.clone(), + params.proof_params, + |_| prepare_inbound_message(¶ms, &message_generator), + encode_all_messages, + encode_lane_data, + false, + false, + ); // update runtime storage let (_, bridged_header_hash) = - insert_header_to_parachains_pallet::>>(state_root); + insert_header_to_parachains_pallet::>(state_root); ( FromBridgedChainMessagesProof { @@ -160,21 +165,24 @@ where /// This method is intended to be used when benchmarking pallet, linked to the chain that /// uses GRANDPA finality. For parachains, please use the /// `prepare_message_delivery_proof_from_parachain` function. -pub fn prepare_message_delivery_proof_from_grandpa_chain( - params: MessageDeliveryProofParams>>, -) -> FromBridgedChainMessagesDeliveryProof>> +pub fn prepare_message_delivery_proof_from_grandpa_chain( + params: MessageDeliveryProofParams>>, +) -> FromBridgedChainMessagesDeliveryProof>> where - R: pallet_bridge_grandpa::Config>>, + R: pallet_bridge_grandpa::Config> + + pallet_bridge_messages::Config< + MI, + BridgedHeaderChain = pallet_bridge_grandpa::Pallet, + >, FI: 'static, - B: MessageBridge, + MI: 'static, { // prepare storage proof let lane = params.lane; - let (state_root, storage_proof) = prepare_message_delivery_storage_proof::( - params.lane, - params.inbound_lane_data, - params.size, - ); + let (state_root, storage_proof) = prepare_message_delivery_storage_proof::< + BridgedChainOf, + ThisChainOf, + >(params.lane, params.inbound_lane_data, params.proof_params); // update runtime storage let (_, bridged_header_hash) = insert_header_to_grandpa_pallet::(state_root); @@ -191,26 +199,25 @@ where /// This method is intended to be used when benchmarking pallet, linked to the chain that /// uses parachain finality. For GRANDPA chains, please use the /// `prepare_message_delivery_proof_from_grandpa_chain` function. -pub fn prepare_message_delivery_proof_from_parachain( - params: MessageDeliveryProofParams>>, -) -> FromBridgedChainMessagesDeliveryProof>> +pub fn prepare_message_delivery_proof_from_parachain( + params: MessageDeliveryProofParams>>, +) -> FromBridgedChainMessagesDeliveryProof>> where - R: pallet_bridge_parachains::Config, + R: pallet_bridge_parachains::Config + pallet_bridge_messages::Config, PI: 'static, - B: MessageBridge, - UnderlyingChainOf>: Chain + Parachain, + MI: 'static, + BridgedChainOf: Chain + Parachain, { // prepare storage proof let lane = params.lane; - let (state_root, storage_proof) = prepare_message_delivery_storage_proof::( - params.lane, - params.inbound_lane_data, - params.size, - ); + let (state_root, storage_proof) = prepare_message_delivery_storage_proof::< + BridgedChainOf, + ThisChainOf, + >(params.lane, params.inbound_lane_data, params.proof_params); // update runtime storage let (_, bridged_header_hash) = - insert_header_to_parachains_pallet::>>(state_root); + insert_header_to_parachains_pallet::>(state_root); FromBridgedChainMessagesDeliveryProof { bridged_header_hash: bridged_header_hash.into(), diff --git a/bridges/bin/runtime-common/src/messages_call_ext.rs b/bridges/bin/runtime-common/src/messages_call_ext.rs index fb07f7b6dd69110918af23b227708e226bede625..a9ee1969ae0ca462f36098f03b4454e1399af129 100644 --- a/bridges/bin/runtime-common/src/messages_call_ext.rs +++ b/bridges/bin/runtime-common/src/messages_call_ext.rs @@ -14,19 +14,14 @@ // You should have received a copy of the GNU General Public License // along with Parity Bridges Common. If not, see . -//! Signed extension for the `pallet-bridge-messages` that is able to reject obsolete -//! (and some other invalid) transactions. +//! Helpers for easier manipulation of call processing with signed extensions. -use crate::messages::{ - source::FromBridgedChainMessagesDeliveryProof, target::FromBridgedChainMessagesProof, +use bp_messages::{ + target_chain::MessageDispatch, ChainWithMessages, InboundLaneData, LaneId, MessageNonce, }; -use bp_messages::{target_chain::MessageDispatch, InboundLaneData, LaneId, MessageNonce}; -use bp_runtime::OwnedBridgeModule; -use frame_support::{ - dispatch::CallableCallFor, - traits::{Get, IsSubType}, -}; -use pallet_bridge_messages::{Config, Pallet}; +use bp_runtime::{AccountIdOf, OwnedBridgeModule}; +use frame_support::{dispatch::CallableCallFor, traits::IsSubType}; +use pallet_bridge_messages::{BridgedChainOf, Config, Pallet}; use sp_runtime::{transaction_validity::TransactionValidity, RuntimeDebug}; use sp_std::ops::RangeInclusive; @@ -213,18 +208,8 @@ pub trait MessagesCallSubType, I: 'static>: } impl< - BridgedHeaderHash, - SourceHeaderChain: bp_messages::target_chain::SourceHeaderChain< - MessagesProof = FromBridgedChainMessagesProof, - >, - TargetHeaderChain: bp_messages::source_chain::TargetHeaderChain< - >::OutboundPayload, - ::AccountId, - MessagesDeliveryProof = FromBridgedChainMessagesDeliveryProof, - >, Call: IsSubType, T>>, - T: frame_system::Config - + Config, + T: frame_system::Config + Config, I: 'static, > MessagesCallSubType for T::RuntimeCall { @@ -340,16 +325,17 @@ impl< /// Returns occupation state of unrewarded relayers vector. fn unrewarded_relayers_occupation, I: 'static>( - inbound_lane_data: &InboundLaneData, + inbound_lane_data: &InboundLaneData>>, ) -> UnrewardedRelayerOccupation { UnrewardedRelayerOccupation { - free_relayer_slots: T::MaxUnrewardedRelayerEntriesAtInboundLane::get() + free_relayer_slots: T::BridgedChain::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX .saturating_sub(inbound_lane_data.relayers.len() as MessageNonce), free_message_slots: { let unconfirmed_messages = inbound_lane_data .last_delivered_nonce() .saturating_sub(inbound_lane_data.last_confirmed_nonce); - T::MaxUnconfirmedMessagesAtInboundLane::get().saturating_sub(unconfirmed_messages) + T::BridgedChain::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX + .saturating_sub(unconfirmed_messages) }, } } @@ -358,22 +344,20 @@ fn unrewarded_relayers_occupation, I: 'static>( mod tests { use super::*; use crate::{ - messages::{ - source::FromBridgedChainMessagesDeliveryProof, target::FromBridgedChainMessagesProof, - }, messages_call_ext::MessagesCallSubType, - mock::{ - DummyMessageDispatch, MaxUnconfirmedMessagesAtInboundLane, - MaxUnrewardedRelayerEntriesAtInboundLane, TestRuntime, ThisChainRuntimeCall, - }, + mock::{BridgedUnderlyingChain, DummyMessageDispatch, TestRuntime, ThisChainRuntimeCall}, + }; + use bp_messages::{ + source_chain::FromBridgedChainMessagesDeliveryProof, + target_chain::FromBridgedChainMessagesProof, DeliveredMessages, UnrewardedRelayer, + UnrewardedRelayersState, }; - use bp_messages::{DeliveredMessages, UnrewardedRelayer, UnrewardedRelayersState}; use sp_std::ops::RangeInclusive; fn fill_unrewarded_relayers() { let mut inbound_lane_state = pallet_bridge_messages::InboundLanes::::get(LaneId([0, 0, 0, 0])); - for n in 0..MaxUnrewardedRelayerEntriesAtInboundLane::get() { + for n in 0..BridgedUnderlyingChain::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX { inbound_lane_state.relayers.push_back(UnrewardedRelayer { relayer: Default::default(), messages: DeliveredMessages { begin: n + 1, end: n + 1 }, @@ -392,7 +376,7 @@ mod tests { relayer: Default::default(), messages: DeliveredMessages { begin: 1, - end: MaxUnconfirmedMessagesAtInboundLane::get(), + end: BridgedUnderlyingChain::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX, }, }); pallet_bridge_messages::InboundLanes::::insert( @@ -418,13 +402,13 @@ mod tests { messages_count: nonces_end.checked_sub(nonces_start).map(|x| x + 1).unwrap_or(0) as u32, dispatch_weight: frame_support::weights::Weight::zero(), - proof: FromBridgedChainMessagesProof { + proof: Box::new(FromBridgedChainMessagesProof { bridged_header_hash: Default::default(), - storage_proof: vec![], + storage_proof: Default::default(), lane: LaneId([0, 0, 0, 0]), nonces_start, nonces_end, - }, + }), }, ) .check_obsolete_call() @@ -508,8 +492,8 @@ mod tests { sp_io::TestExternalities::new(Default::default()).execute_with(|| { fill_unrewarded_messages(); assert!(validate_message_delivery( - MaxUnconfirmedMessagesAtInboundLane::get(), - MaxUnconfirmedMessagesAtInboundLane::get() - 1 + BridgedUnderlyingChain::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX, + BridgedUnderlyingChain::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX - 1 )); }); } @@ -540,7 +524,7 @@ mod tests { pallet_bridge_messages::Call::::receive_messages_delivery_proof { proof: FromBridgedChainMessagesDeliveryProof { bridged_header_hash: Default::default(), - storage_proof: Vec::new(), + storage_proof: Default::default(), lane: LaneId([0, 0, 0, 0]), }, relayers_state: UnrewardedRelayersState { @@ -608,7 +592,7 @@ mod tests { free_message_slots: if is_empty { 0 } else { - MaxUnconfirmedMessagesAtInboundLane::get() + BridgedUnderlyingChain::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX }, }, }, diff --git a/bridges/bin/runtime-common/src/mock.rs b/bridges/bin/runtime-common/src/mock.rs index f49474667896049cfd6aff4bf4a4b0d9d6e73c95..2f248a7162a6cbdcc09d2980a922b1a065127e40 100644 --- a/bridges/bin/runtime-common/src/mock.rs +++ b/bridges/bin/runtime-common/src/mock.rs @@ -18,26 +18,16 @@ #![cfg(test)] -use crate::messages::{ - source::{ - FromThisChainMaximalOutboundPayloadSize, FromThisChainMessagePayload, - TargetHeaderChainAdapter, - }, - target::{FromBridgedChainMessagePayload, SourceHeaderChainAdapter}, - BridgedChainWithMessages, HashOf, MessageBridge, ThisChainWithMessages, -}; +use crate::messages_xcm_extension::XcmAsPlainPayload; -use bp_header_chain::{ChainWithGrandpa, HeaderChain}; +use bp_header_chain::ChainWithGrandpa; use bp_messages::{ target_chain::{DispatchMessage, MessageDispatch}, - LaneId, MessageNonce, + ChainWithMessages, LaneId, MessageNonce, }; use bp_parachains::SingleParaStoredHeaderDataBuilder; use bp_relayers::PayRewardFromAccount; -use bp_runtime::{ - messages::MessageDispatchResult, Chain, ChainId, Parachain, UnderlyingChainProvider, -}; -use codec::{Decode, Encode}; +use bp_runtime::{messages::MessageDispatchResult, Chain, ChainId, Parachain}; use frame_support::{ derive_impl, parameter_types, weights::{ConstantMultiplier, IdentityFee, RuntimeDbWeight, Weight}, @@ -46,7 +36,7 @@ use pallet_transaction_payment::Multiplier; use sp_runtime::{ testing::H256, traits::{BlakeTwo256, ConstU32, ConstU64, ConstU8}, - FixedPointNumber, Perquintill, + FixedPointNumber, Perquintill, StateVersion, }; /// Account identifier at `ThisChain`. @@ -61,8 +51,6 @@ pub type ThisChainHash = H256; pub type ThisChainHasher = BlakeTwo256; /// Runtime call at `ThisChain`. pub type ThisChainRuntimeCall = RuntimeCall; -/// Runtime call origin at `ThisChain`. -pub type ThisChainCallOrigin = RuntimeOrigin; /// Header of `ThisChain`. pub type ThisChainHeader = sp_runtime::generic::Header; /// Block of `ThisChain`. @@ -100,8 +88,6 @@ pub type TestStakeAndSlash = pallet_bridge_relayers::StakeAndSlashNamed< pub const TEST_LANE_ID: LaneId = LaneId([0, 0, 0, 0]); /// Bridged chain id used in tests. pub const TEST_BRIDGED_CHAIN_ID: ChainId = *b"brdg"; -/// Maximal extrinsic weight at the `BridgedChain`. -pub const BRIDGED_CHAIN_MAX_EXTRINSIC_WEIGHT: usize = 2048; /// Maximal extrinsic size at the `BridgedChain`. pub const BRIDGED_CHAIN_MAX_EXTRINSIC_SIZE: u32 = 1024; @@ -126,7 +112,6 @@ crate::generate_bridge_reject_obsolete_headers_and_messages! { parameter_types! { pub const ActiveOutboundLanes: &'static [LaneId] = &[TEST_LANE_ID]; - pub const BridgedChainId: ChainId = TEST_BRIDGED_CHAIN_ID; pub const BridgedParasPalletName: &'static str = "Paras"; pub const ExistentialDeposit: ThisChainBalance = 500; pub const DbWeight: RuntimeDbWeight = RuntimeDbWeight { read: 1, write: 2 }; @@ -136,8 +121,6 @@ parameter_types! { pub AdjustmentVariable: Multiplier = Multiplier::saturating_from_rational(3, 100_000); pub MinimumMultiplier: Multiplier = Multiplier::saturating_from_rational(1, 1_000_000u128); pub MaximumMultiplier: Multiplier = sp_runtime::traits::Bounded::max_value(); - pub const MaxUnrewardedRelayerEntriesAtInboundLane: MessageNonce = 16; - pub const MaxUnconfirmedMessagesAtInboundLane: MessageNonce = 1_000; pub const ReserveId: [u8; 8] = *b"brdgrlrs"; } @@ -203,17 +186,12 @@ impl pallet_bridge_messages::Config for TestRuntime { type RuntimeEvent = RuntimeEvent; type WeightInfo = pallet_bridge_messages::weights::BridgeWeight; type ActiveOutboundLanes = ActiveOutboundLanes; - type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane; - type MaxUnconfirmedMessagesAtInboundLane = MaxUnconfirmedMessagesAtInboundLane; - type MaximalOutboundPayloadSize = FromThisChainMaximalOutboundPayloadSize; - type OutboundPayload = FromThisChainMessagePayload; + type OutboundPayload = XcmAsPlainPayload; - type InboundPayload = FromBridgedChainMessagePayload; - type InboundRelayer = BridgedChainAccountId; + type InboundPayload = Vec; type DeliveryPayments = (); - type TargetHeaderChain = TargetHeaderChainAdapter; type DeliveryConfirmationPayments = pallet_bridge_relayers::DeliveryConfirmationPaymentsAdapter< TestRuntime, (), @@ -221,9 +199,11 @@ impl pallet_bridge_messages::Config for TestRuntime { >; type OnMessagesDelivered = (); - type SourceHeaderChain = SourceHeaderChainAdapter; type MessageDispatch = DummyMessageDispatch; - type BridgedChainId = BridgedChainId; + + type ThisChain = ThisUnderlyingChain; + type BridgedChain = BridgedUnderlyingChain; + type BridgedHeaderChain = BridgeGrandpa; } impl pallet_bridge_relayers::Config for TestRuntime { @@ -262,55 +242,6 @@ impl MessageDispatch for DummyMessageDispatch { } } -/// Bridge that is deployed on `ThisChain` and allows sending/receiving messages to/from -/// `BridgedChain`. -#[derive(Debug, PartialEq, Eq)] -pub struct OnThisChainBridge; - -impl MessageBridge for OnThisChainBridge { - const BRIDGED_MESSAGES_PALLET_NAME: &'static str = ""; - - type ThisChain = ThisChain; - type BridgedChain = BridgedChain; - type BridgedHeaderChain = pallet_bridge_grandpa::GrandpaChainHeaders; -} - -/// Bridge that is deployed on `BridgedChain` and allows sending/receiving messages to/from -/// `ThisChain`. -#[derive(Debug, PartialEq, Eq)] -pub struct OnBridgedChainBridge; - -impl MessageBridge for OnBridgedChainBridge { - const BRIDGED_MESSAGES_PALLET_NAME: &'static str = ""; - - type ThisChain = BridgedChain; - type BridgedChain = ThisChain; - type BridgedHeaderChain = ThisHeaderChain; -} - -/// Dummy implementation of `HeaderChain` for `ThisChain` at the `BridgedChain`. -pub struct ThisHeaderChain; - -impl HeaderChain for ThisHeaderChain { - fn finalized_header_state_root(_hash: HashOf) -> Option> { - unreachable!() - } -} - -/// Call origin at `BridgedChain`. -#[derive(Clone, Debug)] -pub struct BridgedChainOrigin; - -impl From - for Result, BridgedChainOrigin> -{ - fn from( - _origin: BridgedChainOrigin, - ) -> Result, BridgedChainOrigin> { - unreachable!() - } -} - /// Underlying chain of `ThisChain`. pub struct ThisUnderlyingChain; @@ -326,6 +257,8 @@ impl Chain for ThisUnderlyingChain { type Nonce = u32; type Signature = sp_runtime::MultiSignature; + const STATE_VERSION: StateVersion = StateVersion::V1; + fn max_extrinsic_size() -> u32 { BRIDGED_CHAIN_MAX_EXTRINSIC_SIZE } @@ -335,29 +268,20 @@ impl Chain for ThisUnderlyingChain { } } -/// The chain where we are in tests. -pub struct ThisChain; - -impl UnderlyingChainProvider for ThisChain { - type Chain = ThisUnderlyingChain; -} +impl ChainWithMessages for ThisUnderlyingChain { + const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str = ""; -impl ThisChainWithMessages for ThisChain { - type RuntimeOrigin = ThisChainCallOrigin; + const MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX: MessageNonce = 16; + const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce = 1000; } -impl BridgedChainWithMessages for ThisChain {} - /// Underlying chain of `BridgedChain`. pub struct BridgedUnderlyingChain; /// Some parachain under `BridgedChain` consensus. pub struct BridgedUnderlyingParachain; -/// Runtime call of the `BridgedChain`. -#[derive(Decode, Encode)] -pub struct BridgedChainCall; impl Chain for BridgedUnderlyingChain { - const ID: ChainId = *b"buch"; + const ID: ChainId = TEST_BRIDGED_CHAIN_ID; type BlockNumber = BridgedChainBlockNumber; type Hash = BridgedChainHash; @@ -368,6 +292,8 @@ impl Chain for BridgedUnderlyingChain { type Nonce = u32; type Signature = sp_runtime::MultiSignature; + const STATE_VERSION: StateVersion = StateVersion::V1; + fn max_extrinsic_size() -> u32 { BRIDGED_CHAIN_MAX_EXTRINSIC_SIZE } @@ -384,6 +310,12 @@ impl ChainWithGrandpa for BridgedUnderlyingChain { const AVERAGE_HEADER_SIZE: u32 = 64; } +impl ChainWithMessages for BridgedUnderlyingChain { + const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str = ""; + const MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX: MessageNonce = 16; + const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce = 1000; +} + impl Chain for BridgedUnderlyingParachain { const ID: ChainId = *b"bupc"; @@ -396,6 +328,8 @@ impl Chain for BridgedUnderlyingParachain { type Nonce = u32; type Signature = sp_runtime::MultiSignature; + const STATE_VERSION: StateVersion = StateVersion::V1; + fn max_extrinsic_size() -> u32 { BRIDGED_CHAIN_MAX_EXTRINSIC_SIZE } @@ -409,19 +343,6 @@ impl Parachain for BridgedUnderlyingParachain { const MAX_HEADER_SIZE: u32 = 1_024; } -/// The other, bridged chain, used in tests. -pub struct BridgedChain; - -impl UnderlyingChainProvider for BridgedChain { - type Chain = BridgedUnderlyingChain; -} - -impl ThisChainWithMessages for BridgedChain { - type RuntimeOrigin = BridgedChainOrigin; -} - -impl BridgedChainWithMessages for BridgedChain {} - /// Run test within test externalities. pub fn run_test(test: impl FnOnce()) { sp_io::TestExternalities::new(Default::default()).execute_with(test) diff --git a/bridges/bin/runtime-common/src/parachains_benchmarking.rs b/bridges/bin/runtime-common/src/parachains_benchmarking.rs index b3050b9ac0f3ccec617399d3eb91647dcab7eb3d..bcbd779b44dea5fbef7781335cfa1d359ab8c1f1 100644 --- a/bridges/bin/runtime-common/src/parachains_benchmarking.rs +++ b/bridges/bin/runtime-common/src/parachains_benchmarking.rs @@ -18,14 +18,11 @@ #![cfg(feature = "runtime-benchmarks")] -use crate::{ - messages_benchmarking::insert_header_to_grandpa_pallet, - messages_generation::grow_trie_leaf_value, -}; +use crate::messages_benchmarking::insert_header_to_grandpa_pallet; use bp_parachains::parachain_head_storage_key_at_source; use bp_polkadot_core::parachains::{ParaHash, ParaHead, ParaHeadsProof, ParaId}; -use bp_runtime::{record_all_trie_keys, StorageProofSize}; +use bp_runtime::{grow_storage_value, record_all_trie_keys, Chain, UnverifiedStorageProofParams}; use codec::Encode; use frame_support::traits::Get; use pallet_bridge_parachains::{RelayBlockHash, RelayBlockHasher, RelayBlockNumber}; @@ -39,14 +36,14 @@ use sp_trie::{trie_types::TrieDBMutBuilderV1, LayoutV1, MemoryDB, TrieMut}; pub fn prepare_parachain_heads_proof( parachains: &[ParaId], parachain_head_size: u32, - size: StorageProofSize, + proof_params: UnverifiedStorageProofParams, ) -> (RelayBlockNumber, RelayBlockHash, ParaHeadsProof, Vec<(ParaId, ParaHash)>) where R: pallet_bridge_parachains::Config + pallet_bridge_grandpa::Config, PI: 'static, >::BridgedChain: - bp_runtime::Chain, + Chain, { let parachain_head = ParaHead(vec![0u8; parachain_head_size as usize]); @@ -64,7 +61,7 @@ where let storage_key = parachain_head_storage_key_at_source(R::ParasPalletName::get(), *parachain); let leaf_data = if i == 0 { - grow_trie_leaf_value(parachain_head.encode(), size) + grow_storage_value(parachain_head.encode(), &proof_params) } else { parachain_head.encode() }; diff --git a/bridges/chains/chain-bridge-hub-kusama/src/lib.rs b/bridges/chains/chain-bridge-hub-kusama/src/lib.rs index ef3ef4ab7b7a9bc111218e3c53091ac232f34721..c990e8a12f367cafbd35b0693b323a6ec5fb5e96 100644 --- a/bridges/chains/chain-bridge-hub-kusama/src/lib.rs +++ b/bridges/chains/chain-bridge-hub-kusama/src/lib.rs @@ -29,7 +29,7 @@ use frame_support::{ dispatch::DispatchClass, sp_runtime::{MultiAddress, MultiSigner}, }; -use sp_runtime::RuntimeDebug; +use sp_runtime::{RuntimeDebug, StateVersion}; /// BridgeHubKusama parachain. #[derive(RuntimeDebug)] @@ -48,6 +48,8 @@ impl Chain for BridgeHubKusama { type Nonce = Nonce; type Signature = Signature; + const STATE_VERSION: StateVersion = StateVersion::V1; + fn max_extrinsic_size() -> u32 { *BlockLength::get().max.get(DispatchClass::Normal) } diff --git a/bridges/chains/chain-bridge-hub-polkadot/src/lib.rs b/bridges/chains/chain-bridge-hub-polkadot/src/lib.rs index 9db71af928e5df01170cf4ab8bf5f20cd72f7610..7379b8863b1de5c1a1482db90077e958f0a33366 100644 --- a/bridges/chains/chain-bridge-hub-polkadot/src/lib.rs +++ b/bridges/chains/chain-bridge-hub-polkadot/src/lib.rs @@ -26,7 +26,7 @@ use bp_runtime::{ decl_bridge_finality_runtime_apis, decl_bridge_messages_runtime_apis, Chain, ChainId, Parachain, }; use frame_support::dispatch::DispatchClass; -use sp_runtime::RuntimeDebug; +use sp_runtime::{RuntimeDebug, StateVersion}; /// BridgeHubPolkadot parachain. #[derive(RuntimeDebug)] @@ -45,6 +45,8 @@ impl Chain for BridgeHubPolkadot { type Nonce = Nonce; type Signature = Signature; + const STATE_VERSION: StateVersion = StateVersion::V1; + fn max_extrinsic_size() -> u32 { *BlockLength::get().max.get(DispatchClass::Normal) } diff --git a/bridges/chains/chain-bridge-hub-rococo/src/lib.rs b/bridges/chains/chain-bridge-hub-rococo/src/lib.rs index d7097f01c5316a58851f400a86b98eda3d7e8bcc..73af997b9950ef640040e44cbba0b93b6a7a56a3 100644 --- a/bridges/chains/chain-bridge-hub-rococo/src/lib.rs +++ b/bridges/chains/chain-bridge-hub-rococo/src/lib.rs @@ -25,8 +25,10 @@ use bp_messages::*; use bp_runtime::{ decl_bridge_finality_runtime_apis, decl_bridge_messages_runtime_apis, Chain, ChainId, Parachain, }; -use frame_support::dispatch::DispatchClass; -use sp_runtime::{MultiAddress, MultiSigner, RuntimeDebug}; +use frame_support::{ + dispatch::DispatchClass, + sp_runtime::{MultiAddress, MultiSigner, RuntimeDebug, StateVersion}, +}; /// BridgeHubRococo parachain. #[derive(RuntimeDebug)] @@ -45,6 +47,8 @@ impl Chain for BridgeHubRococo { type Nonce = Nonce; type Signature = Signature; + const STATE_VERSION: StateVersion = StateVersion::V1; + fn max_extrinsic_size() -> u32 { *BlockLength::get().max.get(DispatchClass::Normal) } @@ -103,10 +107,10 @@ frame_support::parameter_types! { pub const BridgeHubRococoBaseXcmFeeInRocs: u128 = 59_034_266; /// Transaction fee that is paid at the Rococo BridgeHub for delivering single inbound message. - /// (initially was calculated by test `BridgeHubRococo::can_calculate_fee_for_complex_message_delivery_transaction` + `33%`) + /// (initially was calculated by test `BridgeHubRococo::can_calculate_fee_for_standalone_message_delivery_transaction` + `33%`) pub const BridgeHubRococoBaseDeliveryFeeInRocs: u128 = 314_037_860; /// Transaction fee that is paid at the Rococo BridgeHub for delivering single outbound message confirmation. - /// (initially was calculated by test `BridgeHubRococo::can_calculate_fee_for_complex_message_confirmation_transaction` + `33%`) + /// (initially was calculated by test `BridgeHubRococo::can_calculate_fee_for_standalone_message_confirmation_transaction` + `33%`) pub const BridgeHubRococoBaseConfirmationFeeInRocs: u128 = 57_414_813; } diff --git a/bridges/chains/chain-bridge-hub-westend/src/lib.rs b/bridges/chains/chain-bridge-hub-westend/src/lib.rs index 800f290d7bfa41cec4139e80a7dc9ea8962a6da5..17ff2c858a1d3eeae329cb972d95adc32952ede4 100644 --- a/bridges/chains/chain-bridge-hub-westend/src/lib.rs +++ b/bridges/chains/chain-bridge-hub-westend/src/lib.rs @@ -25,7 +25,7 @@ use bp_runtime::{ decl_bridge_finality_runtime_apis, decl_bridge_messages_runtime_apis, Chain, ChainId, Parachain, }; use frame_support::dispatch::DispatchClass; -use sp_runtime::RuntimeDebug; +use sp_runtime::{RuntimeDebug, StateVersion}; /// BridgeHubWestend parachain. #[derive(RuntimeDebug)] @@ -44,6 +44,8 @@ impl Chain for BridgeHubWestend { type Nonce = Nonce; type Signature = Signature; + const STATE_VERSION: StateVersion = StateVersion::V1; + fn max_extrinsic_size() -> u32 { *BlockLength::get().max.get(DispatchClass::Normal) } diff --git a/bridges/chains/chain-kusama/src/lib.rs b/bridges/chains/chain-kusama/src/lib.rs index fd7172c5869d468ff534e54f9ef6278cf86a88ed..dcd0b23abbbefa2dfba741d6934b5d5510c93017 100644 --- a/bridges/chains/chain-kusama/src/lib.rs +++ b/bridges/chains/chain-kusama/src/lib.rs @@ -23,7 +23,7 @@ pub use bp_polkadot_core::*; use bp_header_chain::ChainWithGrandpa; use bp_runtime::{decl_bridge_finality_runtime_apis, Chain, ChainId}; -use frame_support::weights::Weight; +use frame_support::{sp_runtime::StateVersion, weights::Weight}; /// Kusama Chain pub struct Kusama; @@ -41,6 +41,8 @@ impl Chain for Kusama { type Nonce = Nonce; type Signature = Signature; + const STATE_VERSION: StateVersion = StateVersion::V0; + fn max_extrinsic_size() -> u32 { max_extrinsic_size() } diff --git a/bridges/chains/chain-polkadot-bulletin/src/lib.rs b/bridges/chains/chain-polkadot-bulletin/src/lib.rs index f3d300567f2b4f92cec272e0929a3c53d718c823..88980a9575016bd5c5e1428329454e8131a2075d 100644 --- a/bridges/chains/chain-polkadot-bulletin/src/lib.rs +++ b/bridges/chains/chain-polkadot-bulletin/src/lib.rs @@ -37,7 +37,9 @@ use frame_support::{ }; use frame_system::limits; use scale_info::TypeInfo; -use sp_runtime::{traits::DispatchInfoOf, transaction_validity::TransactionValidityError, Perbill}; +use sp_runtime::{ + traits::DispatchInfoOf, transaction_validity::TransactionValidityError, Perbill, StateVersion, +}; // This chain reuses most of Polkadot primitives. pub use bp_polkadot_core::{ @@ -192,6 +194,8 @@ impl Chain for PolkadotBulletin { type Nonce = Nonce; type Signature = Signature; + const STATE_VERSION: StateVersion = StateVersion::V1; + fn max_extrinsic_size() -> u32 { *BlockLength::get().max.get(DispatchClass::Normal) } diff --git a/bridges/chains/chain-polkadot/src/lib.rs b/bridges/chains/chain-polkadot/src/lib.rs index a8cac0467d574e9355a8fe9ba2e7c2378019349d..f4b262d40735d7470a4d7e289f24bc1d4556d039 100644 --- a/bridges/chains/chain-polkadot/src/lib.rs +++ b/bridges/chains/chain-polkadot/src/lib.rs @@ -25,7 +25,7 @@ use bp_header_chain::ChainWithGrandpa; use bp_runtime::{ decl_bridge_finality_runtime_apis, extensions::PrevalidateAttests, Chain, ChainId, }; -use frame_support::weights::Weight; +use frame_support::{sp_runtime::StateVersion, weights::Weight}; /// Polkadot Chain pub struct Polkadot; @@ -43,6 +43,8 @@ impl Chain for Polkadot { type Nonce = Nonce; type Signature = Signature; + const STATE_VERSION: StateVersion = StateVersion::V0; + fn max_extrinsic_size() -> u32 { max_extrinsic_size() } diff --git a/bridges/chains/chain-rococo/src/lib.rs b/bridges/chains/chain-rococo/src/lib.rs index b290fe71c829d08130556a2b061c0d63f0787d4c..bfcafdf41ea2e629c9a58f2545016b2e776375b8 100644 --- a/bridges/chains/chain-rococo/src/lib.rs +++ b/bridges/chains/chain-rococo/src/lib.rs @@ -23,7 +23,7 @@ pub use bp_polkadot_core::*; use bp_header_chain::ChainWithGrandpa; use bp_runtime::{decl_bridge_finality_runtime_apis, Chain, ChainId}; -use frame_support::weights::Weight; +use frame_support::{sp_runtime::StateVersion, weights::Weight}; /// Rococo Chain pub struct Rococo; @@ -41,6 +41,8 @@ impl Chain for Rococo { type Nonce = Nonce; type Signature = Signature; + const STATE_VERSION: StateVersion = StateVersion::V1; + fn max_extrinsic_size() -> u32 { max_extrinsic_size() } diff --git a/bridges/chains/chain-westend/src/lib.rs b/bridges/chains/chain-westend/src/lib.rs index ef451f7de0a9640bc1a278e1c712bbb099193ceb..2a247e03e59d666d3c5dd54d74e3a4f852a60bd3 100644 --- a/bridges/chains/chain-westend/src/lib.rs +++ b/bridges/chains/chain-westend/src/lib.rs @@ -23,7 +23,7 @@ pub use bp_polkadot_core::*; use bp_header_chain::ChainWithGrandpa; use bp_runtime::{decl_bridge_finality_runtime_apis, Chain, ChainId}; -use frame_support::weights::Weight; +use frame_support::{sp_runtime::StateVersion, weights::Weight}; /// Westend Chain pub struct Westend; @@ -41,6 +41,8 @@ impl Chain for Westend { type Nonce = Nonce; type Signature = Signature; + const STATE_VERSION: StateVersion = StateVersion::V1; + fn max_extrinsic_size() -> u32 { max_extrinsic_size() } diff --git a/bridges/modules/beefy/src/mock.rs b/bridges/modules/beefy/src/mock.rs index 53efd57c29a0dfc870e43be4fec7bcdf817a3282..3b751ddf066c9562cd8fc0f054b1b103306479dd 100644 --- a/bridges/modules/beefy/src/mock.rs +++ b/bridges/modules/beefy/src/mock.rs @@ -29,6 +29,7 @@ use sp_core::{sr25519::Signature, Pair}; use sp_runtime::{ testing::{Header, H256}, traits::{BlakeTwo256, Hash}, + StateVersion, }; pub use sp_consensus_beefy::ecdsa_crypto::{AuthorityId as BeefyId, Pair as BeefyPair}; @@ -93,6 +94,8 @@ impl Chain for TestBridgedChain { type Nonce = u64; type Signature = Signature; + const STATE_VERSION: StateVersion = StateVersion::V1; + fn max_extrinsic_size() -> u32 { unreachable!() } diff --git a/bridges/modules/grandpa/Cargo.toml b/bridges/modules/grandpa/Cargo.toml index 307c7ddaaffd963e89f7b2faa7a487ce5db0dcca..6d1419ae5b030733ad9fb38a6a459ab7ce34f99f 100644 --- a/bridges/modules/grandpa/Cargo.toml +++ b/bridges/modules/grandpa/Cargo.toml @@ -14,7 +14,6 @@ workspace = true [dependencies] codec = { workspace = true } -finality-grandpa = { workspace = true } log = { workspace = true } scale-info = { features = ["derive"], workspace = true } @@ -30,13 +29,13 @@ frame-system = { workspace = true } sp-consensus-grandpa = { features = ["serde"], workspace = true } sp-runtime = { features = ["serde"], workspace = true } sp-std = { workspace = true } -sp-trie = { workspace = true } # Optional Benchmarking Dependencies bp-test-utils = { optional = true, workspace = true } frame-benchmarking = { optional = true, workspace = true } [dev-dependencies] +bp-runtime = { features = ["test-helpers"], workspace = true } sp-core = { workspace = true, default-features = true } sp-io = { workspace = true, default-features = true } @@ -47,7 +46,6 @@ std = [ "bp-runtime/std", "bp-test-utils/std", "codec/std", - "finality-grandpa/std", "frame-benchmarking/std", "frame-support/std", "frame-system/std", @@ -56,7 +54,6 @@ std = [ "sp-consensus-grandpa/std", "sp-runtime/std", "sp-std/std", - "sp-trie/std", ] runtime-benchmarks = [ "bp-test-utils", diff --git a/bridges/modules/grandpa/src/lib.rs b/bridges/modules/grandpa/src/lib.rs index 3b77f676870e1a28b8367f1b14d24c9ca83ece4a..c62951b74656b052d4858dec2af1393e41553029 100644 --- a/bridges/modules/grandpa/src/lib.rs +++ b/bridges/modules/grandpa/src/lib.rs @@ -1443,11 +1443,14 @@ mod tests { } #[test] - fn parse_finalized_storage_proof_rejects_proof_on_unknown_header() { + fn verify_storage_proof_rejects_unknown_header() { run_test(|| { assert_noop!( - Pallet::::storage_proof_checker(Default::default(), vec![],) - .map(|_| ()), + Pallet::::verify_storage_proof( + Default::default(), + Default::default(), + ) + .map(|_| ()), bp_header_chain::HeaderChainError::UnknownHeader, ); }); @@ -1465,9 +1468,7 @@ mod tests { >::put(HeaderId(2, hash)); >::insert(hash, header.build()); - assert_ok!( - Pallet::::storage_proof_checker(hash, storage_proof).map(|_| ()) - ); + assert_ok!(Pallet::::verify_storage_proof(hash, storage_proof).map(|_| ())); }); } diff --git a/bridges/modules/grandpa/src/mock.rs b/bridges/modules/grandpa/src/mock.rs index 27df9d9c78f540d0d73f74c6a86ba19af30d4b6b..71af6182e057cca3d06b98ee6fe94283b93ab77d 100644 --- a/bridges/modules/grandpa/src/mock.rs +++ b/bridges/modules/grandpa/src/mock.rs @@ -20,7 +20,8 @@ use bp_header_chain::ChainWithGrandpa; use bp_runtime::{Chain, ChainId}; use frame_support::{ - construct_runtime, derive_impl, parameter_types, traits::Hooks, weights::Weight, + construct_runtime, derive_impl, parameter_types, sp_runtime::StateVersion, traits::Hooks, + weights::Weight, }; use sp_core::sr25519::Signature; @@ -78,6 +79,8 @@ impl Chain for TestBridgedChain { type Nonce = u64; type Signature = Signature; + const STATE_VERSION: StateVersion = StateVersion::V1; + fn max_extrinsic_size() -> u32 { unreachable!() } diff --git a/bridges/modules/messages/Cargo.toml b/bridges/modules/messages/Cargo.toml index 573d0ba47668cfd5513def1a2465be10002c676f..33f524030d264e4ed292f8f67273e838e15fc3a9 100644 --- a/bridges/modules/messages/Cargo.toml +++ b/bridges/modules/messages/Cargo.toml @@ -13,52 +13,67 @@ workspace = true [dependencies] codec = { workspace = true } log = { workspace = true } -num-traits = { workspace = true } scale-info = { features = ["derive"], workspace = true } # Bridge dependencies - +bp-header-chain = { workspace = true } bp-messages = { workspace = true } bp-runtime = { workspace = true } # Substrate Dependencies - frame-benchmarking = { optional = true, workspace = true } frame-support = { workspace = true } frame-system = { workspace = true } sp-runtime = { workspace = true } sp-std = { workspace = true } +sp-trie = { optional = true, workspace = true } [dev-dependencies] -bp-test-utils = { workspace = true, default-features = true } -pallet-balances = { workspace = true, default-features = true } -sp-io = { workspace = true, default-features = true } +bp-runtime = { features = ["test-helpers"], workspace = true } +bp-test-utils = { workspace = true } +pallet-balances = { workspace = true } +pallet-bridge-grandpa = { workspace = true } +sp-io = { workspace = true } +sp-core = { workspace = true } [features] default = ["std"] std = [ + "bp-header-chain/std", "bp-messages/std", "bp-runtime/std", + "bp-test-utils/std", "codec/std", "frame-benchmarking/std", "frame-support/std", "frame-system/std", "log/std", - "num-traits/std", + "pallet-balances/std", + "pallet-bridge-grandpa/std", "scale-info/std", + "sp-core/std", + "sp-io/std", "sp-runtime/std", "sp-std/std", + "sp-trie/std", ] runtime-benchmarks = [ + "bp-runtime/test-helpers", "frame-benchmarking/runtime-benchmarks", "frame-support/runtime-benchmarks", "frame-system/runtime-benchmarks", "pallet-balances/runtime-benchmarks", + "pallet-bridge-grandpa/runtime-benchmarks", "sp-runtime/runtime-benchmarks", ] try-runtime = [ "frame-support/try-runtime", "frame-system/try-runtime", "pallet-balances/try-runtime", + "pallet-bridge-grandpa/try-runtime", "sp-runtime/try-runtime", ] +test-helpers = [ + "bp-runtime/test-helpers", + "sp-trie", +] diff --git a/bridges/modules/messages/README.md b/bridges/modules/messages/README.md index c06b96b857dea1cdf7fdaed81e70d66aff116064..80fd92eb0e5a7d975ba45619838007a12f5f5553 100644 --- a/bridges/modules/messages/README.md +++ b/bridges/modules/messages/README.md @@ -104,17 +104,22 @@ the message. When a message is delivered to the target chain, the `MessagesDeliv `receive_messages_delivery_proof()` transaction. The `MessagesDelivered` contains the message lane identifier and inclusive range of delivered message nonces. -The pallet provides no means to get the result of message dispatch at the target chain. If that is required, it must be -done outside of the pallet. For example, XCM messages, when dispatched, have special instructions to send some data back -to the sender. Other dispatchers may use similar mechanism for that. -### How to plug-in Messages Module to Send Messages to the Bridged Chain? - -The `pallet_bridge_messages::Config` trait has 3 main associated types that are used to work with outbound messages. The -`pallet_bridge_messages::Config::TargetHeaderChain` defines how we see the bridged chain as the target for our outbound -messages. It must be able to check that the bridged chain may accept our message - like that the message has size below -maximal possible transaction size of the chain and so on. And when the relayer sends us a confirmation transaction, this -implementation must be able to parse and verify the proof of messages delivery. Normally, you would reuse the same -(configurable) type on all chains that are sending messages to the same bridged chain. +The pallet provides no means to get the result of message dispatch at the target chain. If that is +required, it must be done outside of the pallet. For example, XCM messages, when dispatched, have +special instructions to send some data back to the sender. Other dispatchers may use similar +mechanism for that. + +### How to plug-in Messages Module to Send and Receive Messages from the Bridged Chain? + +The `pallet_bridge_messages::Config` trait has 2 main associated types that are used to work with +inbound messages. The `pallet_bridge_messages::BridgedChain` defines basic primitives of the bridged +chain. The `pallet_bridge_messages::BridgedHeaderChain` defines the way we access the bridged chain +headers in our runtime. You may use `pallet_bridge_grandpa` if you're bridging with chain that uses +GRANDPA finality or `pallet_bridge_parachains::ParachainHeaders` if you're bridging with parachain. + +The `pallet_bridge_messages::Config::MessageDispatch` defines a way on how to dispatch delivered +messages. Apart from actually dispatching the message, the implementation must return the correct +dispatch weight of the message before dispatch is called. The last type is the `pallet_bridge_messages::Config::DeliveryConfirmationPayments`. When confirmation transaction is received, we call the `pay_reward()` method, passing the range of delivered messages. @@ -129,18 +134,6 @@ You should be looking at the `bp_messages::source_chain::ForbidOutboundMessages` [`bp_messages::source_chain`](../../primitives/messages/src/source_chain.rs). It implements all required traits and will simply reject all transactions, related to outbound messages. -### How to plug-in Messages Module to Receive Messages from the Bridged Chain? - -The `pallet_bridge_messages::Config` trait has 2 main associated types that are used to work with inbound messages. The -`pallet_bridge_messages::Config::SourceHeaderChain` defines how we see the bridged chain as the source of our inbound -messages. When relayer sends us a delivery transaction, this implementation must be able to parse and verify the proof -of messages wrapped in this transaction. Normally, you would reuse the same (configurable) type on all chains that are -sending messages to the same bridged chain. - -The `pallet_bridge_messages::Config::MessageDispatch` defines a way on how to dispatch delivered messages. Apart from -actually dispatching the message, the implementation must return the correct dispatch weight of the message before -dispatch is called. - ### I have a Messages Module in my Runtime, but I Want to Reject all Inbound Messages. What shall I do? You should be looking at the `bp_messages::target_chain::ForbidInboundMessages` structure from the @@ -150,36 +143,42 @@ and will simply reject all transactions, related to inbound messages. ### What about other Constants in the Messages Module Configuration Trait? Two settings that are used to check messages in the `send_message()` function. The -`pallet_bridge_messages::Config::ActiveOutboundLanes` is an array of all message lanes, that may be used to send -messages. All messages sent using other lanes are rejected. All messages that have size above -`pallet_bridge_messages::Config::MaximalOutboundPayloadSize` will also be rejected. - -To be able to reward the relayer for delivering messages, we store a map of message nonces range => identifier of the -relayer that has delivered this range at the target chain runtime storage. If a relayer delivers multiple consequent -ranges, they're merged into single entry. So there may be more than one entry for the same relayer. Eventually, this -whole map must be delivered back to the source chain to confirm delivery and pay rewards. So to make sure we are able to -craft this confirmation transaction, we need to: (1) keep the size of this map below a certain limit and (2) make sure -that the weight of processing this map is below a certain limit. Both size and processing weight mostly depend on the -number of entries. The number of entries is limited with the -`pallet_bridge_messages::ConfigMaxUnrewardedRelayerEntriesAtInboundLane` parameter. Processing weight also depends on -the total number of messages that are being confirmed, because every confirmed message needs to be read. So there's -another `pallet_bridge_messages::Config::MaxUnconfirmedMessagesAtInboundLane` parameter for that. - -When choosing values for these parameters, you must also keep in mind that if proof in your scheme is based on finality -of headers (and it is the most obvious option for Substrate-based chains with finality notion), then choosing too small -values for these parameters may cause significant delays in message delivery. That's because there are too many actors -involved in this scheme: 1) authorities that are finalizing headers of the target chain need to finalize header with -non-empty map; 2) the headers relayer then needs to submit this header and its finality proof to the source chain; 3) -the messages relayer must then send confirmation transaction (storage proof of this map) to the source chain; 4) when -the confirmation transaction will be mined at some header, source chain authorities must finalize this header; 5) the -headers relay then needs to submit this header and its finality proof to the target chain; 6) only now the messages -relayer may submit new messages from the source to target chain and prune the entry from the map. - -Delivery transaction requires the relayer to provide both number of entries and total number of messages in the map. -This means that the module never charges an extra cost for delivering a map - the relayer would need to pay exactly for -the number of entries+messages it has delivered. So the best guess for values of these parameters would be the pair that -would occupy `N` percent of the maximal transaction size and weight of the source chain. The `N` should be large enough -to process large maps, at the same time keeping reserve for future source chain upgrades. +`pallet_bridge_messages::Config::ActiveOutboundLanes` is an array of all message lanes, that +may be used to send messages. All messages sent using other lanes are rejected. All messages that have +size above `pallet_bridge_messages::Config::MaximalOutboundPayloadSize` will also be rejected. + +To be able to reward the relayer for delivering messages, we store a map of message nonces range => +identifier of the relayer that has delivered this range at the target chain runtime storage. If a +relayer delivers multiple consequent ranges, they're merged into single entry. So there may be more +than one entry for the same relayer. Eventually, this whole map must be delivered back to the source +chain to confirm delivery and pay rewards. So to make sure we are able to craft this confirmation +transaction, we need to: (1) keep the size of this map below a certain limit and (2) make sure that +the weight of processing this map is below a certain limit. Both size and processing weight mostly +depend on the number of entries. The number of entries is limited with the +`pallet_bridge_messages::Config::BridgedChain::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX` parameter. +Processing weight also depends on the total number of messages that are being confirmed, because every +confirmed message needs to be read. So there's another +`pallet_bridge_messages::Config::BridgedChain::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX` parameter +for that. + +When choosing values for these parameters, you must also keep in mind that if proof in your scheme +is based on finality of headers (and it is the most obvious option for Substrate-based chains with +finality notion), then choosing too small values for these parameters may cause significant delays +in message delivery. That's because there are too many actors involved in this scheme: 1) authorities +that are finalizing headers of the target chain need to finalize header with non-empty map; 2) the +headers relayer then needs to submit this header and its finality proof to the source chain; 3) the +messages relayer must then send confirmation transaction (storage proof of this map) to the source +chain; 4) when the confirmation transaction will be mined at some header, source chain authorities +must finalize this header; 5) the headers relay then needs to submit this header and its finality +proof to the target chain; 6) only now the messages relayer may submit new messages from the source +to target chain and prune the entry from the map. + +Delivery transaction requires the relayer to provide both number of entries and total number of +messages in the map. This means that the module never charges an extra cost for delivering a map - +the relayer would need to pay exactly for the number of entries+messages it has delivered. So the +best guess for values of these parameters would be the pair that would occupy `N` percent of the +maximal transaction size and weight of the source chain. The `N` should be large enough to process +large maps, at the same time keeping reserve for future source chain upgrades. ## Non-Essential Functionality diff --git a/bridges/modules/messages/src/benchmarking.rs b/bridges/modules/messages/src/benchmarking.rs index 4f13c4409672b3e76d36fd7d3dd2fab5c7e2ec1b..d38aaf32dc94bd157de0d3e910b729a7970c1684 100644 --- a/bridges/modules/messages/src/benchmarking.rs +++ b/bridges/modules/messages/src/benchmarking.rs @@ -16,19 +16,22 @@ //! Messages pallet benchmarking. +#![cfg(feature = "runtime-benchmarks")] + use crate::{ inbound_lane::InboundLaneStorage, outbound_lane, weights_ext::EXPECTED_DEFAULT_MESSAGE_LENGTH, - Call, OutboundLanes, RuntimeInboundLaneStorage, + BridgedChainOf, Call, OutboundLanes, RuntimeInboundLaneStorage, }; use bp_messages::{ - source_chain::TargetHeaderChain, target_chain::SourceHeaderChain, DeliveredMessages, + source_chain::FromBridgedChainMessagesDeliveryProof, + target_chain::FromBridgedChainMessagesProof, ChainWithMessages, DeliveredMessages, InboundLaneData, LaneId, MessageNonce, OutboundLaneData, UnrewardedRelayer, UnrewardedRelayersState, }; -use bp_runtime::StorageProofSize; +use bp_runtime::{AccountIdOf, HashOf, UnverifiedStorageProofParams}; use codec::Decode; -use frame_benchmarking::{account, benchmarks_instance_pallet}; +use frame_benchmarking::{account, v2::*}; use frame_support::weights::Weight; use frame_system::RawOrigin; use sp_runtime::{traits::TrailingZeroInput, BoundedVec}; @@ -54,7 +57,7 @@ pub struct MessageProofParams { /// return `true` from the `is_message_successfully_dispatched`. pub is_successful_dispatch_expected: bool, /// Proof size requirements. - pub size: StorageProofSize, + pub proof_params: UnverifiedStorageProofParams, } /// Benchmark-specific message delivery proof parameters. @@ -65,7 +68,7 @@ pub struct MessageDeliveryProofParams { /// The proof needs to include this inbound lane data. pub inbound_lane_data: InboundLaneData, /// Proof size requirements. - pub size: StorageProofSize, + pub proof_params: UnverifiedStorageProofParams, } /// Trait that must be implemented by runtime. @@ -80,8 +83,8 @@ pub trait Config: crate::Config { /// Return id of relayer account at the bridged chain. /// /// By default, zero account is returned. - fn bridged_relayer_id() -> Self::InboundRelayer { - Self::InboundRelayer::decode(&mut TrailingZeroInput::zeroes()).unwrap() + fn bridged_relayer_id() -> AccountIdOf> { + Decode::decode(&mut TrailingZeroInput::zeroes()).unwrap() } /// Create given account and give it enough balance for test purposes. Used to create @@ -94,11 +97,11 @@ pub trait Config: crate::Config { /// Prepare messages proof to receive by the module. fn prepare_message_proof( params: MessageProofParams, - ) -> (::MessagesProof, Weight); + ) -> (FromBridgedChainMessagesProof>>, Weight); /// Prepare messages delivery proof to receive by the module. fn prepare_message_delivery_proof( params: MessageDeliveryProofParams, - ) -> >::MessagesDeliveryProof; + ) -> FromBridgedChainMessagesDeliveryProof>>; /// Returns true if message has been successfully dispatched or not. fn is_message_successfully_dispatched(_nonce: MessageNonce) -> bool { @@ -109,174 +112,227 @@ pub trait Config: crate::Config { fn is_relayer_rewarded(relayer: &Self::AccountId) -> bool; } -benchmarks_instance_pallet! { +fn send_regular_message, I: 'static>() { + let mut outbound_lane = outbound_lane::(T::bench_lane_id()); + outbound_lane.send_message(BoundedVec::try_from(vec![]).expect("We craft valid messages")); +} + +fn receive_messages, I: 'static>(nonce: MessageNonce) { + let mut inbound_lane_storage = + RuntimeInboundLaneStorage::::from_lane_id(T::bench_lane_id()); + inbound_lane_storage.set_data(InboundLaneData { + relayers: vec![UnrewardedRelayer { + relayer: T::bridged_relayer_id(), + messages: DeliveredMessages::new(nonce), + }] + .into_iter() + .collect(), + last_confirmed_nonce: 0, + }); +} + +struct ReceiveMessagesProofSetup, I: 'static> { + relayer_id_on_src: AccountIdOf>, + relayer_id_on_tgt: T::AccountId, + msgs_count: u32, + _phantom_data: sp_std::marker::PhantomData, +} + +impl, I: 'static> ReceiveMessagesProofSetup { + const LATEST_RECEIVED_NONCE: MessageNonce = 20; + + fn new(msgs_count: u32) -> Self { + let setup = Self { + relayer_id_on_src: T::bridged_relayer_id(), + relayer_id_on_tgt: account("relayer", 0, SEED), + msgs_count, + _phantom_data: Default::default(), + }; + T::endow_account(&setup.relayer_id_on_tgt); + // mark messages 1..=latest_recvd_nonce as delivered + receive_messages::(Self::LATEST_RECEIVED_NONCE); + + setup + } + + fn relayer_id_on_src(&self) -> AccountIdOf> { + self.relayer_id_on_src.clone() + } + + fn relayer_id_on_tgt(&self) -> T::AccountId { + self.relayer_id_on_tgt.clone() + } + + fn last_nonce(&self) -> MessageNonce { + Self::LATEST_RECEIVED_NONCE + self.msgs_count as u64 + } + + fn nonces(&self) -> RangeInclusive { + (Self::LATEST_RECEIVED_NONCE + 1)..=self.last_nonce() + } + + fn check_last_nonce(&self) { + assert_eq!( + crate::InboundLanes::::get(&T::bench_lane_id()).last_delivered_nonce(), + self.last_nonce(), + ); + } +} + +#[instance_benchmarks] +mod benchmarks { + use super::*; + // // Benchmarks that are used directly by the runtime calls weight formulae. // - // Benchmark `receive_messages_proof` extrinsic with single minimal-weight message and following conditions: + fn max_msgs, I: 'static>() -> u32 { + T::BridgedChain::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX as u32 - + ReceiveMessagesProofSetup::::LATEST_RECEIVED_NONCE as u32 + } + + // Benchmark `receive_messages_proof` extrinsic with single minimal-weight message and following + // conditions: // * proof does not include outbound lane state proof; // * inbound lane already has state, so it needs to be read and decoded; // * message is dispatched (reminder: dispatch weight should be minimal); // * message requires all heavy checks done by dispatcher. - // - // This is base benchmark for all other message delivery benchmarks. - receive_single_message_proof { - let relayer_id_on_source = T::bridged_relayer_id(); - let relayer_id_on_target = account("relayer", 0, SEED); - T::endow_account(&relayer_id_on_target); - - // mark messages 1..=20 as delivered - receive_messages::(20); - + #[benchmark] + fn receive_single_message_proof() { + // setup code + let setup = ReceiveMessagesProofSetup::::new(1); let (proof, dispatch_weight) = T::prepare_message_proof(MessageProofParams { lane: T::bench_lane_id(), - message_nonces: 21..=21, + message_nonces: setup.nonces(), outbound_lane_data: None, is_successful_dispatch_expected: false, - size: StorageProofSize::Minimal(EXPECTED_DEFAULT_MESSAGE_LENGTH), + proof_params: UnverifiedStorageProofParams::from_db_size( + EXPECTED_DEFAULT_MESSAGE_LENGTH, + ), }); - }: receive_messages_proof(RawOrigin::Signed(relayer_id_on_target), relayer_id_on_source, proof, 1, dispatch_weight) - verify { - assert_eq!( - crate::InboundLanes::::get(&T::bench_lane_id()).last_delivered_nonce(), - 21, + + #[extrinsic_call] + receive_messages_proof( + RawOrigin::Signed(setup.relayer_id_on_tgt()), + setup.relayer_id_on_src(), + Box::new(proof), + setup.msgs_count, + dispatch_weight, ); + + // verification code + setup.check_last_nonce(); } - // Benchmark `receive_messages_proof` extrinsic with two minimal-weight messages and following conditions: + // Benchmark `receive_messages_proof` extrinsic with `n` minimal-weight messages and following + // conditions: // * proof does not include outbound lane state proof; // * inbound lane already has state, so it needs to be read and decoded; // * message is dispatched (reminder: dispatch weight should be minimal); // * message requires all heavy checks done by dispatcher. - // - // The weight of single message delivery could be approximated as - // `weight(receive_two_messages_proof) - weight(receive_single_message_proof)`. - // This won't be super-accurate if message has non-zero dispatch weight, but estimation should - // be close enough to real weight. - receive_two_messages_proof { - let relayer_id_on_source = T::bridged_relayer_id(); - let relayer_id_on_target = account("relayer", 0, SEED); - T::endow_account(&relayer_id_on_target); - - // mark messages 1..=20 as delivered - receive_messages::(20); - + #[benchmark] + fn receive_n_messages_proof(n: Linear<1, { max_msgs::() }>) { + // setup code + let setup = ReceiveMessagesProofSetup::::new(n); let (proof, dispatch_weight) = T::prepare_message_proof(MessageProofParams { lane: T::bench_lane_id(), - message_nonces: 21..=22, + message_nonces: setup.nonces(), outbound_lane_data: None, is_successful_dispatch_expected: false, - size: StorageProofSize::Minimal(EXPECTED_DEFAULT_MESSAGE_LENGTH), + proof_params: UnverifiedStorageProofParams::from_db_size( + EXPECTED_DEFAULT_MESSAGE_LENGTH, + ), }); - }: receive_messages_proof(RawOrigin::Signed(relayer_id_on_target), relayer_id_on_source, proof, 2, dispatch_weight) - verify { - assert_eq!( - crate::InboundLanes::::get(&T::bench_lane_id()).last_delivered_nonce(), - 22, + + #[extrinsic_call] + receive_messages_proof( + RawOrigin::Signed(setup.relayer_id_on_tgt()), + setup.relayer_id_on_src(), + Box::new(proof), + setup.msgs_count, + dispatch_weight, ); + + // verification code + setup.check_last_nonce(); } - // Benchmark `receive_messages_proof` extrinsic with single minimal-weight message and following conditions: + // Benchmark `receive_messages_proof` extrinsic with single minimal-weight message and following + // conditions: // * proof includes outbound lane state proof; // * inbound lane already has state, so it needs to be read and decoded; // * message is successfully dispatched (reminder: dispatch weight should be minimal); // * message requires all heavy checks done by dispatcher. // // The weight of outbound lane state delivery would be - // `weight(receive_single_message_proof_with_outbound_lane_state) - weight(receive_single_message_proof)`. - // This won't be super-accurate if message has non-zero dispatch weight, but estimation should - // be close enough to real weight. - receive_single_message_proof_with_outbound_lane_state { - let relayer_id_on_source = T::bridged_relayer_id(); - let relayer_id_on_target = account("relayer", 0, SEED); - T::endow_account(&relayer_id_on_target); - - // mark messages 1..=20 as delivered - receive_messages::(20); - + // `weight(receive_single_message_proof_with_outbound_lane_state) - + // weight(receive_single_message_proof)`. This won't be super-accurate if message has non-zero + // dispatch weight, but estimation should be close enough to real weight. + #[benchmark] + fn receive_single_message_proof_with_outbound_lane_state() { + // setup code + let setup = ReceiveMessagesProofSetup::::new(1); let (proof, dispatch_weight) = T::prepare_message_proof(MessageProofParams { lane: T::bench_lane_id(), - message_nonces: 21..=21, + message_nonces: setup.nonces(), outbound_lane_data: Some(OutboundLaneData { - oldest_unpruned_nonce: 21, - latest_received_nonce: 20, - latest_generated_nonce: 21, + oldest_unpruned_nonce: setup.last_nonce(), + latest_received_nonce: ReceiveMessagesProofSetup::::LATEST_RECEIVED_NONCE, + latest_generated_nonce: setup.last_nonce(), }), is_successful_dispatch_expected: false, - size: StorageProofSize::Minimal(EXPECTED_DEFAULT_MESSAGE_LENGTH), + proof_params: UnverifiedStorageProofParams::from_db_size( + EXPECTED_DEFAULT_MESSAGE_LENGTH, + ), }); - }: receive_messages_proof(RawOrigin::Signed(relayer_id_on_target), relayer_id_on_source, proof, 1, dispatch_weight) - verify { - let lane_state = crate::InboundLanes::::get(&T::bench_lane_id()); - assert_eq!(lane_state.last_delivered_nonce(), 21); - assert_eq!(lane_state.last_confirmed_nonce, 20); - } - - // Benchmark `receive_messages_proof` extrinsic with single minimal-weight message and following conditions: - // * the proof has large leaf with total size of approximately 1KB; - // * proof does not include outbound lane state proof; - // * inbound lane already has state, so it needs to be read and decoded; - // * message is dispatched (reminder: dispatch weight should be minimal); - // * message requires all heavy checks done by dispatcher. - // - // With single KB of messages proof, the weight of the call is increased (roughly) by - // `(receive_single_message_proof_16KB - receive_single_message_proof_1_kb) / 15`. - receive_single_message_proof_1_kb { - let relayer_id_on_source = T::bridged_relayer_id(); - let relayer_id_on_target = account("relayer", 0, SEED); - T::endow_account(&relayer_id_on_target); - - // mark messages 1..=20 as delivered - receive_messages::(20); - let (proof, dispatch_weight) = T::prepare_message_proof(MessageProofParams { - lane: T::bench_lane_id(), - message_nonces: 21..=21, - outbound_lane_data: None, - is_successful_dispatch_expected: false, - size: StorageProofSize::HasLargeLeaf(1024), - }); - }: receive_messages_proof(RawOrigin::Signed(relayer_id_on_target), relayer_id_on_source, proof, 1, dispatch_weight) - verify { - assert_eq!( - crate::InboundLanes::::get(&T::bench_lane_id()).last_delivered_nonce(), - 21, + #[extrinsic_call] + receive_messages_proof( + RawOrigin::Signed(setup.relayer_id_on_tgt()), + setup.relayer_id_on_src(), + Box::new(proof), + setup.msgs_count, + dispatch_weight, ); + + // verification code + setup.check_last_nonce(); } - // Benchmark `receive_messages_proof` extrinsic with single minimal-weight message and following conditions: - // * the proof has large leaf with total size of approximately 16KB; + // Benchmark `receive_messages_proof` extrinsic with single minimal-weight message and following + // conditions: + // * the proof has large leaf with total size ranging between 1KB and 16KB; // * proof does not include outbound lane state proof; // * inbound lane already has state, so it needs to be read and decoded; // * message is dispatched (reminder: dispatch weight should be minimal); // * message requires all heavy checks done by dispatcher. - // - // Size of proof grows because it contains extra trie nodes in it. - // - // With single KB of messages proof, the weight of the call is increased (roughly) by - // `(receive_single_message_proof_16KB - receive_single_message_proof) / 15`. - receive_single_message_proof_16_kb { - let relayer_id_on_source = T::bridged_relayer_id(); - let relayer_id_on_target = account("relayer", 0, SEED); - T::endow_account(&relayer_id_on_target); - - // mark messages 1..=20 as delivered - receive_messages::(20); - + #[benchmark] + fn receive_single_n_bytes_message_proof( + /// Proof size in KB + n: Linear<1, { 16 * 1024 }>, + ) { + // setup code + let setup = ReceiveMessagesProofSetup::::new(1); let (proof, dispatch_weight) = T::prepare_message_proof(MessageProofParams { lane: T::bench_lane_id(), - message_nonces: 21..=21, + message_nonces: setup.nonces(), outbound_lane_data: None, is_successful_dispatch_expected: false, - size: StorageProofSize::HasLargeLeaf(16 * 1024), + proof_params: UnverifiedStorageProofParams::from_db_size(n), }); - }: receive_messages_proof(RawOrigin::Signed(relayer_id_on_target), relayer_id_on_source, proof, 1, dispatch_weight) - verify { - assert_eq!( - crate::InboundLanes::::get(&T::bench_lane_id()).last_delivered_nonce(), - 21, + + #[extrinsic_call] + receive_messages_proof( + RawOrigin::Signed(setup.relayer_id_on_tgt()), + setup.relayer_id_on_src(), + Box::new(proof), + setup.msgs_count, + dispatch_weight, ); + + // verification code + setup.check_last_nonce(); } // Benchmark `receive_messages_delivery_proof` extrinsic with following conditions: @@ -284,7 +340,8 @@ benchmarks_instance_pallet! { // * relayer account does not exist (in practice it needs to exist in production environment). // // This is base benchmark for all other confirmations delivery benchmarks. - receive_delivery_proof_for_single_message { + #[benchmark] + fn receive_delivery_proof_for_single_message() { let relayer_id: T::AccountId = account("relayer", 0, SEED); // send message that we're going to confirm @@ -302,13 +359,21 @@ benchmarks_instance_pallet! { relayers: vec![UnrewardedRelayer { relayer: relayer_id.clone(), messages: DeliveredMessages::new(1), - }].into_iter().collect(), + }] + .into_iter() + .collect(), last_confirmed_nonce: 0, }, - size: StorageProofSize::Minimal(0), + proof_params: UnverifiedStorageProofParams::default(), }); - }: receive_messages_delivery_proof(RawOrigin::Signed(relayer_id.clone()), proof, relayers_state) - verify { + + #[extrinsic_call] + receive_messages_delivery_proof( + RawOrigin::Signed(relayer_id.clone()), + proof, + relayers_state, + ); + assert_eq!(OutboundLanes::::get(T::bench_lane_id()).latest_received_nonce, 1); assert!(T::is_relayer_rewarded(&relayer_id)); } @@ -320,7 +385,8 @@ benchmarks_instance_pallet! { // Additional weight for paying single-message reward to the same relayer could be computed // as `weight(receive_delivery_proof_for_two_messages_by_single_relayer) // - weight(receive_delivery_proof_for_single_message)`. - receive_delivery_proof_for_two_messages_by_single_relayer { + #[benchmark] + fn receive_delivery_proof_for_two_messages_by_single_relayer() { let relayer_id: T::AccountId = account("relayer", 0, SEED); // send message that we're going to confirm @@ -341,13 +407,21 @@ benchmarks_instance_pallet! { relayers: vec![UnrewardedRelayer { relayer: relayer_id.clone(), messages: delivered_messages, - }].into_iter().collect(), + }] + .into_iter() + .collect(), last_confirmed_nonce: 0, }, - size: StorageProofSize::Minimal(0), + proof_params: UnverifiedStorageProofParams::default(), }); - }: receive_messages_delivery_proof(RawOrigin::Signed(relayer_id.clone()), proof, relayers_state) - verify { + + #[extrinsic_call] + receive_messages_delivery_proof( + RawOrigin::Signed(relayer_id.clone()), + proof, + relayers_state, + ); + assert_eq!(OutboundLanes::::get(T::bench_lane_id()).latest_received_nonce, 2); assert!(T::is_relayer_rewarded(&relayer_id)); } @@ -359,7 +433,8 @@ benchmarks_instance_pallet! { // Additional weight for paying reward to the next relayer could be computed // as `weight(receive_delivery_proof_for_two_messages_by_two_relayers) // - weight(receive_delivery_proof_for_two_messages_by_single_relayer)`. - receive_delivery_proof_for_two_messages_by_two_relayers { + #[benchmark] + fn receive_delivery_proof_for_two_messages_by_two_relayers() { let relayer1_id: T::AccountId = account("relayer1", 1, SEED); let relayer2_id: T::AccountId = account("relayer2", 2, SEED); @@ -385,13 +460,21 @@ benchmarks_instance_pallet! { relayer: relayer2_id.clone(), messages: DeliveredMessages::new(2), }, - ].into_iter().collect(), + ] + .into_iter() + .collect(), last_confirmed_nonce: 0, }, - size: StorageProofSize::Minimal(0), + proof_params: UnverifiedStorageProofParams::default(), }); - }: receive_messages_delivery_proof(RawOrigin::Signed(relayer1_id.clone()), proof, relayers_state) - verify { + + #[extrinsic_call] + receive_messages_delivery_proof( + RawOrigin::Signed(relayer1_id.clone()), + proof, + relayers_state, + ); + assert_eq!(OutboundLanes::::get(T::bench_lane_id()).latest_received_nonce, 2); assert!(T::is_relayer_rewarded(&relayer1_id)); assert!(T::is_relayer_rewarded(&relayer2_id)); @@ -411,51 +494,38 @@ benchmarks_instance_pallet! { // * inbound lane already has state, so it needs to be read and decoded; // * message is **SUCCESSFULLY** dispatched; // * message requires all heavy checks done by dispatcher. - receive_single_message_proof_with_dispatch { - // maybe dispatch weight relies on the message size too? - let i in EXPECTED_DEFAULT_MESSAGE_LENGTH .. EXPECTED_DEFAULT_MESSAGE_LENGTH * 16; - - let relayer_id_on_source = T::bridged_relayer_id(); - let relayer_id_on_target = account("relayer", 0, SEED); - T::endow_account(&relayer_id_on_target); - - // mark messages 1..=20 as delivered - receive_messages::(20); - + #[benchmark] + fn receive_single_n_bytes_message_proof_with_dispatch( + /// Proof size in KB + n: Linear<1, { 16 * 1024 }>, + ) { + // setup code + let setup = ReceiveMessagesProofSetup::::new(1); let (proof, dispatch_weight) = T::prepare_message_proof(MessageProofParams { lane: T::bench_lane_id(), - message_nonces: 21..=21, + message_nonces: setup.nonces(), outbound_lane_data: None, is_successful_dispatch_expected: true, - size: StorageProofSize::Minimal(i), + proof_params: UnverifiedStorageProofParams::from_db_size(n), }); - }: receive_messages_proof(RawOrigin::Signed(relayer_id_on_target), relayer_id_on_source, proof, 1, dispatch_weight) - verify { - assert_eq!( - crate::InboundLanes::::get(&T::bench_lane_id()).last_delivered_nonce(), - 21, - ); - assert!(T::is_message_successfully_dispatched(21)); - } - impl_benchmark_test_suite!(Pallet, crate::mock::new_test_ext(), crate::mock::TestRuntime) -} + #[extrinsic_call] + receive_messages_proof( + RawOrigin::Signed(setup.relayer_id_on_tgt()), + setup.relayer_id_on_src(), + Box::new(proof), + setup.msgs_count, + dispatch_weight, + ); -fn send_regular_message, I: 'static>() { - let mut outbound_lane = outbound_lane::(T::bench_lane_id()); - outbound_lane.send_message(BoundedVec::try_from(vec![]).expect("We craft valid messages")); -} + // verification code + setup.check_last_nonce(); + assert!(T::is_message_successfully_dispatched(setup.last_nonce())); + } -fn receive_messages, I: 'static>(nonce: MessageNonce) { - let mut inbound_lane_storage = - RuntimeInboundLaneStorage::::from_lane_id(T::bench_lane_id()); - inbound_lane_storage.set_data(InboundLaneData { - relayers: vec![UnrewardedRelayer { - relayer: T::bridged_relayer_id(), - messages: DeliveredMessages::new(nonce), - }] - .into_iter() - .collect(), - last_confirmed_nonce: 0, - }); + impl_benchmark_test_suite!( + Pallet, + crate::tests::mock::new_test_ext(), + crate::tests::mock::TestRuntime + ); } diff --git a/bridges/modules/messages/src/inbound_lane.rs b/bridges/modules/messages/src/inbound_lane.rs index da1698e6e0370f9f84ca8dd53bc1ebc99f696017..7ef4599a93c4823a9be7fa918b35c309cea6611a 100644 --- a/bridges/modules/messages/src/inbound_lane.rs +++ b/bridges/modules/messages/src/inbound_lane.rs @@ -16,15 +16,15 @@ //! Everything about incoming messages receival. -use crate::Config; +use crate::{BridgedChainOf, Config}; use bp_messages::{ target_chain::{DispatchMessage, DispatchMessageData, MessageDispatch}, - DeliveredMessages, InboundLaneData, LaneId, MessageKey, MessageNonce, OutboundLaneData, - ReceptionResult, UnrewardedRelayer, + ChainWithMessages, DeliveredMessages, InboundLaneData, LaneId, MessageKey, MessageNonce, + OutboundLaneData, ReceptionResult, UnrewardedRelayer, }; +use bp_runtime::AccountIdOf; use codec::{Decode, Encode, EncodeLike, MaxEncodedLen}; -use frame_support::traits::Get; use scale_info::{Type, TypeInfo}; use sp_runtime::RuntimeDebug; use sp_std::prelude::PartialEq; @@ -55,10 +55,12 @@ pub trait InboundLaneStorage { /// /// The encoding of this type matches encoding of the corresponding `MessageData`. #[derive(Encode, Decode, Clone, RuntimeDebug, PartialEq, Eq)] -pub struct StoredInboundLaneData, I: 'static>(pub InboundLaneData); +pub struct StoredInboundLaneData, I: 'static>( + pub InboundLaneData>>, +); impl, I: 'static> sp_std::ops::Deref for StoredInboundLaneData { - type Target = InboundLaneData; + type Target = InboundLaneData>>; fn deref(&self) -> &Self::Target { &self.0 @@ -78,7 +80,7 @@ impl, I: 'static> Default for StoredInboundLaneData { } impl, I: 'static> From> - for InboundLaneData + for InboundLaneData>> { fn from(data: StoredInboundLaneData) -> Self { data.0 @@ -86,7 +88,7 @@ impl, I: 'static> From> } impl, I: 'static> EncodeLike> - for InboundLaneData + for InboundLaneData>> { } @@ -94,14 +96,14 @@ impl, I: 'static> TypeInfo for StoredInboundLaneData { type Identity = Self; fn type_info() -> Type { - InboundLaneData::::type_info() + InboundLaneData::>>::type_info() } } impl, I: 'static> MaxEncodedLen for StoredInboundLaneData { fn max_encoded_len() -> usize { - InboundLaneData::::encoded_size_hint( - T::MaxUnrewardedRelayerEntriesAtInboundLane::get() as usize, + InboundLaneData::>>::encoded_size_hint( + BridgedChainOf::::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX as usize, ) .unwrap_or(usize::MAX) } @@ -216,10 +218,10 @@ mod tests { use super::*; use crate::{ inbound_lane, - mock::{ + tests::mock::{ dispatch_result, inbound_message_data, inbound_unrewarded_relayers_state, run_test, - unrewarded_relayer, TestMessageDispatch, TestRuntime, REGULAR_PAYLOAD, TEST_LANE_ID, - TEST_RELAYER_A, TEST_RELAYER_B, TEST_RELAYER_C, + unrewarded_relayer, BridgedChain, TestMessageDispatch, TestRuntime, REGULAR_PAYLOAD, + TEST_LANE_ID, TEST_RELAYER_A, TEST_RELAYER_B, TEST_RELAYER_C, }, RuntimeInboundLaneStorage, }; @@ -372,8 +374,7 @@ mod tests { fn fails_to_receive_messages_above_unrewarded_relayer_entries_limit_per_lane() { run_test(|| { let mut lane = inbound_lane::(TEST_LANE_ID); - let max_nonce = - ::MaxUnrewardedRelayerEntriesAtInboundLane::get(); + let max_nonce = BridgedChain::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX; for current_nonce in 1..max_nonce + 1 { assert_eq!( lane.receive_message::( @@ -409,7 +410,7 @@ mod tests { fn fails_to_receive_messages_above_unconfirmed_messages_limit_per_lane() { run_test(|| { let mut lane = inbound_lane::(TEST_LANE_ID); - let max_nonce = ::MaxUnconfirmedMessagesAtInboundLane::get(); + let max_nonce = BridgedChain::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX; for current_nonce in 1..=max_nonce { assert_eq!( lane.receive_message::( diff --git a/bridges/modules/messages/src/lib.rs b/bridges/modules/messages/src/lib.rs index e31a4542056cb30466f236d0dc9957c053a03f66..bf105b14040185f61e627a35f4f53b3a66b48c19 100644 --- a/bridges/modules/messages/src/lib.rs +++ b/bridges/modules/messages/src/lib.rs @@ -41,8 +41,8 @@ pub use outbound_lane::StoredMessagePayload; pub use weights::WeightInfo; pub use weights_ext::{ ensure_able_to_receive_confirmation, ensure_able_to_receive_message, - ensure_weights_are_correct, WeightInfoExt, EXPECTED_DEFAULT_MESSAGE_LENGTH, - EXTRA_STORAGE_PROOF_SIZE, + ensure_maximal_message_dispatch, ensure_weights_are_correct, WeightInfoExt, + EXPECTED_DEFAULT_MESSAGE_LENGTH, EXTRA_STORAGE_PROOF_SIZE, }; use crate::{ @@ -50,20 +50,23 @@ use crate::{ outbound_lane::{OutboundLane, OutboundLaneStorage, ReceptionConfirmationError}, }; +use bp_header_chain::HeaderChain; use bp_messages::{ source_chain::{ - DeliveryConfirmationPayments, OnMessagesDelivered, SendMessageArtifacts, TargetHeaderChain, + DeliveryConfirmationPayments, FromBridgedChainMessagesDeliveryProof, OnMessagesDelivered, + SendMessageArtifacts, }, target_chain::{ - DeliveryPayments, DispatchMessage, MessageDispatch, ProvedLaneMessages, ProvedMessages, - SourceHeaderChain, + DeliveryPayments, DispatchMessage, FromBridgedChainMessagesProof, MessageDispatch, + ProvedLaneMessages, ProvedMessages, }, - DeliveredMessages, InboundLaneData, InboundMessageDetails, LaneId, MessageKey, MessageNonce, - MessagePayload, MessagesOperatingMode, OutboundLaneData, OutboundMessageDetails, - UnrewardedRelayersState, VerificationError, + ChainWithMessages, DeliveredMessages, InboundLaneData, InboundMessageDetails, LaneId, + MessageKey, MessageNonce, MessagePayload, MessagesOperatingMode, OutboundLaneData, + OutboundMessageDetails, UnrewardedRelayersState, VerificationError, }; use bp_runtime::{ - BasicOperatingMode, ChainId, OwnedBridgeModule, PreComputedSize, RangeInclusiveExt, Size, + AccountIdOf, BasicOperatingMode, HashOf, OwnedBridgeModule, PreComputedSize, RangeInclusiveExt, + Size, }; use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{dispatch::PostDispatchInfo, ensure, fail, traits::Get, DefaultNoBound}; @@ -72,6 +75,8 @@ use sp_std::{marker::PhantomData, prelude::*}; mod inbound_lane; mod outbound_lane; +mod proofs; +mod tests; mod weights_ext; pub mod weights; @@ -79,10 +84,9 @@ pub mod weights; #[cfg(feature = "runtime-benchmarks")] pub mod benchmarking; -#[cfg(test)] -mod mock; - pub use pallet::*; +#[cfg(feature = "test-helpers")] +pub use tests::*; /// The target that will be used when publishing logs related to this pallet. pub const LOG_TARGET: &str = "runtime::bridge-messages"; @@ -105,76 +109,39 @@ pub mod pallet { /// Benchmarks results from runtime we're plugged into. type WeightInfo: WeightInfoExt; - /// Gets the chain id value from the instance. - #[pallet::constant] - type BridgedChainId: Get; + /// This chain type. + type ThisChain: ChainWithMessages; + /// Bridged chain type. + type BridgedChain: ChainWithMessages; + /// Bridged chain headers provider. + type BridgedHeaderChain: HeaderChain; /// Get all active outbound lanes that the message pallet is serving. type ActiveOutboundLanes: Get<&'static [LaneId]>; - /// Maximal number of unrewarded relayer entries at inbound lane. Unrewarded means that the - /// relayer has delivered messages, but either confirmations haven't been delivered back to - /// the source chain, or we haven't received reward confirmations yet. - /// - /// This constant limits maximal number of entries in the `InboundLaneData::relayers`. Keep - /// in mind that the same relayer account may take several (non-consecutive) entries in this - /// set. - type MaxUnrewardedRelayerEntriesAtInboundLane: Get; - /// Maximal number of unconfirmed messages at inbound lane. Unconfirmed means that the - /// message has been delivered, but either confirmations haven't been delivered back to the - /// source chain, or we haven't received reward confirmations for these messages yet. - /// - /// This constant limits difference between last message from last entry of the - /// `InboundLaneData::relayers` and first message at the first entry. - /// - /// There is no point of making this parameter lesser than - /// MaxUnrewardedRelayerEntriesAtInboundLane, because then maximal number of relayer entries - /// will be limited by maximal number of messages. - /// - /// This value also represents maximal number of messages in single delivery transaction. - /// Transaction that is declaring more messages than this value, will be rejected. Even if - /// these messages are from different lanes. - type MaxUnconfirmedMessagesAtInboundLane: Get; - - /// Maximal encoded size of the outbound payload. - #[pallet::constant] - type MaximalOutboundPayloadSize: Get; + /// Payload type of outbound messages. This payload is dispatched on the bridged chain. type OutboundPayload: Parameter + Size; - /// Payload type of inbound messages. This payload is dispatched on this chain. type InboundPayload: Decode; - /// Identifier of relayer that deliver messages to this chain. Relayer reward is paid on the - /// bridged chain. - type InboundRelayer: Parameter + MaxEncodedLen; - /// Delivery payments. - type DeliveryPayments: DeliveryPayments; - - // Types that are used by outbound_lane (on source chain). - /// Target header chain. - type TargetHeaderChain: TargetHeaderChain; - /// Delivery confirmation payments. + /// Handler for relayer payments that happen during message delivery transaction. + type DeliveryPayments: DeliveryPayments; + /// Handler for relayer payments that happen during message delivery confirmation + /// transaction. type DeliveryConfirmationPayments: DeliveryConfirmationPayments; /// Delivery confirmation callback. type OnMessagesDelivered: OnMessagesDelivered; - // Types that are used by inbound_lane (on target chain). - - /// Source header chain, as it is represented on target chain. - type SourceHeaderChain: SourceHeaderChain; - /// Message dispatch. + /// Message dispatch handler. type MessageDispatch: MessageDispatch; } - /// Shortcut to messages proof type for Config. - pub type MessagesProofOf = - <>::SourceHeaderChain as SourceHeaderChain>::MessagesProof; - /// Shortcut to messages delivery proof type for Config. - pub type MessagesDeliveryProofOf = - <>::TargetHeaderChain as TargetHeaderChain< - >::OutboundPayload, - ::AccountId, - >>::MessagesDeliveryProof; + /// Shortcut to this chain type for Config. + pub type ThisChainOf = >::ThisChain; + /// Shortcut to bridged chain type for Config. + pub type BridgedChainOf = >::BridgedChain; + /// Shortcut to bridged header chain type for Config. + pub type BridgedHeaderChainOf = >::BridgedHeaderChain; #[pallet::pallet] pub struct Pallet(PhantomData<(T, I)>); @@ -265,11 +232,11 @@ pub mod pallet { /// The call may succeed, but some messages may not be delivered e.g. if they are not fit /// into the unrewarded relayers vector. #[pallet::call_index(2)] - #[pallet::weight(T::WeightInfo::receive_messages_proof_weight(proof, *messages_count, *dispatch_weight))] + #[pallet::weight(T::WeightInfo::receive_messages_proof_weight(&**proof, *messages_count, *dispatch_weight))] pub fn receive_messages_proof( origin: OriginFor, - relayer_id_at_bridged_chain: T::InboundRelayer, - proof: MessagesProofOf, + relayer_id_at_bridged_chain: AccountIdOf>, + proof: Box>>>, messages_count: u32, dispatch_weight: Weight, ) -> DispatchResultWithPostInfo { @@ -278,7 +245,8 @@ pub mod pallet { // reject transactions that are declaring too many messages ensure!( - MessageNonce::from(messages_count) <= T::MaxUnconfirmedMessagesAtInboundLane::get(), + MessageNonce::from(messages_count) <= + BridgedChainOf::::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX, Error::::TooManyMessagesInTheProof ); @@ -296,22 +264,19 @@ pub mod pallet { // The DeclaredWeight is exactly what's computed here. Unfortunately it is impossible // to get pre-computed value (and it has been already computed by the executive). let declared_weight = T::WeightInfo::receive_messages_proof_weight( - &proof, + &*proof, messages_count, dispatch_weight, ); let mut actual_weight = declared_weight; // verify messages proof && convert proof into messages - let messages = verify_and_decode_messages_proof::< - T::SourceHeaderChain, - T::InboundPayload, - >(proof, messages_count) - .map_err(|err| { - log::trace!(target: LOG_TARGET, "Rejecting invalid messages proof: {:?}", err,); + let messages = verify_and_decode_messages_proof::(*proof, messages_count) + .map_err(|err| { + log::trace!(target: LOG_TARGET, "Rejecting invalid messages proof: {:?}", err,); - Error::::InvalidMessagesProof - })?; + Error::::InvalidMessagesProof + })?; // dispatch messages and (optionally) update lane(s) state(s) let mut total_messages = 0; @@ -424,14 +389,14 @@ pub mod pallet { ))] pub fn receive_messages_delivery_proof( origin: OriginFor, - proof: MessagesDeliveryProofOf, + proof: FromBridgedChainMessagesDeliveryProof>>, mut relayers_state: UnrewardedRelayersState, ) -> DispatchResultWithPostInfo { Self::ensure_not_halted().map_err(Error::::BridgeModule)?; let proof_size = proof.size(); let confirmation_relayer = ensure_signed(origin)?; - let (lane_id, lane_data) = T::TargetHeaderChain::verify_messages_delivery_proof(proof) + let (lane_id, lane_data) = proofs::verify_messages_delivery_proof::(proof) .map_err(|err| { log::trace!( target: LOG_TARGET, @@ -542,8 +507,6 @@ pub mod pallet { InactiveOutboundLane, /// The inbound message dispatcher is inactive. MessageDispatchInactive, - /// Message has been treated as invalid by chain verifier. - MessageRejectedByChainVerifier(VerificationError), /// Message has been treated as invalid by the pallet logic. MessageRejectedByPallet(VerificationError), /// Submitter has failed to pay fee for delivering and dispatching messages. @@ -674,7 +637,9 @@ pub mod pallet { } /// Return inbound lane data. - pub fn inbound_lane_data(lane: LaneId) -> InboundLaneData { + pub fn inbound_lane_data( + lane: LaneId, + ) -> InboundLaneData>> { InboundLanes::::get(lane).0 } } @@ -714,18 +679,6 @@ where // let's check if outbound lane is active ensure!(T::ActiveOutboundLanes::get().contains(&lane), Error::::InactiveOutboundLane); - // let's first check if message can be delivered to target chain - T::TargetHeaderChain::verify_message(message).map_err(|err| { - log::trace!( - target: LOG_TARGET, - "Message to lane {:?} is rejected by target chain: {:?}", - lane, - err, - ); - - Error::::MessageRejectedByChainVerifier(err) - })?; - Ok(SendMessageArgs { lane_id: lane, payload: StoredMessagePayload::::try_from(message.encode()).map_err(|_| { @@ -785,7 +738,7 @@ fn outbound_lane, I: 'static>( /// Runtime inbound lane storage. struct RuntimeInboundLaneStorage, I: 'static = ()> { lane_id: LaneId, - cached_data: Option>, + cached_data: Option>>>, _phantom: PhantomData, } @@ -802,39 +755,39 @@ impl, I: 'static> RuntimeInboundLaneStorage { /// maximal configured. /// /// Maximal inbound lane state set size is configured by the - /// `MaxUnrewardedRelayerEntriesAtInboundLane` constant from the pallet configuration. The PoV + /// `MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX` constant from the pallet configuration. The PoV /// of the call includes the maximal size of inbound lane state. If the actual size is smaller, /// we may subtract extra bytes from this component. pub fn extra_proof_size_bytes(&mut self) -> u64 { let max_encoded_len = StoredInboundLaneData::::max_encoded_len(); let relayers_count = self.get_or_init_data().relayers.len(); let actual_encoded_len = - InboundLaneData::::encoded_size_hint(relayers_count) + InboundLaneData::>>::encoded_size_hint(relayers_count) .unwrap_or(usize::MAX); max_encoded_len.saturating_sub(actual_encoded_len) as _ } } impl, I: 'static> InboundLaneStorage for RuntimeInboundLaneStorage { - type Relayer = T::InboundRelayer; + type Relayer = AccountIdOf>; fn id(&self) -> LaneId { self.lane_id } fn max_unrewarded_relayer_entries(&self) -> MessageNonce { - T::MaxUnrewardedRelayerEntriesAtInboundLane::get() + BridgedChainOf::::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX } fn max_unconfirmed_messages(&self) -> MessageNonce { - T::MaxUnconfirmedMessagesAtInboundLane::get() + BridgedChainOf::::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX } - fn get_or_init_data(&mut self) -> InboundLaneData { + fn get_or_init_data(&mut self) -> InboundLaneData>> { match self.cached_data { Some(ref data) => data.clone(), None => { - let data: InboundLaneData = + let data: InboundLaneData>> = InboundLanes::::get(self.lane_id).into(); self.cached_data = Some(data.clone()); data @@ -842,7 +795,7 @@ impl, I: 'static> InboundLaneStorage for RuntimeInboundLaneStorage< } } - fn set_data(&mut self, data: InboundLaneData) { + fn set_data(&mut self, data: InboundLaneData>>) { self.cached_data = Some(data.clone()); InboundLanes::::insert(self.lane_id, StoredInboundLaneData::(data)) } @@ -887,14 +840,14 @@ impl, I: 'static> OutboundLaneStorage for RuntimeOutboundLaneStorag } /// Verify messages proof and return proved messages with decoded payload. -fn verify_and_decode_messages_proof( - proof: Chain::MessagesProof, +fn verify_and_decode_messages_proof, I: 'static>( + proof: FromBridgedChainMessagesProof>>, messages_count: u32, -) -> Result>, VerificationError> { - // `receive_messages_proof` weight formula and `MaxUnconfirmedMessagesAtInboundLane` check - // guarantees that the `message_count` is sane and Vec may be allocated. +) -> Result>, VerificationError> { + // `receive_messages_proof` weight formula and `MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX` + // check guarantees that the `message_count` is sane and Vec may be allocated. // (tx with too many messages will either be rejected from the pool, or will fail earlier) - Chain::verify_messages_proof(proof, messages_count).map(|messages_by_lane| { + proofs::verify_messages_proof::(proof, messages_count).map(|messages_by_lane| { messages_by_lane .into_iter() .map(|(lane, lane_data)| { @@ -909,1209 +862,3 @@ fn verify_and_decode_messages_proof::set_block_number(1); - System::::reset_events(); - } - - fn send_regular_message(lane_id: LaneId) { - get_ready_for_events(); - - let outbound_lane = outbound_lane::(lane_id); - let message_nonce = outbound_lane.data().latest_generated_nonce + 1; - let prev_enqueued_messages = outbound_lane.data().queued_messages().saturating_len(); - let valid_message = Pallet::::validate_message(lane_id, ®ULAR_PAYLOAD) - .expect("validate_message has failed"); - let artifacts = Pallet::::send_message(valid_message); - assert_eq!(artifacts.enqueued_messages, prev_enqueued_messages + 1); - - // check event with assigned nonce - assert_eq!( - System::::events(), - vec![EventRecord { - phase: Phase::Initialization, - event: TestEvent::Messages(Event::MessageAccepted { - lane_id, - nonce: message_nonce - }), - topics: vec![], - }], - ); - } - - fn receive_messages_delivery_proof() { - System::::set_block_number(1); - System::::reset_events(); - - assert_ok!(Pallet::::receive_messages_delivery_proof( - RuntimeOrigin::signed(1), - TestMessagesDeliveryProof(Ok(( - TEST_LANE_ID, - InboundLaneData { - last_confirmed_nonce: 1, - relayers: vec![UnrewardedRelayer { - relayer: 0, - messages: DeliveredMessages::new(1), - }] - .into_iter() - .collect(), - }, - ))), - UnrewardedRelayersState { - unrewarded_relayer_entries: 1, - messages_in_oldest_entry: 1, - total_messages: 1, - last_delivered_nonce: 1, - }, - )); - - assert_eq!( - System::::events(), - vec![EventRecord { - phase: Phase::Initialization, - event: TestEvent::Messages(Event::MessagesDelivered { - lane_id: TEST_LANE_ID, - messages: DeliveredMessages::new(1), - }), - topics: vec![], - }], - ); - } - - #[test] - fn pallet_rejects_transactions_if_halted() { - run_test(|| { - // send message first to be able to check that delivery_proof fails later - send_regular_message(TEST_LANE_ID); - - PalletOperatingMode::::put(MessagesOperatingMode::Basic( - BasicOperatingMode::Halted, - )); - - assert_noop!( - Pallet::::validate_message(TEST_LANE_ID, ®ULAR_PAYLOAD), - Error::::NotOperatingNormally, - ); - - assert_noop!( - Pallet::::receive_messages_proof( - RuntimeOrigin::signed(1), - TEST_RELAYER_A, - Ok(vec![message(2, REGULAR_PAYLOAD)]).into(), - 1, - REGULAR_PAYLOAD.declared_weight, - ), - Error::::BridgeModule(bp_runtime::OwnedBridgeModuleError::Halted), - ); - - assert_noop!( - Pallet::::receive_messages_delivery_proof( - RuntimeOrigin::signed(1), - TestMessagesDeliveryProof(Ok(( - TEST_LANE_ID, - InboundLaneData { - last_confirmed_nonce: 1, - relayers: vec![unrewarded_relayer(1, 1, TEST_RELAYER_A)] - .into_iter() - .collect(), - }, - ))), - UnrewardedRelayersState { - unrewarded_relayer_entries: 1, - messages_in_oldest_entry: 1, - total_messages: 1, - last_delivered_nonce: 1, - }, - ), - Error::::BridgeModule(bp_runtime::OwnedBridgeModuleError::Halted), - ); - }); - } - - #[test] - fn pallet_rejects_new_messages_in_rejecting_outbound_messages_operating_mode() { - run_test(|| { - // send message first to be able to check that delivery_proof fails later - send_regular_message(TEST_LANE_ID); - - PalletOperatingMode::::put( - MessagesOperatingMode::RejectingOutboundMessages, - ); - - assert_noop!( - Pallet::::validate_message(TEST_LANE_ID, ®ULAR_PAYLOAD), - Error::::NotOperatingNormally, - ); - - assert_ok!(Pallet::::receive_messages_proof( - RuntimeOrigin::signed(1), - TEST_RELAYER_A, - Ok(vec![message(1, REGULAR_PAYLOAD)]).into(), - 1, - REGULAR_PAYLOAD.declared_weight, - ),); - - assert_ok!(Pallet::::receive_messages_delivery_proof( - RuntimeOrigin::signed(1), - TestMessagesDeliveryProof(Ok(( - TEST_LANE_ID, - InboundLaneData { - last_confirmed_nonce: 1, - relayers: vec![unrewarded_relayer(1, 1, TEST_RELAYER_A)] - .into_iter() - .collect(), - }, - ))), - UnrewardedRelayersState { - unrewarded_relayer_entries: 1, - messages_in_oldest_entry: 1, - total_messages: 1, - last_delivered_nonce: 1, - }, - )); - }); - } - - #[test] - fn send_message_works() { - run_test(|| { - send_regular_message(TEST_LANE_ID); - }); - } - - #[test] - fn send_message_rejects_too_large_message() { - run_test(|| { - let mut message_payload = message_payload(1, 0); - // the payload isn't simply extra, so it'll definitely overflow - // `MAX_OUTBOUND_PAYLOAD_SIZE` if we add `MAX_OUTBOUND_PAYLOAD_SIZE` bytes to extra - message_payload - .extra - .extend_from_slice(&[0u8; MAX_OUTBOUND_PAYLOAD_SIZE as usize]); - assert_noop!( - Pallet::::validate_message(TEST_LANE_ID, &message_payload.clone(),), - Error::::MessageRejectedByPallet( - VerificationError::MessageTooLarge - ), - ); - - // let's check that we're able to send `MAX_OUTBOUND_PAYLOAD_SIZE` messages - while message_payload.encoded_size() as u32 > MAX_OUTBOUND_PAYLOAD_SIZE { - message_payload.extra.pop(); - } - assert_eq!(message_payload.encoded_size() as u32, MAX_OUTBOUND_PAYLOAD_SIZE); - - let valid_message = - Pallet::::validate_message(TEST_LANE_ID, &message_payload) - .expect("validate_message has failed"); - Pallet::::send_message(valid_message); - }) - } - - #[test] - fn chain_verifier_rejects_invalid_message_in_send_message() { - run_test(|| { - // messages with this payload are rejected by target chain verifier - assert_noop!( - Pallet::::validate_message( - TEST_LANE_ID, - &PAYLOAD_REJECTED_BY_TARGET_CHAIN, - ), - Error::::MessageRejectedByChainVerifier(VerificationError::Other( - mock::TEST_ERROR - )), - ); - }); - } - - #[test] - fn receive_messages_proof_works() { - run_test(|| { - assert_ok!(Pallet::::receive_messages_proof( - RuntimeOrigin::signed(1), - TEST_RELAYER_A, - Ok(vec![message(1, REGULAR_PAYLOAD)]).into(), - 1, - REGULAR_PAYLOAD.declared_weight, - )); - - assert_eq!(InboundLanes::::get(TEST_LANE_ID).0.last_delivered_nonce(), 1); - - assert!(TestDeliveryPayments::is_reward_paid(1)); - }); - } - - #[test] - fn receive_messages_proof_updates_confirmed_message_nonce() { - run_test(|| { - // say we have received 10 messages && last confirmed message is 8 - InboundLanes::::insert( - TEST_LANE_ID, - InboundLaneData { - last_confirmed_nonce: 8, - relayers: vec![ - unrewarded_relayer(9, 9, TEST_RELAYER_A), - unrewarded_relayer(10, 10, TEST_RELAYER_B), - ] - .into_iter() - .collect(), - }, - ); - assert_eq!( - inbound_unrewarded_relayers_state(TEST_LANE_ID), - UnrewardedRelayersState { - unrewarded_relayer_entries: 2, - messages_in_oldest_entry: 1, - total_messages: 2, - last_delivered_nonce: 10, - }, - ); - - // message proof includes outbound lane state with latest confirmed message updated to 9 - let mut message_proof: TestMessagesProof = - Ok(vec![message(11, REGULAR_PAYLOAD)]).into(); - message_proof.result.as_mut().unwrap()[0].1.lane_state = - Some(OutboundLaneData { latest_received_nonce: 9, ..Default::default() }); - - assert_ok!(Pallet::::receive_messages_proof( - RuntimeOrigin::signed(1), - TEST_RELAYER_A, - message_proof, - 1, - REGULAR_PAYLOAD.declared_weight, - )); - - assert_eq!( - InboundLanes::::get(TEST_LANE_ID).0, - InboundLaneData { - last_confirmed_nonce: 9, - relayers: vec![ - unrewarded_relayer(10, 10, TEST_RELAYER_B), - unrewarded_relayer(11, 11, TEST_RELAYER_A) - ] - .into_iter() - .collect(), - }, - ); - assert_eq!( - inbound_unrewarded_relayers_state(TEST_LANE_ID), - UnrewardedRelayersState { - unrewarded_relayer_entries: 2, - messages_in_oldest_entry: 1, - total_messages: 2, - last_delivered_nonce: 11, - }, - ); - }); - } - - #[test] - fn receive_messages_fails_if_dispatcher_is_inactive() { - run_test(|| { - TestMessageDispatch::deactivate(); - assert_noop!( - Pallet::::receive_messages_proof( - RuntimeOrigin::signed(1), - TEST_RELAYER_A, - Ok(vec![message(1, REGULAR_PAYLOAD)]).into(), - 1, - REGULAR_PAYLOAD.declared_weight, - ), - Error::::MessageDispatchInactive, - ); - }); - } - - #[test] - fn receive_messages_proof_does_not_accept_message_if_dispatch_weight_is_not_enough() { - run_test(|| { - let mut declared_weight = REGULAR_PAYLOAD.declared_weight; - *declared_weight.ref_time_mut() -= 1; - assert_noop!( - Pallet::::receive_messages_proof( - RuntimeOrigin::signed(1), - TEST_RELAYER_A, - Ok(vec![message(1, REGULAR_PAYLOAD)]).into(), - 1, - declared_weight, - ), - Error::::InsufficientDispatchWeight - ); - assert_eq!(InboundLanes::::get(TEST_LANE_ID).last_delivered_nonce(), 0); - }); - } - - #[test] - fn receive_messages_proof_rejects_invalid_proof() { - run_test(|| { - assert_noop!( - Pallet::::receive_messages_proof( - RuntimeOrigin::signed(1), - TEST_RELAYER_A, - Err(()).into(), - 1, - Weight::zero(), - ), - Error::::InvalidMessagesProof, - ); - }); - } - - #[test] - fn receive_messages_proof_rejects_proof_with_too_many_messages() { - run_test(|| { - assert_noop!( - Pallet::::receive_messages_proof( - RuntimeOrigin::signed(1), - TEST_RELAYER_A, - Ok(vec![message(1, REGULAR_PAYLOAD)]).into(), - u32::MAX, - Weight::zero(), - ), - Error::::TooManyMessagesInTheProof, - ); - }); - } - - #[test] - fn receive_messages_delivery_proof_works() { - run_test(|| { - send_regular_message(TEST_LANE_ID); - receive_messages_delivery_proof(); - - assert_eq!( - OutboundLanes::::get(TEST_LANE_ID).latest_received_nonce, - 1, - ); - }); - } - - #[test] - fn receive_messages_delivery_proof_rewards_relayers() { - run_test(|| { - send_regular_message(TEST_LANE_ID); - send_regular_message(TEST_LANE_ID); - - // this reports delivery of message 1 => reward is paid to TEST_RELAYER_A - let single_message_delivery_proof = TestMessagesDeliveryProof(Ok(( - TEST_LANE_ID, - InboundLaneData { - relayers: vec![unrewarded_relayer(1, 1, TEST_RELAYER_A)].into_iter().collect(), - ..Default::default() - }, - ))); - let single_message_delivery_proof_size = single_message_delivery_proof.size(); - let result = Pallet::::receive_messages_delivery_proof( - RuntimeOrigin::signed(1), - single_message_delivery_proof, - UnrewardedRelayersState { - unrewarded_relayer_entries: 1, - messages_in_oldest_entry: 1, - total_messages: 1, - last_delivered_nonce: 1, - }, - ); - assert_ok!(result); - assert_eq!( - result.unwrap().actual_weight.unwrap(), - TestWeightInfo::receive_messages_delivery_proof_weight( - &PreComputedSize(single_message_delivery_proof_size as _), - &UnrewardedRelayersState { - unrewarded_relayer_entries: 1, - total_messages: 1, - ..Default::default() - }, - ) - ); - assert!(TestDeliveryConfirmationPayments::is_reward_paid(TEST_RELAYER_A, 1)); - assert!(!TestDeliveryConfirmationPayments::is_reward_paid(TEST_RELAYER_B, 1)); - assert_eq!(TestOnMessagesDelivered::call_arguments(), Some((TEST_LANE_ID, 1))); - - // this reports delivery of both message 1 and message 2 => reward is paid only to - // TEST_RELAYER_B - let two_messages_delivery_proof = TestMessagesDeliveryProof(Ok(( - TEST_LANE_ID, - InboundLaneData { - relayers: vec![ - unrewarded_relayer(1, 1, TEST_RELAYER_A), - unrewarded_relayer(2, 2, TEST_RELAYER_B), - ] - .into_iter() - .collect(), - ..Default::default() - }, - ))); - let two_messages_delivery_proof_size = two_messages_delivery_proof.size(); - let result = Pallet::::receive_messages_delivery_proof( - RuntimeOrigin::signed(1), - two_messages_delivery_proof, - UnrewardedRelayersState { - unrewarded_relayer_entries: 2, - messages_in_oldest_entry: 1, - total_messages: 2, - last_delivered_nonce: 2, - }, - ); - assert_ok!(result); - // even though the pre-dispatch weight was for two messages, the actual weight is - // for single message only - assert_eq!( - result.unwrap().actual_weight.unwrap(), - TestWeightInfo::receive_messages_delivery_proof_weight( - &PreComputedSize(two_messages_delivery_proof_size as _), - &UnrewardedRelayersState { - unrewarded_relayer_entries: 1, - total_messages: 1, - ..Default::default() - }, - ) - ); - assert!(!TestDeliveryConfirmationPayments::is_reward_paid(TEST_RELAYER_A, 1)); - assert!(TestDeliveryConfirmationPayments::is_reward_paid(TEST_RELAYER_B, 1)); - assert_eq!(TestOnMessagesDelivered::call_arguments(), Some((TEST_LANE_ID, 0))); - }); - } - - #[test] - fn receive_messages_delivery_proof_rejects_invalid_proof() { - run_test(|| { - assert_noop!( - Pallet::::receive_messages_delivery_proof( - RuntimeOrigin::signed(1), - TestMessagesDeliveryProof(Err(())), - Default::default(), - ), - Error::::InvalidMessagesDeliveryProof, - ); - }); - } - - #[test] - fn receive_messages_delivery_proof_rejects_proof_if_declared_relayers_state_is_invalid() { - run_test(|| { - // when number of relayers entries is invalid - assert_noop!( - Pallet::::receive_messages_delivery_proof( - RuntimeOrigin::signed(1), - TestMessagesDeliveryProof(Ok(( - TEST_LANE_ID, - InboundLaneData { - relayers: vec![ - unrewarded_relayer(1, 1, TEST_RELAYER_A), - unrewarded_relayer(2, 2, TEST_RELAYER_B) - ] - .into_iter() - .collect(), - ..Default::default() - } - ))), - UnrewardedRelayersState { - unrewarded_relayer_entries: 1, - total_messages: 2, - last_delivered_nonce: 2, - ..Default::default() - }, - ), - Error::::InvalidUnrewardedRelayersState, - ); - - // when number of messages is invalid - assert_noop!( - Pallet::::receive_messages_delivery_proof( - RuntimeOrigin::signed(1), - TestMessagesDeliveryProof(Ok(( - TEST_LANE_ID, - InboundLaneData { - relayers: vec![ - unrewarded_relayer(1, 1, TEST_RELAYER_A), - unrewarded_relayer(2, 2, TEST_RELAYER_B) - ] - .into_iter() - .collect(), - ..Default::default() - } - ))), - UnrewardedRelayersState { - unrewarded_relayer_entries: 2, - total_messages: 1, - last_delivered_nonce: 2, - ..Default::default() - }, - ), - Error::::InvalidUnrewardedRelayersState, - ); - - // when last delivered nonce is invalid - assert_noop!( - Pallet::::receive_messages_delivery_proof( - RuntimeOrigin::signed(1), - TestMessagesDeliveryProof(Ok(( - TEST_LANE_ID, - InboundLaneData { - relayers: vec![ - unrewarded_relayer(1, 1, TEST_RELAYER_A), - unrewarded_relayer(2, 2, TEST_RELAYER_B) - ] - .into_iter() - .collect(), - ..Default::default() - } - ))), - UnrewardedRelayersState { - unrewarded_relayer_entries: 2, - total_messages: 2, - last_delivered_nonce: 8, - ..Default::default() - }, - ), - Error::::InvalidUnrewardedRelayersState, - ); - }); - } - - #[test] - fn receive_messages_accepts_single_message_with_invalid_payload() { - run_test(|| { - let mut invalid_message = message(1, REGULAR_PAYLOAD); - invalid_message.payload = Vec::new(); - - assert_ok!(Pallet::::receive_messages_proof( - RuntimeOrigin::signed(1), - TEST_RELAYER_A, - Ok(vec![invalid_message]).into(), - 1, - Weight::zero(), /* weight may be zero in this case (all messages are - * improperly encoded) */ - ),); - - assert_eq!(InboundLanes::::get(TEST_LANE_ID).last_delivered_nonce(), 1,); - }); - } - - #[test] - fn receive_messages_accepts_batch_with_message_with_invalid_payload() { - run_test(|| { - let mut invalid_message = message(2, REGULAR_PAYLOAD); - invalid_message.payload = Vec::new(); - - assert_ok!(Pallet::::receive_messages_proof( - RuntimeOrigin::signed(1), - TEST_RELAYER_A, - Ok( - vec![message(1, REGULAR_PAYLOAD), invalid_message, message(3, REGULAR_PAYLOAD),] - ) - .into(), - 3, - REGULAR_PAYLOAD.declared_weight + REGULAR_PAYLOAD.declared_weight, - ),); - - assert_eq!(InboundLanes::::get(TEST_LANE_ID).last_delivered_nonce(), 3,); - }); - } - - #[test] - fn actual_dispatch_weight_does_not_overflow() { - run_test(|| { - let message1 = message(1, message_payload(0, u64::MAX / 2)); - let message2 = message(2, message_payload(0, u64::MAX / 2)); - let message3 = message(3, message_payload(0, u64::MAX / 2)); - - assert_noop!( - Pallet::::receive_messages_proof( - RuntimeOrigin::signed(1), - TEST_RELAYER_A, - // this may cause overflow if source chain storage is invalid - Ok(vec![message1, message2, message3]).into(), - 3, - Weight::MAX, - ), - Error::::InsufficientDispatchWeight - ); - assert_eq!(InboundLanes::::get(TEST_LANE_ID).last_delivered_nonce(), 0); - }); - } - - #[test] - fn ref_time_refund_from_receive_messages_proof_works() { - run_test(|| { - fn submit_with_unspent_weight( - nonce: MessageNonce, - unspent_weight: u64, - ) -> (Weight, Weight) { - let mut payload = REGULAR_PAYLOAD; - *payload.dispatch_result.unspent_weight.ref_time_mut() = unspent_weight; - let proof = Ok(vec![message(nonce, payload)]).into(); - let messages_count = 1; - let pre_dispatch_weight = - ::WeightInfo::receive_messages_proof_weight( - &proof, - messages_count, - REGULAR_PAYLOAD.declared_weight, - ); - let result = Pallet::::receive_messages_proof( - RuntimeOrigin::signed(1), - TEST_RELAYER_A, - proof, - messages_count, - REGULAR_PAYLOAD.declared_weight, - ) - .expect("delivery has failed"); - let post_dispatch_weight = - result.actual_weight.expect("receive_messages_proof always returns Some"); - - // message delivery transactions are never free - assert_eq!(result.pays_fee, Pays::Yes); - - (pre_dispatch_weight, post_dispatch_weight) - } - - // when dispatch is returning `unspent_weight < declared_weight` - let (pre, post) = submit_with_unspent_weight(1, 1); - assert_eq!(post.ref_time(), pre.ref_time() - 1); - - // when dispatch is returning `unspent_weight = declared_weight` - let (pre, post) = - submit_with_unspent_weight(2, REGULAR_PAYLOAD.declared_weight.ref_time()); - assert_eq!( - post.ref_time(), - pre.ref_time() - REGULAR_PAYLOAD.declared_weight.ref_time() - ); - - // when dispatch is returning `unspent_weight > declared_weight` - let (pre, post) = - submit_with_unspent_weight(3, REGULAR_PAYLOAD.declared_weight.ref_time() + 1); - assert_eq!( - post.ref_time(), - pre.ref_time() - REGULAR_PAYLOAD.declared_weight.ref_time() - ); - - // when there's no unspent weight - let (pre, post) = submit_with_unspent_weight(4, 0); - assert_eq!(post.ref_time(), pre.ref_time()); - - // when dispatch is returning `unspent_weight < declared_weight` - let (pre, post) = submit_with_unspent_weight(5, 1); - assert_eq!(post.ref_time(), pre.ref_time() - 1); - }); - } - - #[test] - fn proof_size_refund_from_receive_messages_proof_works() { - run_test(|| { - let max_entries = crate::mock::MaxUnrewardedRelayerEntriesAtInboundLane::get() as usize; - - // if there's maximal number of unrewarded relayer entries at the inbound lane, then - // `proof_size` is unchanged in post-dispatch weight - let proof: TestMessagesProof = Ok(vec![message(101, REGULAR_PAYLOAD)]).into(); - let messages_count = 1; - let pre_dispatch_weight = - ::WeightInfo::receive_messages_proof_weight( - &proof, - messages_count, - REGULAR_PAYLOAD.declared_weight, - ); - InboundLanes::::insert( - TEST_LANE_ID, - StoredInboundLaneData(InboundLaneData { - relayers: vec![ - UnrewardedRelayer { - relayer: 42, - messages: DeliveredMessages { begin: 0, end: 100 } - }; - max_entries - ] - .into_iter() - .collect(), - last_confirmed_nonce: 0, - }), - ); - let post_dispatch_weight = Pallet::::receive_messages_proof( - RuntimeOrigin::signed(1), - TEST_RELAYER_A, - proof.clone(), - messages_count, - REGULAR_PAYLOAD.declared_weight, - ) - .unwrap() - .actual_weight - .unwrap(); - assert_eq!(post_dispatch_weight.proof_size(), pre_dispatch_weight.proof_size()); - - // if count of unrewarded relayer entries is less than maximal, then some `proof_size` - // must be refunded - InboundLanes::::insert( - TEST_LANE_ID, - StoredInboundLaneData(InboundLaneData { - relayers: vec![ - UnrewardedRelayer { - relayer: 42, - messages: DeliveredMessages { begin: 0, end: 100 } - }; - max_entries - 1 - ] - .into_iter() - .collect(), - last_confirmed_nonce: 0, - }), - ); - let post_dispatch_weight = Pallet::::receive_messages_proof( - RuntimeOrigin::signed(1), - TEST_RELAYER_A, - proof, - messages_count, - REGULAR_PAYLOAD.declared_weight, - ) - .unwrap() - .actual_weight - .unwrap(); - assert!( - post_dispatch_weight.proof_size() < pre_dispatch_weight.proof_size(), - "Expected post-dispatch PoV {} to be less than pre-dispatch PoV {}", - post_dispatch_weight.proof_size(), - pre_dispatch_weight.proof_size(), - ); - }); - } - - #[test] - fn messages_delivered_callbacks_are_called() { - run_test(|| { - send_regular_message(TEST_LANE_ID); - send_regular_message(TEST_LANE_ID); - send_regular_message(TEST_LANE_ID); - - // messages 1+2 are confirmed in 1 tx, message 3 in a separate tx - // dispatch of message 2 has failed - let mut delivered_messages_1_and_2 = DeliveredMessages::new(1); - delivered_messages_1_and_2.note_dispatched_message(); - let messages_1_and_2_proof = Ok(( - TEST_LANE_ID, - InboundLaneData { - last_confirmed_nonce: 0, - relayers: vec![UnrewardedRelayer { - relayer: 0, - messages: delivered_messages_1_and_2.clone(), - }] - .into_iter() - .collect(), - }, - )); - let delivered_message_3 = DeliveredMessages::new(3); - let messages_3_proof = Ok(( - TEST_LANE_ID, - InboundLaneData { - last_confirmed_nonce: 0, - relayers: vec![UnrewardedRelayer { relayer: 0, messages: delivered_message_3 }] - .into_iter() - .collect(), - }, - )); - - // first tx with messages 1+2 - assert_ok!(Pallet::::receive_messages_delivery_proof( - RuntimeOrigin::signed(1), - TestMessagesDeliveryProof(messages_1_and_2_proof), - UnrewardedRelayersState { - unrewarded_relayer_entries: 1, - messages_in_oldest_entry: 2, - total_messages: 2, - last_delivered_nonce: 2, - }, - )); - // second tx with message 3 - assert_ok!(Pallet::::receive_messages_delivery_proof( - RuntimeOrigin::signed(1), - TestMessagesDeliveryProof(messages_3_proof), - UnrewardedRelayersState { - unrewarded_relayer_entries: 1, - messages_in_oldest_entry: 1, - total_messages: 1, - last_delivered_nonce: 3, - }, - )); - }); - } - - #[test] - fn receive_messages_delivery_proof_rejects_proof_if_trying_to_confirm_more_messages_than_expected( - ) { - run_test(|| { - // send message first to be able to check that delivery_proof fails later - send_regular_message(TEST_LANE_ID); - - // 1) InboundLaneData declares that the `last_confirmed_nonce` is 1; - // 2) InboundLaneData has no entries => `InboundLaneData::last_delivered_nonce()` - // returns `last_confirmed_nonce`; - // 3) it means that we're going to confirm delivery of messages 1..=1; - // 4) so the number of declared messages (see `UnrewardedRelayersState`) is `0` and - // number of actually confirmed messages is `1`. - assert_noop!( - Pallet::::receive_messages_delivery_proof( - RuntimeOrigin::signed(1), - TestMessagesDeliveryProof(Ok(( - TEST_LANE_ID, - InboundLaneData { last_confirmed_nonce: 1, relayers: Default::default() }, - ))), - UnrewardedRelayersState { last_delivered_nonce: 1, ..Default::default() }, - ), - Error::::ReceptionConfirmation( - ReceptionConfirmationError::TryingToConfirmMoreMessagesThanExpected - ), - ); - }); - } - - #[test] - fn storage_keys_computed_properly() { - assert_eq!( - PalletOperatingMode::::storage_value_final_key().to_vec(), - bp_messages::storage_keys::operating_mode_key("Messages").0, - ); - - assert_eq!( - OutboundMessages::::storage_map_final_key(MessageKey { - lane_id: TEST_LANE_ID, - nonce: 42 - }), - bp_messages::storage_keys::message_key("Messages", &TEST_LANE_ID, 42).0, - ); - - assert_eq!( - OutboundLanes::::storage_map_final_key(TEST_LANE_ID), - bp_messages::storage_keys::outbound_lane_data_key("Messages", &TEST_LANE_ID).0, - ); - - assert_eq!( - InboundLanes::::storage_map_final_key(TEST_LANE_ID), - bp_messages::storage_keys::inbound_lane_data_key("Messages", &TEST_LANE_ID).0, - ); - } - - #[test] - fn inbound_message_details_works() { - run_test(|| { - assert_eq!( - Pallet::::inbound_message_data( - TEST_LANE_ID, - REGULAR_PAYLOAD.encode(), - OutboundMessageDetails { nonce: 0, dispatch_weight: Weight::zero(), size: 0 }, - ), - InboundMessageDetails { dispatch_weight: REGULAR_PAYLOAD.declared_weight }, - ); - }); - } - - #[test] - fn on_idle_callback_respects_remaining_weight() { - run_test(|| { - send_regular_message(TEST_LANE_ID); - send_regular_message(TEST_LANE_ID); - send_regular_message(TEST_LANE_ID); - send_regular_message(TEST_LANE_ID); - - assert_ok!(Pallet::::receive_messages_delivery_proof( - RuntimeOrigin::signed(1), - TestMessagesDeliveryProof(Ok(( - TEST_LANE_ID, - InboundLaneData { - last_confirmed_nonce: 4, - relayers: vec![unrewarded_relayer(1, 4, TEST_RELAYER_A)] - .into_iter() - .collect(), - }, - ))), - UnrewardedRelayersState { - unrewarded_relayer_entries: 1, - messages_in_oldest_entry: 4, - total_messages: 4, - last_delivered_nonce: 4, - }, - )); - - // all 4 messages may be pruned now - assert_eq!( - outbound_lane::(TEST_LANE_ID).data().latest_received_nonce, - 4 - ); - assert_eq!( - outbound_lane::(TEST_LANE_ID).data().oldest_unpruned_nonce, - 1 - ); - System::::set_block_number(2); - - // if passed wight is too low to do anything - let dbw = DbWeight::get(); - assert_eq!( - Pallet::::on_idle(0, dbw.reads_writes(1, 1)), - Weight::zero(), - ); - assert_eq!( - outbound_lane::(TEST_LANE_ID).data().oldest_unpruned_nonce, - 1 - ); - - // if passed wight is enough to prune single message - assert_eq!( - Pallet::::on_idle(0, dbw.reads_writes(1, 2)), - dbw.reads_writes(1, 2), - ); - assert_eq!( - outbound_lane::(TEST_LANE_ID).data().oldest_unpruned_nonce, - 2 - ); - - // if passed wight is enough to prune two more messages - assert_eq!( - Pallet::::on_idle(0, dbw.reads_writes(1, 3)), - dbw.reads_writes(1, 3), - ); - assert_eq!( - outbound_lane::(TEST_LANE_ID).data().oldest_unpruned_nonce, - 4 - ); - - // if passed wight is enough to prune many messages - assert_eq!( - Pallet::::on_idle(0, dbw.reads_writes(100, 100)), - dbw.reads_writes(1, 2), - ); - assert_eq!( - outbound_lane::(TEST_LANE_ID).data().oldest_unpruned_nonce, - 5 - ); - }); - } - - #[test] - fn on_idle_callback_is_rotating_lanes_to_prune() { - run_test(|| { - // send + receive confirmation for lane 1 - send_regular_message(TEST_LANE_ID); - receive_messages_delivery_proof(); - // send + receive confirmation for lane 2 - send_regular_message(TEST_LANE_ID_2); - assert_ok!(Pallet::::receive_messages_delivery_proof( - RuntimeOrigin::signed(1), - TestMessagesDeliveryProof(Ok(( - TEST_LANE_ID_2, - InboundLaneData { - last_confirmed_nonce: 1, - relayers: vec![unrewarded_relayer(1, 1, TEST_RELAYER_A)] - .into_iter() - .collect(), - }, - ))), - UnrewardedRelayersState { - unrewarded_relayer_entries: 1, - messages_in_oldest_entry: 1, - total_messages: 1, - last_delivered_nonce: 1, - }, - )); - - // nothing is pruned yet - assert_eq!( - outbound_lane::(TEST_LANE_ID).data().latest_received_nonce, - 1 - ); - assert_eq!( - outbound_lane::(TEST_LANE_ID).data().oldest_unpruned_nonce, - 1 - ); - assert_eq!( - outbound_lane::(TEST_LANE_ID_2).data().latest_received_nonce, - 1 - ); - assert_eq!( - outbound_lane::(TEST_LANE_ID_2).data().oldest_unpruned_nonce, - 1 - ); - - // in block#2.on_idle lane messages of lane 1 are pruned - let dbw = DbWeight::get(); - System::::set_block_number(2); - assert_eq!( - Pallet::::on_idle(0, dbw.reads_writes(100, 100)), - dbw.reads_writes(1, 2), - ); - assert_eq!( - outbound_lane::(TEST_LANE_ID).data().oldest_unpruned_nonce, - 2 - ); - assert_eq!( - outbound_lane::(TEST_LANE_ID_2).data().oldest_unpruned_nonce, - 1 - ); - - // in block#3.on_idle lane messages of lane 2 are pruned - System::::set_block_number(3); - - assert_eq!( - Pallet::::on_idle(0, dbw.reads_writes(100, 100)), - dbw.reads_writes(1, 2), - ); - assert_eq!( - outbound_lane::(TEST_LANE_ID).data().oldest_unpruned_nonce, - 2 - ); - assert_eq!( - outbound_lane::(TEST_LANE_ID_2).data().oldest_unpruned_nonce, - 2 - ); - }); - } - - #[test] - fn outbound_message_from_unconfigured_lane_is_rejected() { - run_test(|| { - assert_noop!( - Pallet::::validate_message(TEST_LANE_ID_3, ®ULAR_PAYLOAD,), - Error::::InactiveOutboundLane, - ); - }); - } - - #[test] - fn test_bridge_messages_call_is_correctly_defined() { - let account_id = 1; - let message_proof: TestMessagesProof = Ok(vec![message(1, REGULAR_PAYLOAD)]).into(); - let message_delivery_proof = TestMessagesDeliveryProof(Ok(( - TEST_LANE_ID, - InboundLaneData { - last_confirmed_nonce: 1, - relayers: vec![UnrewardedRelayer { - relayer: 0, - messages: DeliveredMessages::new(1), - }] - .into_iter() - .collect(), - }, - ))); - let unrewarded_relayer_state = UnrewardedRelayersState { - unrewarded_relayer_entries: 1, - total_messages: 1, - last_delivered_nonce: 1, - ..Default::default() - }; - - let direct_receive_messages_proof_call = Call::::receive_messages_proof { - relayer_id_at_bridged_chain: account_id, - proof: message_proof.clone(), - messages_count: 1, - dispatch_weight: REGULAR_PAYLOAD.declared_weight, - }; - let indirect_receive_messages_proof_call = BridgeMessagesCall::< - AccountId, - TestMessagesProof, - TestMessagesDeliveryProof, - >::receive_messages_proof { - relayer_id_at_bridged_chain: account_id, - proof: message_proof, - messages_count: 1, - dispatch_weight: REGULAR_PAYLOAD.declared_weight, - }; - assert_eq!( - direct_receive_messages_proof_call.encode(), - indirect_receive_messages_proof_call.encode() - ); - - let direct_receive_messages_delivery_proof_call = - Call::::receive_messages_delivery_proof { - proof: message_delivery_proof.clone(), - relayers_state: unrewarded_relayer_state.clone(), - }; - let indirect_receive_messages_delivery_proof_call = BridgeMessagesCall::< - AccountId, - TestMessagesProof, - TestMessagesDeliveryProof, - >::receive_messages_delivery_proof { - proof: message_delivery_proof, - relayers_state: unrewarded_relayer_state, - }; - assert_eq!( - direct_receive_messages_delivery_proof_call.encode(), - indirect_receive_messages_delivery_proof_call.encode() - ); - } - - generate_owned_bridge_module_tests!( - MessagesOperatingMode::Basic(BasicOperatingMode::Normal), - MessagesOperatingMode::Basic(BasicOperatingMode::Halted) - ); - - #[test] - fn inbound_storage_extra_proof_size_bytes_works() { - fn relayer_entry() -> UnrewardedRelayer { - UnrewardedRelayer { relayer: 42u64, messages: DeliveredMessages { begin: 0, end: 100 } } - } - - fn storage(relayer_entries: usize) -> RuntimeInboundLaneStorage { - RuntimeInboundLaneStorage { - lane_id: Default::default(), - cached_data: Some(InboundLaneData { - relayers: vec![relayer_entry(); relayer_entries].into_iter().collect(), - last_confirmed_nonce: 0, - }), - _phantom: Default::default(), - } - } - - let max_entries = crate::mock::MaxUnrewardedRelayerEntriesAtInboundLane::get() as usize; - - // when we have exactly `MaxUnrewardedRelayerEntriesAtInboundLane` unrewarded relayers - assert_eq!(storage(max_entries).extra_proof_size_bytes(), 0); - - // when we have less than `MaxUnrewardedRelayerEntriesAtInboundLane` unrewarded relayers - assert_eq!( - storage(max_entries - 1).extra_proof_size_bytes(), - relayer_entry().encode().len() as u64 - ); - assert_eq!( - storage(max_entries - 2).extra_proof_size_bytes(), - 2 * relayer_entry().encode().len() as u64 - ); - - // when we have more than `MaxUnrewardedRelayerEntriesAtInboundLane` unrewarded relayers - // (shall not happen in practice) - assert_eq!(storage(max_entries + 1).extra_proof_size_bytes(), 0); - } - - #[test] - fn maybe_outbound_lanes_count_returns_correct_value() { - assert_eq!( - MaybeOutboundLanesCount::::get(), - Some(mock::ActiveOutboundLanes::get().len() as u32) - ); - } -} diff --git a/bridges/modules/messages/src/outbound_lane.rs b/bridges/modules/messages/src/outbound_lane.rs index acef5546d2a64fa8a3fb38c6b41ae30819cdeaa2..fcdddf199dc65b37dd014745b6a1630709ad8f8b 100644 --- a/bridges/modules/messages/src/outbound_lane.rs +++ b/bridges/modules/messages/src/outbound_lane.rs @@ -18,16 +18,18 @@ use crate::{Config, LOG_TARGET}; -use bp_messages::{DeliveredMessages, LaneId, MessageNonce, OutboundLaneData, UnrewardedRelayer}; +use bp_messages::{ + ChainWithMessages, DeliveredMessages, LaneId, MessageNonce, OutboundLaneData, UnrewardedRelayer, +}; use codec::{Decode, Encode}; use frame_support::{ + traits::Get, weights::{RuntimeDbWeight, Weight}, BoundedVec, PalletError, }; -use num_traits::Zero; use scale_info::TypeInfo; -use sp_runtime::RuntimeDebug; -use sp_std::collections::vec_deque::VecDeque; +use sp_runtime::{traits::Zero, RuntimeDebug}; +use sp_std::{collections::vec_deque::VecDeque, marker::PhantomData}; /// Outbound lane storage. pub trait OutboundLaneStorage { @@ -48,8 +50,17 @@ pub trait OutboundLaneStorage { fn remove_message(&mut self, nonce: &MessageNonce); } +/// Limit for the `StoredMessagePayload` vector. +pub struct StoredMessagePayloadLimit(PhantomData<(T, I)>); + +impl, I: 'static> Get for StoredMessagePayloadLimit { + fn get() -> u32 { + T::BridgedChain::maximal_incoming_message_size() + } +} + /// Outbound message data wrapper that implements `MaxEncodedLen`. -pub type StoredMessagePayload = BoundedVec>::MaximalOutboundPayloadSize>; +pub type StoredMessagePayload = BoundedVec>; /// Result of messages receival confirmation. #[derive(Encode, Decode, RuntimeDebug, PartialEq, Eq, PalletError, TypeInfo)] @@ -204,11 +215,11 @@ fn ensure_unrewarded_relayers_are_correct( mod tests { use super::*; use crate::{ - mock::{ + outbound_lane, + tests::mock::{ outbound_message_data, run_test, unrewarded_relayer, TestRelayer, TestRuntime, REGULAR_PAYLOAD, TEST_LANE_ID, }, - outbound_lane, }; use frame_support::weights::constants::RocksDbWeight; use sp_std::ops::RangeInclusive; @@ -263,12 +274,43 @@ mod tests { assert_eq!(lane.send_message(outbound_message_data(REGULAR_PAYLOAD)), 3); assert_eq!(lane.storage.data().latest_generated_nonce, 3); assert_eq!(lane.storage.data().latest_received_nonce, 0); + assert_eq!(lane.storage.data().oldest_unpruned_nonce, 1); assert_eq!( lane.confirm_delivery(3, 3, &unrewarded_relayers(1..=3)), Ok(Some(delivered_messages(1..=3))), ); assert_eq!(lane.storage.data().latest_generated_nonce, 3); assert_eq!(lane.storage.data().latest_received_nonce, 3); + assert_eq!(lane.storage.data().oldest_unpruned_nonce, 1); + }); + } + + #[test] + fn confirm_partial_delivery_works() { + run_test(|| { + let mut lane = outbound_lane::(TEST_LANE_ID); + assert_eq!(lane.send_message(outbound_message_data(REGULAR_PAYLOAD)), 1); + assert_eq!(lane.send_message(outbound_message_data(REGULAR_PAYLOAD)), 2); + assert_eq!(lane.send_message(outbound_message_data(REGULAR_PAYLOAD)), 3); + assert_eq!(lane.storage.data().latest_generated_nonce, 3); + assert_eq!(lane.storage.data().latest_received_nonce, 0); + assert_eq!(lane.storage.data().oldest_unpruned_nonce, 1); + + assert_eq!( + lane.confirm_delivery(3, 2, &unrewarded_relayers(1..=2)), + Ok(Some(delivered_messages(1..=2))), + ); + assert_eq!(lane.storage.data().latest_generated_nonce, 3); + assert_eq!(lane.storage.data().latest_received_nonce, 2); + assert_eq!(lane.storage.data().oldest_unpruned_nonce, 1); + + assert_eq!( + lane.confirm_delivery(3, 3, &unrewarded_relayers(3..=3)), + Ok(Some(delivered_messages(3..=3))), + ); + assert_eq!(lane.storage.data().latest_generated_nonce, 3); + assert_eq!(lane.storage.data().latest_received_nonce, 3); + assert_eq!(lane.storage.data().oldest_unpruned_nonce, 1); }); } @@ -281,6 +323,7 @@ mod tests { lane.send_message(outbound_message_data(REGULAR_PAYLOAD)); assert_eq!(lane.storage.data().latest_generated_nonce, 3); assert_eq!(lane.storage.data().latest_received_nonce, 0); + assert_eq!(lane.storage.data().oldest_unpruned_nonce, 1); assert_eq!( lane.confirm_delivery(3, 3, &unrewarded_relayers(1..=3)), Ok(Some(delivered_messages(1..=3))), @@ -288,10 +331,12 @@ mod tests { assert_eq!(lane.confirm_delivery(3, 3, &unrewarded_relayers(1..=3)), Ok(None),); assert_eq!(lane.storage.data().latest_generated_nonce, 3); assert_eq!(lane.storage.data().latest_received_nonce, 3); + assert_eq!(lane.storage.data().oldest_unpruned_nonce, 1); assert_eq!(lane.confirm_delivery(1, 2, &unrewarded_relayers(1..=1)), Ok(None),); assert_eq!(lane.storage.data().latest_generated_nonce, 3); assert_eq!(lane.storage.data().latest_received_nonce, 3); + assert_eq!(lane.storage.data().oldest_unpruned_nonce, 1); }); } @@ -310,8 +355,8 @@ mod tests { 3, &unrewarded_relayers(1..=1) .into_iter() - .chain(unrewarded_relayers(2..=30).into_iter()) - .chain(unrewarded_relayers(3..=3).into_iter()) + .chain(unrewarded_relayers(2..=30)) + .chain(unrewarded_relayers(3..=3)) .collect(), ), Err(ReceptionConfirmationError::FailedToConfirmFutureMessages), @@ -326,8 +371,8 @@ mod tests { 3, &unrewarded_relayers(1..=1) .into_iter() - .chain(unrewarded_relayers(2..=1).into_iter()) - .chain(unrewarded_relayers(2..=3).into_iter()) + .chain(unrewarded_relayers(2..=1)) + .chain(unrewarded_relayers(2..=3)) .collect(), ), Err(ReceptionConfirmationError::EmptyUnrewardedRelayerEntry), @@ -341,8 +386,8 @@ mod tests { 3, &unrewarded_relayers(1..=1) .into_iter() - .chain(unrewarded_relayers(3..=3).into_iter()) - .chain(unrewarded_relayers(2..=2).into_iter()) + .chain(unrewarded_relayers(3..=3)) + .chain(unrewarded_relayers(2..=2)) .collect(), ), Err(ReceptionConfirmationError::NonConsecutiveUnrewardedRelayerEntries), diff --git a/bridges/modules/messages/src/proofs.rs b/bridges/modules/messages/src/proofs.rs new file mode 100644 index 0000000000000000000000000000000000000000..18367029d72cd356939f19f769a36b634ad1991e --- /dev/null +++ b/bridges/modules/messages/src/proofs.rs @@ -0,0 +1,562 @@ +// Copyright 2019-2021 Parity Technologies (UK) Ltd. +// This file is part of Parity Bridges Common. + +// Parity Bridges Common is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity Bridges Common is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity Bridges Common. If not, see . + +//! Tools for messages and delivery proof verification. + +use crate::{BridgedChainOf, BridgedHeaderChainOf, Config}; + +use bp_header_chain::{HeaderChain, HeaderChainError}; +use bp_messages::{ + source_chain::FromBridgedChainMessagesDeliveryProof, + target_chain::{FromBridgedChainMessagesProof, ProvedLaneMessages, ProvedMessages}, + ChainWithMessages, InboundLaneData, LaneId, Message, MessageKey, MessageNonce, MessagePayload, + OutboundLaneData, VerificationError, +}; +use bp_runtime::{ + HashOf, HasherOf, RangeInclusiveExt, RawStorageProof, StorageProofChecker, StorageProofError, +}; +use codec::Decode; +use sp_std::vec::Vec; + +/// 'Parsed' message delivery proof - inbound lane id and its state. +pub(crate) type ParsedMessagesDeliveryProofFromBridgedChain = + (LaneId, InboundLaneData<::AccountId>); + +/// Verify proof of Bridged -> This chain messages. +/// +/// This function is used when Bridged chain is directly using GRANDPA finality. For Bridged +/// parachains, please use the `verify_messages_proof_from_parachain`. +/// +/// The `messages_count` argument verification (sane limits) is supposed to be made +/// outside of this function. This function only verifies that the proof declares exactly +/// `messages_count` messages. +pub fn verify_messages_proof, I: 'static>( + proof: FromBridgedChainMessagesProof>>, + messages_count: u32, +) -> Result, VerificationError> { + let FromBridgedChainMessagesProof { + bridged_header_hash, + storage_proof, + lane, + nonces_start, + nonces_end, + } = proof; + let mut parser: MessagesStorageProofAdapter = + MessagesStorageProofAdapter::try_new_with_verified_storage_proof( + bridged_header_hash, + storage_proof, + ) + .map_err(VerificationError::HeaderChain)?; + let nonces_range = nonces_start..=nonces_end; + + // receiving proofs where end < begin is ok (if proof includes outbound lane state) + let messages_in_the_proof = nonces_range.checked_len().unwrap_or(0); + if messages_in_the_proof != MessageNonce::from(messages_count) { + return Err(VerificationError::MessagesCountMismatch) + } + + // Read messages first. All messages that are claimed to be in the proof must + // be in the proof. So any error in `read_value`, or even missing value is fatal. + // + // Mind that we allow proofs with no messages if outbound lane state is proved. + let mut messages = Vec::with_capacity(messages_in_the_proof as _); + for nonce in nonces_range { + let message_key = MessageKey { lane_id: lane, nonce }; + let message_payload = parser + .read_and_decode_message_payload(&message_key) + .map_err(VerificationError::MessageStorage)?; + messages.push(Message { key: message_key, payload: message_payload }); + } + + // Now let's check if proof contains outbound lane state proof. It is optional, so + // we simply ignore `read_value` errors and missing value. + let proved_lane_messages = ProvedLaneMessages { + lane_state: parser + .read_and_decode_outbound_lane_data(&lane) + .map_err(VerificationError::OutboundLaneStorage)?, + messages, + }; + + // Now we may actually check if the proof is empty or not. + if proved_lane_messages.lane_state.is_none() && proved_lane_messages.messages.is_empty() { + return Err(VerificationError::EmptyMessageProof) + } + + // Check that the storage proof doesn't have any untouched keys. + parser.ensure_no_unused_keys().map_err(VerificationError::StorageProof)?; + + // We only support single lane messages in this generated_schema + let mut proved_messages = ProvedMessages::new(); + proved_messages.insert(lane, proved_lane_messages); + + Ok(proved_messages) +} + +/// Verify proof of This -> Bridged chain messages delivery. +pub fn verify_messages_delivery_proof, I: 'static>( + proof: FromBridgedChainMessagesDeliveryProof>>, +) -> Result, VerificationError> { + let FromBridgedChainMessagesDeliveryProof { bridged_header_hash, storage_proof, lane } = proof; + let mut parser: MessagesStorageProofAdapter = + MessagesStorageProofAdapter::try_new_with_verified_storage_proof( + bridged_header_hash, + storage_proof, + ) + .map_err(VerificationError::HeaderChain)?; + // Messages delivery proof is just proof of single storage key read => any error + // is fatal. + let storage_inbound_lane_data_key = bp_messages::storage_keys::inbound_lane_data_key( + T::ThisChain::WITH_CHAIN_MESSAGES_PALLET_NAME, + &lane, + ); + let inbound_lane_data = parser + .read_and_decode_mandatory_value(&storage_inbound_lane_data_key) + .map_err(VerificationError::InboundLaneStorage)?; + + // check that the storage proof doesn't have any untouched trie nodes + parser.ensure_no_unused_keys().map_err(VerificationError::StorageProof)?; + + Ok((lane, inbound_lane_data)) +} + +/// Abstraction over storage proof manipulation, hiding implementation details of actual storage +/// proofs. +trait StorageProofAdapter, I: 'static> { + fn read_and_decode_mandatory_value( + &mut self, + key: &impl AsRef<[u8]>, + ) -> Result; + fn read_and_decode_optional_value( + &mut self, + key: &impl AsRef<[u8]>, + ) -> Result, StorageProofError>; + fn ensure_no_unused_keys(self) -> Result<(), StorageProofError>; + + fn read_and_decode_outbound_lane_data( + &mut self, + lane_id: &LaneId, + ) -> Result, StorageProofError> { + let storage_outbound_lane_data_key = bp_messages::storage_keys::outbound_lane_data_key( + T::ThisChain::WITH_CHAIN_MESSAGES_PALLET_NAME, + lane_id, + ); + self.read_and_decode_optional_value(&storage_outbound_lane_data_key) + } + + fn read_and_decode_message_payload( + &mut self, + message_key: &MessageKey, + ) -> Result { + let storage_message_key = bp_messages::storage_keys::message_key( + T::ThisChain::WITH_CHAIN_MESSAGES_PALLET_NAME, + &message_key.lane_id, + message_key.nonce, + ); + self.read_and_decode_mandatory_value(&storage_message_key) + } +} + +/// Actual storage proof adapter for messages proofs. +type MessagesStorageProofAdapter = StorageProofCheckerAdapter; + +/// A `StorageProofAdapter` implementation for raw storage proofs. +struct StorageProofCheckerAdapter, I: 'static> { + storage: StorageProofChecker>>, + _dummy: sp_std::marker::PhantomData<(T, I)>, +} + +impl, I: 'static> StorageProofCheckerAdapter { + fn try_new_with_verified_storage_proof( + bridged_header_hash: HashOf>, + storage_proof: RawStorageProof, + ) -> Result { + BridgedHeaderChainOf::::verify_storage_proof(bridged_header_hash, storage_proof).map( + |storage| StorageProofCheckerAdapter:: { storage, _dummy: Default::default() }, + ) + } +} + +impl, I: 'static> StorageProofAdapter for StorageProofCheckerAdapter { + fn read_and_decode_optional_value( + &mut self, + key: &impl AsRef<[u8]>, + ) -> Result, StorageProofError> { + self.storage.read_and_decode_opt_value(key.as_ref()) + } + + fn read_and_decode_mandatory_value( + &mut self, + key: &impl AsRef<[u8]>, + ) -> Result { + self.storage.read_and_decode_mandatory_value(key.as_ref()) + } + + fn ensure_no_unused_keys(self) -> Result<(), StorageProofError> { + self.storage.ensure_no_unused_nodes() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::tests::{ + messages_generation::{ + encode_all_messages, encode_lane_data, generate_dummy_message, + prepare_messages_storage_proof, + }, + mock::*, + }; + + use bp_header_chain::StoredHeaderDataBuilder; + use bp_runtime::{HeaderId, StorageProofError}; + use codec::Encode; + use sp_runtime::traits::Header; + + fn using_messages_proof( + nonces_end: MessageNonce, + outbound_lane_data: Option, + encode_message: impl Fn(MessageNonce, &MessagePayload) -> Option>, + encode_outbound_lane_data: impl Fn(&OutboundLaneData) -> Vec, + add_duplicate_key: bool, + add_unused_key: bool, + test: impl Fn(FromBridgedChainMessagesProof) -> R, + ) -> R { + let (state_root, storage_proof) = prepare_messages_storage_proof::( + TEST_LANE_ID, + 1..=nonces_end, + outbound_lane_data, + bp_runtime::UnverifiedStorageProofParams::default(), + generate_dummy_message, + encode_message, + encode_outbound_lane_data, + add_duplicate_key, + add_unused_key, + ); + + sp_io::TestExternalities::new(Default::default()).execute_with(move || { + let bridged_header = BridgedChainHeader::new( + 0, + Default::default(), + state_root, + Default::default(), + Default::default(), + ); + let bridged_header_hash = bridged_header.hash(); + + pallet_bridge_grandpa::BestFinalized::::put(HeaderId( + 0, + bridged_header_hash, + )); + pallet_bridge_grandpa::ImportedHeaders::::insert( + bridged_header_hash, + bridged_header.build(), + ); + test(FromBridgedChainMessagesProof { + bridged_header_hash, + storage_proof, + lane: TEST_LANE_ID, + nonces_start: 1, + nonces_end, + }) + }) + } + + #[test] + fn messages_proof_is_rejected_if_declared_less_than_actual_number_of_messages() { + assert_eq!( + using_messages_proof( + 10, + None, + encode_all_messages, + encode_lane_data, + false, + false, + |proof| { verify_messages_proof::(proof, 5) } + ), + Err(VerificationError::MessagesCountMismatch), + ); + } + + #[test] + fn messages_proof_is_rejected_if_declared_more_than_actual_number_of_messages() { + assert_eq!( + using_messages_proof( + 10, + None, + encode_all_messages, + encode_lane_data, + false, + false, + |proof| { verify_messages_proof::(proof, 15) } + ), + Err(VerificationError::MessagesCountMismatch), + ); + } + + #[test] + fn message_proof_is_rejected_if_header_is_missing_from_the_chain() { + assert_eq!( + using_messages_proof( + 10, + None, + encode_all_messages, + encode_lane_data, + false, + false, + |proof| { + let bridged_header_hash = + pallet_bridge_grandpa::BestFinalized::::get().unwrap().1; + pallet_bridge_grandpa::ImportedHeaders::::remove( + bridged_header_hash, + ); + verify_messages_proof::(proof, 10) + } + ), + Err(VerificationError::HeaderChain(HeaderChainError::UnknownHeader)), + ); + } + + #[test] + fn message_proof_is_rejected_if_header_state_root_mismatches() { + assert_eq!( + using_messages_proof( + 10, + None, + encode_all_messages, + encode_lane_data, + false, + false, + |proof| { + let bridged_header_hash = + pallet_bridge_grandpa::BestFinalized::::get().unwrap().1; + pallet_bridge_grandpa::ImportedHeaders::::insert( + bridged_header_hash, + BridgedChainHeader::new( + 0, + Default::default(), + Default::default(), + Default::default(), + Default::default(), + ) + .build(), + ); + verify_messages_proof::(proof, 10) + } + ), + Err(VerificationError::HeaderChain(HeaderChainError::StorageProof( + StorageProofError::StorageRootMismatch + ))), + ); + } + + #[test] + fn message_proof_is_rejected_if_it_has_duplicate_trie_nodes() { + assert_eq!( + using_messages_proof( + 10, + None, + encode_all_messages, + encode_lane_data, + true, + false, + |proof| { verify_messages_proof::(proof, 10) }, + ), + Err(VerificationError::HeaderChain(HeaderChainError::StorageProof( + StorageProofError::DuplicateNodes + ))), + ); + } + + #[test] + fn message_proof_is_rejected_if_it_has_unused_trie_nodes() { + assert_eq!( + using_messages_proof( + 10, + None, + encode_all_messages, + encode_lane_data, + false, + true, + |proof| { verify_messages_proof::(proof, 10) }, + ), + Err(VerificationError::StorageProof(StorageProofError::UnusedKey)), + ); + } + + #[test] + fn message_proof_is_rejected_if_required_message_is_missing() { + matches!( + using_messages_proof( + 10, + None, + |n, m| if n != 5 { Some(m.encode()) } else { None }, + encode_lane_data, + false, + false, + |proof| verify_messages_proof::(proof, 10) + ), + Err(VerificationError::MessageStorage(StorageProofError::EmptyVal)), + ); + } + + #[test] + fn message_proof_is_rejected_if_message_decode_fails() { + matches!( + using_messages_proof( + 10, + None, + |n, m| { + let mut m = m.encode(); + if n == 5 { + m = vec![42] + } + Some(m) + }, + encode_lane_data, + false, + false, + |proof| verify_messages_proof::(proof, 10), + ), + Err(VerificationError::MessageStorage(StorageProofError::DecodeError)), + ); + } + + #[test] + fn message_proof_is_rejected_if_outbound_lane_state_decode_fails() { + matches!( + using_messages_proof( + 10, + Some(OutboundLaneData { + oldest_unpruned_nonce: 1, + latest_received_nonce: 1, + latest_generated_nonce: 1, + }), + encode_all_messages, + |d| { + let mut d = d.encode(); + d.truncate(1); + d + }, + false, + false, + |proof| verify_messages_proof::(proof, 10), + ), + Err(VerificationError::OutboundLaneStorage(StorageProofError::DecodeError)), + ); + } + + #[test] + fn message_proof_is_rejected_if_it_is_empty() { + assert_eq!( + using_messages_proof( + 0, + None, + encode_all_messages, + encode_lane_data, + false, + false, + |proof| { verify_messages_proof::(proof, 0) }, + ), + Err(VerificationError::EmptyMessageProof), + ); + } + + #[test] + fn non_empty_message_proof_without_messages_is_accepted() { + assert_eq!( + using_messages_proof( + 0, + Some(OutboundLaneData { + oldest_unpruned_nonce: 1, + latest_received_nonce: 1, + latest_generated_nonce: 1, + }), + encode_all_messages, + encode_lane_data, + false, + false, + |proof| verify_messages_proof::(proof, 0), + ), + Ok(vec![( + TEST_LANE_ID, + ProvedLaneMessages { + lane_state: Some(OutboundLaneData { + oldest_unpruned_nonce: 1, + latest_received_nonce: 1, + latest_generated_nonce: 1, + }), + messages: Vec::new(), + }, + )] + .into_iter() + .collect()), + ); + } + + #[test] + fn non_empty_message_proof_is_accepted() { + assert_eq!( + using_messages_proof( + 1, + Some(OutboundLaneData { + oldest_unpruned_nonce: 1, + latest_received_nonce: 1, + latest_generated_nonce: 1, + }), + encode_all_messages, + encode_lane_data, + false, + false, + |proof| verify_messages_proof::(proof, 1), + ), + Ok(vec![( + TEST_LANE_ID, + ProvedLaneMessages { + lane_state: Some(OutboundLaneData { + oldest_unpruned_nonce: 1, + latest_received_nonce: 1, + latest_generated_nonce: 1, + }), + messages: vec![Message { + key: MessageKey { lane_id: TEST_LANE_ID, nonce: 1 }, + payload: vec![42], + }], + }, + )] + .into_iter() + .collect()), + ); + } + + #[test] + fn verify_messages_proof_does_not_panic_if_messages_count_mismatches() { + assert_eq!( + using_messages_proof( + 1, + None, + encode_all_messages, + encode_lane_data, + false, + false, + |mut proof| { + proof.nonces_end = u64::MAX; + verify_messages_proof::(proof, u32::MAX) + }, + ), + Err(VerificationError::MessagesCountMismatch), + ); + } +} diff --git a/bridges/bin/runtime-common/src/messages_generation.rs b/bridges/modules/messages/src/tests/messages_generation.rs similarity index 62% rename from bridges/bin/runtime-common/src/messages_generation.rs rename to bridges/modules/messages/src/tests/messages_generation.rs index c37aaa5d4d5378a1b76507e017c73aec3c7aabbd..6c4867fa6de39fa97b35cbd1f270bdeff4c76dff 100644 --- a/bridges/bin/runtime-common/src/messages_generation.rs +++ b/bridges/modules/messages/src/tests/messages_generation.rs @@ -16,17 +16,23 @@ //! Helpers for generating message storage proofs, that are used by tests and by benchmarks. -use crate::messages::{AccountIdOf, BridgedChain, HashOf, HasherOf, MessageBridge, ThisChain}; - use bp_messages::{ - storage_keys, InboundLaneData, LaneId, MessageKey, MessageNonce, MessagePayload, - OutboundLaneData, + storage_keys, ChainWithMessages, InboundLaneData, LaneId, MessageKey, MessageNonce, + MessagePayload, OutboundLaneData, +}; +use bp_runtime::{ + grow_storage_value, record_all_trie_keys, AccountIdOf, Chain, HashOf, HasherOf, + RawStorageProof, UnverifiedStorageProofParams, }; -use bp_runtime::{record_all_trie_keys, RawStorageProof, StorageProofSize}; use codec::Encode; use sp_std::{ops::RangeInclusive, prelude::*}; use sp_trie::{trie_types::TrieDBMutBuilderV1, LayoutV1, MemoryDB, TrieMut}; +/// Dummy message generation function. +pub fn generate_dummy_message(_: MessageNonce) -> MessagePayload { + vec![42] +} + /// Simple and correct message data encode function. pub fn encode_all_messages(_: MessageNonce, m: &MessagePayload) -> Option> { Some(m.encode()) @@ -40,18 +46,20 @@ pub fn encode_lane_data(d: &OutboundLaneData) -> Vec { /// Prepare storage proof of given messages. /// /// Returns state trie root and nodes with prepared messages. -pub fn prepare_messages_storage_proof( +#[allow(clippy::too_many_arguments)] +pub fn prepare_messages_storage_proof( lane: LaneId, message_nonces: RangeInclusive, outbound_lane_data: Option, - size: StorageProofSize, - message_payload: MessagePayload, + proof_params: UnverifiedStorageProofParams, + generate_message: impl Fn(MessageNonce) -> MessagePayload, encode_message: impl Fn(MessageNonce, &MessagePayload) -> Option>, encode_outbound_lane_data: impl Fn(&OutboundLaneData) -> Vec, -) -> (HashOf>, RawStorageProof) + add_duplicate_key: bool, + add_unused_key: bool, +) -> (HashOf, RawStorageProof) where - B: MessageBridge, - HashOf>: Copy + Default, + HashOf: Copy + Default, { // prepare Bridged chain storage with messages and (optionally) outbound lane state let message_count = message_nonces.end().saturating_sub(*message_nonces.start()) + 1; @@ -60,22 +68,22 @@ where let mut mdb = MemoryDB::default(); { let mut trie = - TrieDBMutBuilderV1::>>::new(&mut mdb, &mut root).build(); + TrieDBMutBuilderV1::>::new(&mut mdb, &mut root).build(); // insert messages for (i, nonce) in message_nonces.into_iter().enumerate() { let message_key = MessageKey { lane_id: lane, nonce }; - let message_payload = match encode_message(nonce, &message_payload) { + let message_payload = match encode_message(nonce, &generate_message(nonce)) { Some(message_payload) => if i == 0 { - grow_trie_leaf_value(message_payload, size) + grow_storage_value(message_payload, &proof_params) } else { message_payload }, None => continue, }; let storage_key = storage_keys::message_key( - B::BRIDGED_MESSAGES_PALLET_NAME, + ThisChain::WITH_CHAIN_MESSAGES_PALLET_NAME, &message_key.lane_id, message_key.nonce, ) @@ -89,8 +97,11 @@ where // insert outbound lane state if let Some(outbound_lane_data) = outbound_lane_data.as_ref().map(encode_outbound_lane_data) { - let storage_key = - storage_keys::outbound_lane_data_key(B::BRIDGED_MESSAGES_PALLET_NAME, &lane).0; + let storage_key = storage_keys::outbound_lane_data_key( + ThisChain::WITH_CHAIN_MESSAGES_PALLET_NAME, + &lane, + ) + .0; trie.insert(&storage_key, &outbound_lane_data) .map_err(|_| "TrieMut::insert has failed") .expect("TrieMut::insert should not fail in benchmarks"); @@ -99,52 +110,54 @@ where } // generate storage proof to be delivered to This chain - let storage_proof = record_all_trie_keys::>>, _>(&mdb, &root) - .map_err(|_| "record_all_trie_keys has failed") - .expect("record_all_trie_keys should not fail in benchmarks"); + let mut storage_proof = + record_all_trie_keys::>, _>(&mdb, &root) + .map_err(|_| "record_all_trie_keys has failed") + .expect("record_all_trie_keys should not fail in benchmarks"); + + if add_duplicate_key { + assert!(!storage_proof.is_empty()); + let node = storage_proof.pop().unwrap(); + storage_proof.push(node.clone()); + storage_proof.push(node); + } + + if add_unused_key { + storage_proof.push(b"unused_value".to_vec()); + } + (root, storage_proof) } /// Prepare storage proof of given messages delivery. /// /// Returns state trie root and nodes with prepared messages. -pub fn prepare_message_delivery_storage_proof( +pub fn prepare_message_delivery_storage_proof( lane: LaneId, - inbound_lane_data: InboundLaneData>>, - size: StorageProofSize, -) -> (HashOf>, RawStorageProof) + inbound_lane_data: InboundLaneData>, + proof_params: UnverifiedStorageProofParams, +) -> (HashOf, RawStorageProof) where - B: MessageBridge, + HashOf: Copy + Default, { // prepare Bridged chain storage with inbound lane state - let storage_key = storage_keys::inbound_lane_data_key(B::BRIDGED_MESSAGES_PALLET_NAME, &lane).0; + let storage_key = + storage_keys::inbound_lane_data_key(ThisChain::WITH_CHAIN_MESSAGES_PALLET_NAME, &lane).0; let mut root = Default::default(); let mut mdb = MemoryDB::default(); { let mut trie = - TrieDBMutBuilderV1::>>::new(&mut mdb, &mut root).build(); - let inbound_lane_data = grow_trie_leaf_value(inbound_lane_data.encode(), size); + TrieDBMutBuilderV1::>::new(&mut mdb, &mut root).build(); + let inbound_lane_data = grow_storage_value(inbound_lane_data.encode(), &proof_params); trie.insert(&storage_key, &inbound_lane_data) .map_err(|_| "TrieMut::insert has failed") .expect("TrieMut::insert should not fail in benchmarks"); } // generate storage proof to be delivered to This chain - let storage_proof = record_all_trie_keys::>>, _>(&mdb, &root) + let storage_proof = record_all_trie_keys::>, _>(&mdb, &root) .map_err(|_| "record_all_trie_keys has failed") .expect("record_all_trie_keys should not fail in benchmarks"); (root, storage_proof) } - -/// Add extra data to the trie leaf value so that it'll be of given size. -pub fn grow_trie_leaf_value(mut value: Vec, size: StorageProofSize) -> Vec { - match size { - StorageProofSize::Minimal(_) => (), - StorageProofSize::HasLargeLeaf(size) if size as usize > value.len() => { - value.extend(sp_std::iter::repeat(42u8).take(size as usize - value.len())); - }, - StorageProofSize::HasLargeLeaf(_) => (), - } - value -} diff --git a/bridges/modules/messages/src/mock.rs b/bridges/modules/messages/src/tests/mock.rs similarity index 62% rename from bridges/modules/messages/src/mock.rs rename to bridges/modules/messages/src/tests/mock.rs index 3a1e0063d5337769b75b35035116aaff6e2b2e08..ffdd536830b5f7dde6671c75ba1ac108d7d218e4 100644 --- a/bridges/modules/messages/src/mock.rs +++ b/bridges/modules/messages/src/tests/mock.rs @@ -17,30 +17,43 @@ // From construct_runtime macro #![allow(clippy::from_over_into)] -use crate::{Config, StoredMessagePayload}; +use crate::{ + tests::messages_generation::{ + encode_all_messages, encode_lane_data, prepare_message_delivery_storage_proof, + prepare_messages_storage_proof, + }, + Config, StoredMessagePayload, +}; +use bp_header_chain::{ChainWithGrandpa, StoredHeaderData}; use bp_messages::{ calc_relayers_rewards, - source_chain::{DeliveryConfirmationPayments, OnMessagesDelivered, TargetHeaderChain}, + source_chain::{ + DeliveryConfirmationPayments, FromBridgedChainMessagesDeliveryProof, OnMessagesDelivered, + }, target_chain::{ - DeliveryPayments, DispatchMessage, DispatchMessageData, MessageDispatch, - ProvedLaneMessages, ProvedMessages, SourceHeaderChain, + DeliveryPayments, DispatchMessage, DispatchMessageData, FromBridgedChainMessagesProof, + MessageDispatch, }, - DeliveredMessages, InboundLaneData, LaneId, Message, MessageKey, MessageNonce, - UnrewardedRelayer, UnrewardedRelayersState, VerificationError, + ChainWithMessages, DeliveredMessages, InboundLaneData, LaneId, Message, MessageKey, + MessageNonce, OutboundLaneData, UnrewardedRelayer, UnrewardedRelayersState, +}; +use bp_runtime::{ + messages::MessageDispatchResult, Chain, ChainId, Size, UnverifiedStorageProofParams, }; -use bp_runtime::{messages::MessageDispatchResult, Size}; use codec::{Decode, Encode}; use frame_support::{ derive_impl, parameter_types, weights::{constants::RocksDbWeight, Weight}, }; use scale_info::TypeInfo; -use sp_runtime::BuildStorage; -use std::{ - collections::{BTreeMap, VecDeque}, - ops::RangeInclusive, +use sp_core::H256; +use sp_runtime::{ + testing::Header as SubstrateHeader, + traits::{BlakeTwo256, ConstU32}, + BuildStorage, StateVersion, }; +use std::{collections::VecDeque, ops::RangeInclusive}; pub type AccountId = u64; pub type Balance = u64; @@ -62,6 +75,77 @@ pub type TestMessageFee = u64; pub type TestRelayer = u64; pub type TestDispatchLevelResult = (); +pub struct ThisChain; + +impl Chain for ThisChain { + const ID: ChainId = *b"ttch"; + + type BlockNumber = u64; + type Hash = H256; + type Hasher = BlakeTwo256; + type Header = SubstrateHeader; + type AccountId = AccountId; + type Balance = Balance; + type Nonce = u64; + type Signature = sp_runtime::MultiSignature; + const STATE_VERSION: StateVersion = StateVersion::V1; + + fn max_extrinsic_size() -> u32 { + u32::MAX + } + + fn max_extrinsic_weight() -> Weight { + Weight::MAX + } +} + +impl ChainWithMessages for ThisChain { + const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str = "WithThisChainBridgeMessages"; + const MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX: MessageNonce = 16; + const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce = 128; +} + +pub struct BridgedChain; + +pub type BridgedHeaderHash = H256; +pub type BridgedChainHeader = SubstrateHeader; + +impl Chain for BridgedChain { + const ID: ChainId = *b"tbch"; + + type BlockNumber = u64; + type Hash = BridgedHeaderHash; + type Hasher = BlakeTwo256; + type Header = BridgedChainHeader; + type AccountId = TestRelayer; + type Balance = Balance; + type Nonce = u64; + type Signature = sp_runtime::MultiSignature; + const STATE_VERSION: StateVersion = StateVersion::V1; + + fn max_extrinsic_size() -> u32 { + 4096 + } + + fn max_extrinsic_weight() -> Weight { + Weight::MAX + } +} + +impl ChainWithGrandpa for BridgedChain { + const WITH_CHAIN_GRANDPA_PALLET_NAME: &'static str = "WithBridgedChainBridgeGrandpa"; + const MAX_AUTHORITIES_COUNT: u32 = 16; + const REASONABLE_HEADERS_IN_JUSTIFICATION_ANCESTRY: u32 = 4; + const MAX_MANDATORY_HEADER_SIZE: u32 = 4096; + const AVERAGE_HEADER_SIZE: u32 = 4096; +} + +impl ChainWithMessages for BridgedChain { + const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str = "WithBridgedChainBridgeMessages"; + const MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX: MessageNonce = 16; + const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce = 128; +} + type Block = frame_system::mocking::MockBlock; use crate as pallet_bridge_messages; @@ -71,6 +155,7 @@ frame_support::construct_runtime! { { System: frame_system::{Pallet, Call, Config, Storage, Event}, Balances: pallet_balances::{Pallet, Call, Event}, + BridgedChainGrandpa: pallet_bridge_grandpa::{Pallet, Call, Event}, Messages: pallet_bridge_messages::{Pallet, Call, Event}, } } @@ -89,10 +174,17 @@ impl pallet_balances::Config for TestRuntime { type AccountStore = System; } +impl pallet_bridge_grandpa::Config for TestRuntime { + type RuntimeEvent = RuntimeEvent; + type BridgedChain = BridgedChain; + type MaxFreeHeadersPerBlock = ConstU32<4>; + type FreeHeadersInterval = ConstU32<1_024>; + type HeadersToKeep = ConstU32<8>; + type WeightInfo = pallet_bridge_grandpa::weights::BridgeWeight; +} + parameter_types! { pub const MaxMessagesToPruneAtOnce: u64 = 10; - pub const MaxUnrewardedRelayerEntriesAtInboundLane: u64 = 16; - pub const MaxUnconfirmedMessagesAtInboundLane: u64 = 128; pub const TestBridgedChainId: bp_runtime::ChainId = *b"test"; pub const ActiveOutboundLanes: &'static [LaneId] = &[TEST_LANE_ID, TEST_LANE_ID_2]; } @@ -103,24 +195,22 @@ pub type TestWeightInfo = (); impl Config for TestRuntime { type RuntimeEvent = RuntimeEvent; type WeightInfo = TestWeightInfo; + + type ThisChain = ThisChain; + type BridgedChain = BridgedChain; + type BridgedHeaderChain = BridgedChainGrandpa; + type ActiveOutboundLanes = ActiveOutboundLanes; - type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane; - type MaxUnconfirmedMessagesAtInboundLane = MaxUnconfirmedMessagesAtInboundLane; - type MaximalOutboundPayloadSize = frame_support::traits::ConstU32; type OutboundPayload = TestPayload; type InboundPayload = TestPayload; - type InboundRelayer = TestRelayer; type DeliveryPayments = TestDeliveryPayments; - type TargetHeaderChain = TestTargetHeaderChain; type DeliveryConfirmationPayments = TestDeliveryConfirmationPayments; type OnMessagesDelivered = TestOnMessagesDelivered; - type SourceHeaderChain = TestSourceHeaderChain; type MessageDispatch = TestMessageDispatch; - type BridgedChainId = TestBridgedChainId; } #[cfg(feature = "runtime-benchmarks")] @@ -131,29 +221,26 @@ impl crate::benchmarking::Config<()> for TestRuntime { fn prepare_message_proof( params: crate::benchmarking::MessageProofParams, - ) -> (TestMessagesProof, Weight) { - // in mock run we only care about benchmarks correctness, not the benchmark results - // => ignore size related arguments - let (messages, total_dispatch_weight) = - params.message_nonces.into_iter().map(|n| message(n, REGULAR_PAYLOAD)).fold( - (Vec::new(), Weight::zero()), - |(mut messages, total_dispatch_weight), message| { - let weight = REGULAR_PAYLOAD.declared_weight; - messages.push(message); - (messages, total_dispatch_weight.saturating_add(weight)) - }, - ); - let mut proof: TestMessagesProof = Ok(messages).into(); - proof.result.as_mut().unwrap().get_mut(0).unwrap().1.lane_state = params.outbound_lane_data; - (proof, total_dispatch_weight) + ) -> (FromBridgedChainMessagesProof, Weight) { + use bp_runtime::RangeInclusiveExt; + + let dispatch_weight = + REGULAR_PAYLOAD.declared_weight * params.message_nonces.checked_len().unwrap_or(0); + ( + *prepare_messages_proof( + params.message_nonces.into_iter().map(|n| message(n, REGULAR_PAYLOAD)).collect(), + params.outbound_lane_data, + ), + dispatch_weight, + ) } fn prepare_message_delivery_proof( params: crate::benchmarking::MessageDeliveryProofParams, - ) -> TestMessagesDeliveryProof { + ) -> FromBridgedChainMessagesDeliveryProof { // in mock run we only care about benchmarks correctness, not the benchmark results // => ignore size related arguments - TestMessagesDeliveryProof(Ok((params.lane, params.inbound_lane_data))) + prepare_messages_delivery_proof(params.lane, params.inbound_lane_data) } fn is_relayer_rewarded(_relayer: &AccountId) -> bool { @@ -167,9 +254,6 @@ impl Size for TestPayload { } } -/// Maximal outbound payload size. -pub const MAX_OUTBOUND_PAYLOAD_SIZE: u32 = 4096; - /// Account that has balance to use in tests. pub const ENDOWED_ACCOUNT: AccountId = 0xDEAD; @@ -182,9 +266,6 @@ pub const TEST_RELAYER_B: AccountId = 101; /// Account id of additional test relayer - C. pub const TEST_RELAYER_C: AccountId = 102; -/// Error that is returned by all test implementations. -pub const TEST_ERROR: &str = "Test error"; - /// Lane that we're using in tests. pub const TEST_LANE_ID: LaneId = LaneId([0, 0, 0, 1]); @@ -197,71 +278,6 @@ pub const TEST_LANE_ID_3: LaneId = LaneId([0, 0, 0, 3]); /// Regular message payload. pub const REGULAR_PAYLOAD: TestPayload = message_payload(0, 50); -/// Payload that is rejected by `TestTargetHeaderChain`. -pub const PAYLOAD_REJECTED_BY_TARGET_CHAIN: TestPayload = message_payload(1, 50); - -/// Vec of proved messages, grouped by lane. -pub type MessagesByLaneVec = Vec<(LaneId, ProvedLaneMessages)>; - -/// Test messages proof. -#[derive(Debug, Encode, Decode, Clone, PartialEq, Eq, TypeInfo)] -pub struct TestMessagesProof { - pub result: Result, -} - -impl Size for TestMessagesProof { - fn size(&self) -> u32 { - 0 - } -} - -impl From, ()>> for TestMessagesProof { - fn from(result: Result, ()>) -> Self { - Self { - result: result.map(|messages| { - let mut messages_by_lane: BTreeMap> = - BTreeMap::new(); - for message in messages { - messages_by_lane.entry(message.key.lane_id).or_default().messages.push(message); - } - messages_by_lane.into_iter().collect() - }), - } - } -} - -/// Messages delivery proof used in tests. -#[derive(Debug, Encode, Decode, Eq, Clone, PartialEq, TypeInfo)] -pub struct TestMessagesDeliveryProof(pub Result<(LaneId, InboundLaneData), ()>); - -impl Size for TestMessagesDeliveryProof { - fn size(&self) -> u32 { - 0 - } -} - -/// Target header chain that is used in tests. -#[derive(Debug, Default)] -pub struct TestTargetHeaderChain; - -impl TargetHeaderChain for TestTargetHeaderChain { - type MessagesDeliveryProof = TestMessagesDeliveryProof; - - fn verify_message(payload: &TestPayload) -> Result<(), VerificationError> { - if *payload == PAYLOAD_REJECTED_BY_TARGET_CHAIN { - Err(VerificationError::Other(TEST_ERROR)) - } else { - Ok(()) - } - } - - fn verify_messages_delivery_proof( - proof: Self::MessagesDeliveryProof, - ) -> Result<(LaneId, InboundLaneData), VerificationError> { - proof.0.map_err(|_| VerificationError::Other(TEST_ERROR)) - } -} - /// Reward payments at the target chain during delivery transaction. #[derive(Debug, Default)] pub struct TestDeliveryPayments; @@ -322,24 +338,6 @@ impl DeliveryConfirmationPayments for TestDeliveryConfirmationPayment } } -/// Source header chain that is used in tests. -#[derive(Debug)] -pub struct TestSourceHeaderChain; - -impl SourceHeaderChain for TestSourceHeaderChain { - type MessagesProof = TestMessagesProof; - - fn verify_messages_proof( - proof: Self::MessagesProof, - _messages_count: u32, - ) -> Result, VerificationError> { - proof - .result - .map(|proof| proof.into_iter().collect()) - .map_err(|_| VerificationError::Other(TEST_ERROR)) - } -} - /// Test message dispatcher. #[derive(Debug)] pub struct TestMessageDispatch; @@ -458,3 +456,75 @@ pub fn new_test_ext() -> sp_io::TestExternalities { pub fn run_test(test: impl FnOnce() -> T) -> T { new_test_ext().execute_with(test) } + +/// Prepare valid storage proof for given messages and insert appropriate header to the +/// bridged header chain. +/// +/// Since this function changes the runtime storage, you can't "inline" it in the +/// `asset_noop` macro calls. +pub fn prepare_messages_proof( + messages: Vec, + outbound_lane_data: Option, +) -> Box> { + // first - let's generate storage proof + let lane = messages.first().unwrap().key.lane_id; + let nonces_start = messages.first().unwrap().key.nonce; + let nonces_end = messages.last().unwrap().key.nonce; + let (storage_root, storage_proof) = prepare_messages_storage_proof::( + TEST_LANE_ID, + nonces_start..=nonces_end, + outbound_lane_data, + UnverifiedStorageProofParams::default(), + |nonce| messages[(nonce - nonces_start) as usize].payload.clone(), + encode_all_messages, + encode_lane_data, + false, + false, + ); + + // let's now insert bridged chain header into the storage + let bridged_header_hash = Default::default(); + pallet_bridge_grandpa::ImportedHeaders::::insert( + bridged_header_hash, + StoredHeaderData { number: 0, state_root: storage_root }, + ); + + Box::new(FromBridgedChainMessagesProof:: { + bridged_header_hash, + storage_proof, + lane, + nonces_start, + nonces_end, + }) +} + +/// Prepare valid storage proof for given messages and insert appropriate header to the +/// bridged header chain. +/// +/// Since this function changes the runtime storage, you can't "inline" it in the +/// `asset_noop` macro calls. +pub fn prepare_messages_delivery_proof( + lane: LaneId, + inbound_lane_data: InboundLaneData, +) -> FromBridgedChainMessagesDeliveryProof { + // first - let's generate storage proof + let (storage_root, storage_proof) = + prepare_message_delivery_storage_proof::( + lane, + inbound_lane_data, + UnverifiedStorageProofParams::default(), + ); + + // let's now insert bridged chain header into the storage + let bridged_header_hash = Default::default(); + pallet_bridge_grandpa::ImportedHeaders::::insert( + bridged_header_hash, + StoredHeaderData { number: 0, state_root: storage_root }, + ); + + FromBridgedChainMessagesDeliveryProof:: { + bridged_header_hash, + storage_proof, + lane, + } +} diff --git a/bridges/modules/messages/src/tests/mod.rs b/bridges/modules/messages/src/tests/mod.rs new file mode 100644 index 0000000000000000000000000000000000000000..c3bde5fc275849fab930ad0b1ec9f0b4e80ce4ea --- /dev/null +++ b/bridges/modules/messages/src/tests/mod.rs @@ -0,0 +1,26 @@ +// Copyright 2019-2021 Parity Technologies (UK) Ltd. +// This file is part of Parity Bridges Common. + +// Parity Bridges Common is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity Bridges Common is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity Bridges Common. If not, see . + +//! Tests and test helpers for messages pallet. + +#![cfg(any(feature = "test-helpers", test))] + +#[cfg(test)] +pub(crate) mod mock; +#[cfg(test)] +mod pallet_tests; + +pub mod messages_generation; diff --git a/bridges/modules/messages/src/tests/pallet_tests.rs b/bridges/modules/messages/src/tests/pallet_tests.rs new file mode 100644 index 0000000000000000000000000000000000000000..42e1042717de07656630855c00967361be78f664 --- /dev/null +++ b/bridges/modules/messages/src/tests/pallet_tests.rs @@ -0,0 +1,1100 @@ +// Copyright 2019-2021 Parity Technologies (UK) Ltd. +// This file is part of Parity Bridges Common. + +// Parity Bridges Common is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity Bridges Common is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity Bridges Common. If not, see . + +//! Pallet-level tests. + +use crate::{ + outbound_lane, + outbound_lane::ReceptionConfirmationError, + tests::mock::{self, RuntimeEvent as TestEvent, *}, + weights_ext::WeightInfoExt, + Call, Config, Error, Event, InboundLanes, MaybeOutboundLanesCount, OutboundLanes, + OutboundMessages, Pallet, PalletOperatingMode, PalletOwner, RuntimeInboundLaneStorage, + StoredInboundLaneData, +}; + +use bp_messages::{ + source_chain::{FromBridgedChainMessagesDeliveryProof, MessagesBridge}, + target_chain::FromBridgedChainMessagesProof, + BridgeMessagesCall, ChainWithMessages, DeliveredMessages, InboundLaneData, + InboundMessageDetails, LaneId, MessageKey, MessageNonce, MessagesOperatingMode, + OutboundLaneData, OutboundMessageDetails, UnrewardedRelayer, UnrewardedRelayersState, + VerificationError, +}; +use bp_runtime::{BasicOperatingMode, PreComputedSize, RangeInclusiveExt, Size}; +use bp_test_utils::generate_owned_bridge_module_tests; +use codec::Encode; +use frame_support::{ + assert_noop, assert_ok, + dispatch::Pays, + storage::generator::{StorageMap, StorageValue}, + traits::Hooks, + weights::Weight, +}; +use frame_system::{EventRecord, Pallet as System, Phase}; +use sp_core::Get; +use sp_runtime::DispatchError; + +fn get_ready_for_events() { + System::::set_block_number(1); + System::::reset_events(); +} + +fn send_regular_message(lane_id: LaneId) { + get_ready_for_events(); + + let outbound_lane = outbound_lane::(lane_id); + let message_nonce = outbound_lane.data().latest_generated_nonce + 1; + let prev_enqueued_messages = outbound_lane.data().queued_messages().saturating_len(); + let valid_message = Pallet::::validate_message(lane_id, ®ULAR_PAYLOAD) + .expect("validate_message has failed"); + let artifacts = Pallet::::send_message(valid_message); + assert_eq!(artifacts.enqueued_messages, prev_enqueued_messages + 1); + + // check event with assigned nonce + assert_eq!( + System::::events(), + vec![EventRecord { + phase: Phase::Initialization, + event: TestEvent::Messages(Event::MessageAccepted { lane_id, nonce: message_nonce }), + topics: vec![], + }], + ); +} + +fn receive_messages_delivery_proof() { + System::::set_block_number(1); + System::::reset_events(); + + assert_ok!(Pallet::::receive_messages_delivery_proof( + RuntimeOrigin::signed(1), + prepare_messages_delivery_proof( + TEST_LANE_ID, + InboundLaneData { + last_confirmed_nonce: 1, + relayers: vec![UnrewardedRelayer { + relayer: 0, + messages: DeliveredMessages::new(1), + }] + .into(), + }, + ), + UnrewardedRelayersState { + unrewarded_relayer_entries: 1, + messages_in_oldest_entry: 1, + total_messages: 1, + last_delivered_nonce: 1, + }, + )); + + assert_eq!( + System::::events(), + vec![EventRecord { + phase: Phase::Initialization, + event: TestEvent::Messages(Event::MessagesDelivered { + lane_id: TEST_LANE_ID, + messages: DeliveredMessages::new(1), + }), + topics: vec![], + }], + ); +} + +#[test] +fn pallet_rejects_transactions_if_halted() { + run_test(|| { + // send message first to be able to check that delivery_proof fails later + send_regular_message(TEST_LANE_ID); + + PalletOperatingMode::::put(MessagesOperatingMode::Basic( + BasicOperatingMode::Halted, + )); + + assert_noop!( + Pallet::::validate_message(TEST_LANE_ID, ®ULAR_PAYLOAD), + Error::::NotOperatingNormally, + ); + + let messages_proof = prepare_messages_proof(vec![message(2, REGULAR_PAYLOAD)], None); + assert_noop!( + Pallet::::receive_messages_proof( + RuntimeOrigin::signed(1), + TEST_RELAYER_A, + messages_proof, + 1, + REGULAR_PAYLOAD.declared_weight, + ), + Error::::BridgeModule(bp_runtime::OwnedBridgeModuleError::Halted), + ); + + let delivery_proof = prepare_messages_delivery_proof( + TEST_LANE_ID, + InboundLaneData { + last_confirmed_nonce: 1, + relayers: vec![unrewarded_relayer(1, 1, TEST_RELAYER_A)].into(), + }, + ); + assert_noop!( + Pallet::::receive_messages_delivery_proof( + RuntimeOrigin::signed(1), + delivery_proof, + UnrewardedRelayersState { + unrewarded_relayer_entries: 1, + messages_in_oldest_entry: 1, + total_messages: 1, + last_delivered_nonce: 1, + }, + ), + Error::::BridgeModule(bp_runtime::OwnedBridgeModuleError::Halted), + ); + }); +} + +#[test] +fn receive_messages_fails_if_dispatcher_is_inactive() { + run_test(|| { + TestMessageDispatch::deactivate(); + let proof = prepare_messages_proof(vec![message(1, REGULAR_PAYLOAD)], None); + assert_noop!( + Pallet::::receive_messages_proof( + RuntimeOrigin::signed(1), + TEST_RELAYER_A, + proof, + 1, + REGULAR_PAYLOAD.declared_weight, + ), + Error::::MessageDispatchInactive, + ); + }); +} + +#[test] +fn pallet_rejects_new_messages_in_rejecting_outbound_messages_operating_mode() { + run_test(|| { + // send message first to be able to check that delivery_proof fails later + send_regular_message(TEST_LANE_ID); + + PalletOperatingMode::::put( + MessagesOperatingMode::RejectingOutboundMessages, + ); + + assert_noop!( + Pallet::::validate_message(TEST_LANE_ID, ®ULAR_PAYLOAD), + Error::::NotOperatingNormally, + ); + + assert_ok!(Pallet::::receive_messages_proof( + RuntimeOrigin::signed(1), + TEST_RELAYER_A, + prepare_messages_proof(vec![message(1, REGULAR_PAYLOAD)], None), + 1, + REGULAR_PAYLOAD.declared_weight, + ),); + + assert_ok!(Pallet::::receive_messages_delivery_proof( + RuntimeOrigin::signed(1), + prepare_messages_delivery_proof( + TEST_LANE_ID, + InboundLaneData { + last_confirmed_nonce: 1, + relayers: vec![unrewarded_relayer(1, 1, TEST_RELAYER_A)].into(), + }, + ), + UnrewardedRelayersState { + unrewarded_relayer_entries: 1, + messages_in_oldest_entry: 1, + total_messages: 1, + last_delivered_nonce: 1, + }, + )); + }); +} + +#[test] +fn send_message_works() { + run_test(|| { + send_regular_message(TEST_LANE_ID); + }); +} + +#[test] +fn send_message_rejects_too_large_message() { + run_test(|| { + let mut message_payload = message_payload(1, 0); + // the payload isn't simply extra, so it'll definitely overflow + // `max_outbound_payload_size` if we add `max_outbound_payload_size` bytes to extra + let max_outbound_payload_size = BridgedChain::maximal_incoming_message_size(); + message_payload + .extra + .extend_from_slice(&vec![0u8; max_outbound_payload_size as usize]); + assert_noop!( + Pallet::::validate_message(TEST_LANE_ID, &message_payload.clone(),), + Error::::MessageRejectedByPallet(VerificationError::MessageTooLarge), + ); + + // let's check that we're able to send `max_outbound_payload_size` messages + while message_payload.encoded_size() as u32 > max_outbound_payload_size { + message_payload.extra.pop(); + } + assert_eq!(message_payload.encoded_size() as u32, max_outbound_payload_size); + + let valid_message = + Pallet::::validate_message(TEST_LANE_ID, &message_payload) + .expect("validate_message has failed"); + Pallet::::send_message(valid_message); + }) +} + +#[test] +fn receive_messages_proof_works() { + run_test(|| { + assert_ok!(Pallet::::receive_messages_proof( + RuntimeOrigin::signed(1), + TEST_RELAYER_A, + prepare_messages_proof(vec![message(1, REGULAR_PAYLOAD)], None), + 1, + REGULAR_PAYLOAD.declared_weight, + )); + + assert_eq!(InboundLanes::::get(TEST_LANE_ID).0.last_delivered_nonce(), 1); + + assert!(TestDeliveryPayments::is_reward_paid(1)); + }); +} + +#[test] +fn receive_messages_proof_updates_confirmed_message_nonce() { + run_test(|| { + // say we have received 10 messages && last confirmed message is 8 + InboundLanes::::insert( + TEST_LANE_ID, + InboundLaneData { + last_confirmed_nonce: 8, + relayers: vec![ + unrewarded_relayer(9, 9, TEST_RELAYER_A), + unrewarded_relayer(10, 10, TEST_RELAYER_B), + ] + .into(), + }, + ); + assert_eq!( + inbound_unrewarded_relayers_state(TEST_LANE_ID), + UnrewardedRelayersState { + unrewarded_relayer_entries: 2, + messages_in_oldest_entry: 1, + total_messages: 2, + last_delivered_nonce: 10, + }, + ); + + // message proof includes outbound lane state with latest confirmed message updated to 9 + assert_ok!(Pallet::::receive_messages_proof( + RuntimeOrigin::signed(1), + TEST_RELAYER_A, + prepare_messages_proof( + vec![message(11, REGULAR_PAYLOAD)], + Some(OutboundLaneData { latest_received_nonce: 9, ..Default::default() }), + ), + 1, + REGULAR_PAYLOAD.declared_weight, + )); + + assert_eq!( + InboundLanes::::get(TEST_LANE_ID).0, + InboundLaneData { + last_confirmed_nonce: 9, + relayers: vec![ + unrewarded_relayer(10, 10, TEST_RELAYER_B), + unrewarded_relayer(11, 11, TEST_RELAYER_A) + ] + .into(), + }, + ); + assert_eq!( + inbound_unrewarded_relayers_state(TEST_LANE_ID), + UnrewardedRelayersState { + unrewarded_relayer_entries: 2, + messages_in_oldest_entry: 1, + total_messages: 2, + last_delivered_nonce: 11, + }, + ); + }); +} + +#[test] +fn receive_messages_proof_does_not_accept_message_if_dispatch_weight_is_not_enough() { + run_test(|| { + let proof = prepare_messages_proof(vec![message(1, REGULAR_PAYLOAD)], None); + let mut declared_weight = REGULAR_PAYLOAD.declared_weight; + *declared_weight.ref_time_mut() -= 1; + + assert_noop!( + Pallet::::receive_messages_proof( + RuntimeOrigin::signed(1), + TEST_RELAYER_A, + proof, + 1, + declared_weight, + ), + Error::::InsufficientDispatchWeight + ); + assert_eq!(InboundLanes::::get(TEST_LANE_ID).last_delivered_nonce(), 0); + }); +} + +#[test] +fn receive_messages_proof_rejects_invalid_proof() { + run_test(|| { + let mut proof = prepare_messages_proof(vec![message(1, REGULAR_PAYLOAD)], None); + proof.nonces_end += 1; + + assert_noop!( + Pallet::::receive_messages_proof( + RuntimeOrigin::signed(1), + TEST_RELAYER_A, + proof, + 1, + Weight::zero(), + ), + Error::::InvalidMessagesProof, + ); + }); +} + +#[test] +fn receive_messages_proof_rejects_proof_with_too_many_messages() { + run_test(|| { + let proof = prepare_messages_proof(vec![message(1, REGULAR_PAYLOAD)], None); + assert_noop!( + Pallet::::receive_messages_proof( + RuntimeOrigin::signed(1), + TEST_RELAYER_A, + proof, + u32::MAX, + Weight::zero(), + ), + Error::::TooManyMessagesInTheProof, + ); + }); +} + +#[test] +fn receive_messages_delivery_proof_works() { + run_test(|| { + send_regular_message(TEST_LANE_ID); + receive_messages_delivery_proof(); + + assert_eq!(OutboundLanes::::get(TEST_LANE_ID).latest_received_nonce, 1,); + }); +} + +#[test] +fn receive_messages_delivery_proof_rewards_relayers() { + run_test(|| { + send_regular_message(TEST_LANE_ID); + send_regular_message(TEST_LANE_ID); + + // this reports delivery of message 1 => reward is paid to TEST_RELAYER_A + let single_message_delivery_proof = prepare_messages_delivery_proof( + TEST_LANE_ID, + InboundLaneData { + relayers: vec![unrewarded_relayer(1, 1, TEST_RELAYER_A)].into(), + ..Default::default() + }, + ); + let single_message_delivery_proof_size = single_message_delivery_proof.size(); + let result = Pallet::::receive_messages_delivery_proof( + RuntimeOrigin::signed(1), + single_message_delivery_proof, + UnrewardedRelayersState { + unrewarded_relayer_entries: 1, + messages_in_oldest_entry: 1, + total_messages: 1, + last_delivered_nonce: 1, + }, + ); + assert_ok!(result); + assert_eq!( + result.unwrap().actual_weight.unwrap(), + TestWeightInfo::receive_messages_delivery_proof_weight( + &PreComputedSize(single_message_delivery_proof_size as _), + &UnrewardedRelayersState { + unrewarded_relayer_entries: 1, + total_messages: 1, + ..Default::default() + }, + ) + ); + assert!(TestDeliveryConfirmationPayments::is_reward_paid(TEST_RELAYER_A, 1)); + assert!(!TestDeliveryConfirmationPayments::is_reward_paid(TEST_RELAYER_B, 1)); + + // this reports delivery of both message 1 and message 2 => reward is paid only to + // TEST_RELAYER_B + let two_messages_delivery_proof = prepare_messages_delivery_proof( + TEST_LANE_ID, + InboundLaneData { + relayers: vec![ + unrewarded_relayer(1, 1, TEST_RELAYER_A), + unrewarded_relayer(2, 2, TEST_RELAYER_B), + ] + .into(), + ..Default::default() + }, + ); + let two_messages_delivery_proof_size = two_messages_delivery_proof.size(); + let result = Pallet::::receive_messages_delivery_proof( + RuntimeOrigin::signed(1), + two_messages_delivery_proof, + UnrewardedRelayersState { + unrewarded_relayer_entries: 2, + messages_in_oldest_entry: 1, + total_messages: 2, + last_delivered_nonce: 2, + }, + ); + assert_ok!(result); + // even though the pre-dispatch weight was for two messages, the actual weight is + // for single message only + assert_eq!( + result.unwrap().actual_weight.unwrap(), + TestWeightInfo::receive_messages_delivery_proof_weight( + &PreComputedSize(two_messages_delivery_proof_size as _), + &UnrewardedRelayersState { + unrewarded_relayer_entries: 1, + total_messages: 1, + ..Default::default() + }, + ) + ); + assert!(!TestDeliveryConfirmationPayments::is_reward_paid(TEST_RELAYER_A, 1)); + assert!(TestDeliveryConfirmationPayments::is_reward_paid(TEST_RELAYER_B, 1)); + assert_eq!(TestOnMessagesDelivered::call_arguments(), Some((TEST_LANE_ID, 0))); + }); +} + +#[test] +fn receive_messages_delivery_proof_rejects_invalid_proof() { + run_test(|| { + let mut proof = prepare_messages_delivery_proof(TEST_LANE_ID, Default::default()); + proof.lane = bp_messages::LaneId([42, 42, 42, 42]); + + assert_noop!( + Pallet::::receive_messages_delivery_proof( + RuntimeOrigin::signed(1), + proof, + Default::default(), + ), + Error::::InvalidMessagesDeliveryProof, + ); + }); +} + +#[test] +fn receive_messages_delivery_proof_rejects_proof_if_declared_relayers_state_is_invalid() { + run_test(|| { + // when number of relayers entries is invalid + let proof = prepare_messages_delivery_proof( + TEST_LANE_ID, + InboundLaneData { + relayers: vec![ + unrewarded_relayer(1, 1, TEST_RELAYER_A), + unrewarded_relayer(2, 2, TEST_RELAYER_B), + ] + .into(), + ..Default::default() + }, + ); + assert_noop!( + Pallet::::receive_messages_delivery_proof( + RuntimeOrigin::signed(1), + proof, + UnrewardedRelayersState { + unrewarded_relayer_entries: 1, + total_messages: 2, + last_delivered_nonce: 2, + ..Default::default() + }, + ), + Error::::InvalidUnrewardedRelayersState, + ); + + // when number of messages is invalid + let proof = prepare_messages_delivery_proof( + TEST_LANE_ID, + InboundLaneData { + relayers: vec![ + unrewarded_relayer(1, 1, TEST_RELAYER_A), + unrewarded_relayer(2, 2, TEST_RELAYER_B), + ] + .into(), + ..Default::default() + }, + ); + assert_noop!( + Pallet::::receive_messages_delivery_proof( + RuntimeOrigin::signed(1), + proof, + UnrewardedRelayersState { + unrewarded_relayer_entries: 2, + total_messages: 1, + last_delivered_nonce: 2, + ..Default::default() + }, + ), + Error::::InvalidUnrewardedRelayersState, + ); + + // when last delivered nonce is invalid + let proof = prepare_messages_delivery_proof( + TEST_LANE_ID, + InboundLaneData { + relayers: vec![ + unrewarded_relayer(1, 1, TEST_RELAYER_A), + unrewarded_relayer(2, 2, TEST_RELAYER_B), + ] + .into(), + ..Default::default() + }, + ); + assert_noop!( + Pallet::::receive_messages_delivery_proof( + RuntimeOrigin::signed(1), + proof, + UnrewardedRelayersState { + unrewarded_relayer_entries: 2, + total_messages: 2, + last_delivered_nonce: 8, + ..Default::default() + }, + ), + Error::::InvalidUnrewardedRelayersState, + ); + }); +} + +#[test] +fn receive_messages_accepts_single_message_with_invalid_payload() { + run_test(|| { + let mut invalid_message = message(1, REGULAR_PAYLOAD); + invalid_message.payload = Vec::new(); + + assert_ok!(Pallet::::receive_messages_proof( + RuntimeOrigin::signed(1), + TEST_RELAYER_A, + prepare_messages_proof(vec![invalid_message], None), + 1, + Weight::zero(), /* weight may be zero in this case (all messages are + * improperly encoded) */ + ),); + + assert_eq!(InboundLanes::::get(TEST_LANE_ID).last_delivered_nonce(), 1,); + }); +} + +#[test] +fn receive_messages_accepts_batch_with_message_with_invalid_payload() { + run_test(|| { + let mut invalid_message = message(2, REGULAR_PAYLOAD); + invalid_message.payload = Vec::new(); + + assert_ok!(Pallet::::receive_messages_proof( + RuntimeOrigin::signed(1), + TEST_RELAYER_A, + prepare_messages_proof( + vec![message(1, REGULAR_PAYLOAD), invalid_message, message(3, REGULAR_PAYLOAD),], + None + ), + 3, + REGULAR_PAYLOAD.declared_weight + REGULAR_PAYLOAD.declared_weight, + ),); + + assert_eq!(InboundLanes::::get(TEST_LANE_ID).last_delivered_nonce(), 3,); + }); +} + +#[test] +fn actual_dispatch_weight_does_not_overflow() { + run_test(|| { + let message1 = message(1, message_payload(0, u64::MAX / 2)); + let message2 = message(2, message_payload(0, u64::MAX / 2)); + let message3 = message(3, message_payload(0, u64::MAX / 2)); + + let proof = prepare_messages_proof(vec![message1, message2, message3], None); + assert_noop!( + Pallet::::receive_messages_proof( + RuntimeOrigin::signed(1), + TEST_RELAYER_A, + // this may cause overflow if source chain storage is invalid + proof, + 3, + Weight::MAX, + ), + Error::::InsufficientDispatchWeight + ); + assert_eq!(InboundLanes::::get(TEST_LANE_ID).last_delivered_nonce(), 0); + }); +} + +#[test] +fn ref_time_refund_from_receive_messages_proof_works() { + run_test(|| { + fn submit_with_unspent_weight( + nonce: MessageNonce, + unspent_weight: u64, + ) -> (Weight, Weight) { + let mut payload = REGULAR_PAYLOAD; + *payload.dispatch_result.unspent_weight.ref_time_mut() = unspent_weight; + let proof = prepare_messages_proof(vec![message(nonce, payload)], None); + let messages_count = 1; + let pre_dispatch_weight = + ::WeightInfo::receive_messages_proof_weight( + &*proof, + messages_count, + REGULAR_PAYLOAD.declared_weight, + ); + let result = Pallet::::receive_messages_proof( + RuntimeOrigin::signed(1), + TEST_RELAYER_A, + proof, + messages_count, + REGULAR_PAYLOAD.declared_weight, + ) + .expect("delivery has failed"); + let post_dispatch_weight = + result.actual_weight.expect("receive_messages_proof always returns Some"); + + // message delivery transactions are never free + assert_eq!(result.pays_fee, Pays::Yes); + + (pre_dispatch_weight, post_dispatch_weight) + } + + // when dispatch is returning `unspent_weight < declared_weight` + let (pre, post) = submit_with_unspent_weight(1, 1); + assert_eq!(post.ref_time(), pre.ref_time() - 1); + + // when dispatch is returning `unspent_weight = declared_weight` + let (pre, post) = submit_with_unspent_weight(2, REGULAR_PAYLOAD.declared_weight.ref_time()); + assert_eq!(post.ref_time(), pre.ref_time() - REGULAR_PAYLOAD.declared_weight.ref_time()); + + // when dispatch is returning `unspent_weight > declared_weight` + let (pre, post) = + submit_with_unspent_weight(3, REGULAR_PAYLOAD.declared_weight.ref_time() + 1); + assert_eq!(post.ref_time(), pre.ref_time() - REGULAR_PAYLOAD.declared_weight.ref_time()); + + // when there's no unspent weight + let (pre, post) = submit_with_unspent_weight(4, 0); + assert_eq!(post.ref_time(), pre.ref_time()); + + // when dispatch is returning `unspent_weight < declared_weight` + let (pre, post) = submit_with_unspent_weight(5, 1); + assert_eq!(post.ref_time(), pre.ref_time() - 1); + }); +} + +#[test] +fn proof_size_refund_from_receive_messages_proof_works() { + run_test(|| { + let max_entries = BridgedChain::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX as usize; + + // if there's maximal number of unrewarded relayer entries at the inbound lane, then + // `proof_size` is unchanged in post-dispatch weight + let proof = prepare_messages_proof(vec![message(101, REGULAR_PAYLOAD)], None); + let messages_count = 1; + let pre_dispatch_weight = + ::WeightInfo::receive_messages_proof_weight( + &*proof, + messages_count, + REGULAR_PAYLOAD.declared_weight, + ); + InboundLanes::::insert( + TEST_LANE_ID, + StoredInboundLaneData(InboundLaneData { + relayers: vec![ + UnrewardedRelayer { + relayer: 42, + messages: DeliveredMessages { begin: 0, end: 100 } + }; + max_entries + ] + .into(), + last_confirmed_nonce: 0, + }), + ); + let post_dispatch_weight = Pallet::::receive_messages_proof( + RuntimeOrigin::signed(1), + TEST_RELAYER_A, + proof.clone(), + messages_count, + REGULAR_PAYLOAD.declared_weight, + ) + .unwrap() + .actual_weight + .unwrap(); + assert_eq!(post_dispatch_weight.proof_size(), pre_dispatch_weight.proof_size()); + + // if count of unrewarded relayer entries is less than maximal, then some `proof_size` + // must be refunded + InboundLanes::::insert( + TEST_LANE_ID, + StoredInboundLaneData(InboundLaneData { + relayers: vec![ + UnrewardedRelayer { + relayer: 42, + messages: DeliveredMessages { begin: 0, end: 100 } + }; + max_entries - 1 + ] + .into(), + last_confirmed_nonce: 0, + }), + ); + let post_dispatch_weight = Pallet::::receive_messages_proof( + RuntimeOrigin::signed(1), + TEST_RELAYER_A, + proof, + messages_count, + REGULAR_PAYLOAD.declared_weight, + ) + .unwrap() + .actual_weight + .unwrap(); + assert!( + post_dispatch_weight.proof_size() < pre_dispatch_weight.proof_size(), + "Expected post-dispatch PoV {} to be less than pre-dispatch PoV {}", + post_dispatch_weight.proof_size(), + pre_dispatch_weight.proof_size(), + ); + }); +} + +#[test] +fn receive_messages_delivery_proof_rejects_proof_if_trying_to_confirm_more_messages_than_expected() +{ + run_test(|| { + // send message first to be able to check that delivery_proof fails later + send_regular_message(TEST_LANE_ID); + + // 1) InboundLaneData declares that the `last_confirmed_nonce` is 1; + // 2) InboundLaneData has no entries => `InboundLaneData::last_delivered_nonce()` returns + // `last_confirmed_nonce`; + // 3) it means that we're going to confirm delivery of messages 1..=1; + // 4) so the number of declared messages (see `UnrewardedRelayersState`) is `0` and numer of + // actually confirmed messages is `1`. + let proof = prepare_messages_delivery_proof( + TEST_LANE_ID, + InboundLaneData { last_confirmed_nonce: 1, relayers: Default::default() }, + ); + assert_noop!( + Pallet::::receive_messages_delivery_proof( + RuntimeOrigin::signed(1), + proof, + UnrewardedRelayersState { last_delivered_nonce: 1, ..Default::default() }, + ), + Error::::ReceptionConfirmation( + ReceptionConfirmationError::TryingToConfirmMoreMessagesThanExpected + ), + ); + }); +} + +#[test] +fn storage_keys_computed_properly() { + assert_eq!( + PalletOperatingMode::::storage_value_final_key().to_vec(), + bp_messages::storage_keys::operating_mode_key("Messages").0, + ); + + assert_eq!( + OutboundMessages::::storage_map_final_key(MessageKey { + lane_id: TEST_LANE_ID, + nonce: 42 + }), + bp_messages::storage_keys::message_key("Messages", &TEST_LANE_ID, 42).0, + ); + + assert_eq!( + OutboundLanes::::storage_map_final_key(TEST_LANE_ID), + bp_messages::storage_keys::outbound_lane_data_key("Messages", &TEST_LANE_ID).0, + ); + + assert_eq!( + InboundLanes::::storage_map_final_key(TEST_LANE_ID), + bp_messages::storage_keys::inbound_lane_data_key("Messages", &TEST_LANE_ID).0, + ); +} + +#[test] +fn inbound_message_details_works() { + run_test(|| { + assert_eq!( + Pallet::::inbound_message_data( + TEST_LANE_ID, + REGULAR_PAYLOAD.encode(), + OutboundMessageDetails { nonce: 0, dispatch_weight: Weight::zero(), size: 0 }, + ), + InboundMessageDetails { dispatch_weight: REGULAR_PAYLOAD.declared_weight }, + ); + }); +} + +#[test] +fn on_idle_callback_respects_remaining_weight() { + run_test(|| { + send_regular_message(TEST_LANE_ID); + send_regular_message(TEST_LANE_ID); + send_regular_message(TEST_LANE_ID); + send_regular_message(TEST_LANE_ID); + + assert_ok!(Pallet::::receive_messages_delivery_proof( + RuntimeOrigin::signed(1), + prepare_messages_delivery_proof( + TEST_LANE_ID, + InboundLaneData { + last_confirmed_nonce: 4, + relayers: vec![unrewarded_relayer(1, 4, TEST_RELAYER_A)].into(), + }, + ), + UnrewardedRelayersState { + unrewarded_relayer_entries: 1, + messages_in_oldest_entry: 4, + total_messages: 4, + last_delivered_nonce: 4, + }, + )); + + // all 4 messages may be pruned now + assert_eq!(outbound_lane::(TEST_LANE_ID).data().latest_received_nonce, 4); + assert_eq!(outbound_lane::(TEST_LANE_ID).data().oldest_unpruned_nonce, 1); + System::::set_block_number(2); + + // if passed wight is too low to do anything + let dbw = DbWeight::get(); + assert_eq!(Pallet::::on_idle(0, dbw.reads_writes(1, 1)), Weight::zero(),); + assert_eq!(outbound_lane::(TEST_LANE_ID).data().oldest_unpruned_nonce, 1); + + // if passed wight is enough to prune single message + assert_eq!( + Pallet::::on_idle(0, dbw.reads_writes(1, 2)), + dbw.reads_writes(1, 2), + ); + assert_eq!(outbound_lane::(TEST_LANE_ID).data().oldest_unpruned_nonce, 2); + + // if passed wight is enough to prune two more messages + assert_eq!( + Pallet::::on_idle(0, dbw.reads_writes(1, 3)), + dbw.reads_writes(1, 3), + ); + assert_eq!(outbound_lane::(TEST_LANE_ID).data().oldest_unpruned_nonce, 4); + + // if passed wight is enough to prune many messages + assert_eq!( + Pallet::::on_idle(0, dbw.reads_writes(100, 100)), + dbw.reads_writes(1, 2), + ); + assert_eq!(outbound_lane::(TEST_LANE_ID).data().oldest_unpruned_nonce, 5); + }); +} + +#[test] +fn on_idle_callback_is_rotating_lanes_to_prune() { + run_test(|| { + // send + receive confirmation for lane 1 + send_regular_message(TEST_LANE_ID); + receive_messages_delivery_proof(); + // send + receive confirmation for lane 2 + send_regular_message(TEST_LANE_ID_2); + assert_ok!(Pallet::::receive_messages_delivery_proof( + RuntimeOrigin::signed(1), + prepare_messages_delivery_proof( + TEST_LANE_ID_2, + InboundLaneData { + last_confirmed_nonce: 1, + relayers: vec![unrewarded_relayer(1, 1, TEST_RELAYER_A)].into(), + }, + ), + UnrewardedRelayersState { + unrewarded_relayer_entries: 1, + messages_in_oldest_entry: 1, + total_messages: 1, + last_delivered_nonce: 1, + }, + )); + + // nothing is pruned yet + assert_eq!(outbound_lane::(TEST_LANE_ID).data().latest_received_nonce, 1); + assert_eq!(outbound_lane::(TEST_LANE_ID).data().oldest_unpruned_nonce, 1); + assert_eq!( + outbound_lane::(TEST_LANE_ID_2).data().latest_received_nonce, + 1 + ); + assert_eq!( + outbound_lane::(TEST_LANE_ID_2).data().oldest_unpruned_nonce, + 1 + ); + + // in block#2.on_idle lane messages of lane 1 are pruned + let dbw = DbWeight::get(); + System::::set_block_number(2); + assert_eq!( + Pallet::::on_idle(0, dbw.reads_writes(100, 100)), + dbw.reads_writes(1, 2), + ); + assert_eq!(outbound_lane::(TEST_LANE_ID).data().oldest_unpruned_nonce, 2); + assert_eq!( + outbound_lane::(TEST_LANE_ID_2).data().oldest_unpruned_nonce, + 1 + ); + + // in block#3.on_idle lane messages of lane 2 are pruned + System::::set_block_number(3); + + assert_eq!( + Pallet::::on_idle(0, dbw.reads_writes(100, 100)), + dbw.reads_writes(1, 2), + ); + assert_eq!(outbound_lane::(TEST_LANE_ID).data().oldest_unpruned_nonce, 2); + assert_eq!( + outbound_lane::(TEST_LANE_ID_2).data().oldest_unpruned_nonce, + 2 + ); + }); +} + +#[test] +fn outbound_message_from_unconfigured_lane_is_rejected() { + run_test(|| { + assert_noop!( + Pallet::::validate_message(TEST_LANE_ID_3, ®ULAR_PAYLOAD,), + Error::::InactiveOutboundLane, + ); + }); +} + +#[test] +fn test_bridge_messages_call_is_correctly_defined() { + run_test(|| { + let account_id = 1; + let message_proof = prepare_messages_proof(vec![message(1, REGULAR_PAYLOAD)], None); + let message_delivery_proof = prepare_messages_delivery_proof( + TEST_LANE_ID, + InboundLaneData { + last_confirmed_nonce: 1, + relayers: vec![UnrewardedRelayer { + relayer: 0, + messages: DeliveredMessages::new(1), + }] + .into(), + }, + ); + let unrewarded_relayer_state = UnrewardedRelayersState { + unrewarded_relayer_entries: 1, + total_messages: 1, + last_delivered_nonce: 1, + ..Default::default() + }; + + let direct_receive_messages_proof_call = Call::::receive_messages_proof { + relayer_id_at_bridged_chain: account_id, + proof: message_proof.clone(), + messages_count: 1, + dispatch_weight: REGULAR_PAYLOAD.declared_weight, + }; + let indirect_receive_messages_proof_call = BridgeMessagesCall::< + AccountId, + FromBridgedChainMessagesProof, + FromBridgedChainMessagesDeliveryProof, + >::receive_messages_proof { + relayer_id_at_bridged_chain: account_id, + proof: *message_proof, + messages_count: 1, + dispatch_weight: REGULAR_PAYLOAD.declared_weight, + }; + assert_eq!( + direct_receive_messages_proof_call.encode(), + indirect_receive_messages_proof_call.encode() + ); + + let direct_receive_messages_delivery_proof_call = + Call::::receive_messages_delivery_proof { + proof: message_delivery_proof.clone(), + relayers_state: unrewarded_relayer_state.clone(), + }; + let indirect_receive_messages_delivery_proof_call = BridgeMessagesCall::< + AccountId, + FromBridgedChainMessagesProof, + FromBridgedChainMessagesDeliveryProof, + >::receive_messages_delivery_proof { + proof: message_delivery_proof, + relayers_state: unrewarded_relayer_state, + }; + assert_eq!( + direct_receive_messages_delivery_proof_call.encode(), + indirect_receive_messages_delivery_proof_call.encode() + ); + }); +} + +generate_owned_bridge_module_tests!( + MessagesOperatingMode::Basic(BasicOperatingMode::Normal), + MessagesOperatingMode::Basic(BasicOperatingMode::Halted) +); + +#[test] +fn inbound_storage_extra_proof_size_bytes_works() { + fn relayer_entry() -> UnrewardedRelayer { + UnrewardedRelayer { relayer: 42u64, messages: DeliveredMessages { begin: 0, end: 100 } } + } + + fn storage(relayer_entries: usize) -> RuntimeInboundLaneStorage { + RuntimeInboundLaneStorage { + lane_id: Default::default(), + cached_data: Some(InboundLaneData { + relayers: vec![relayer_entry(); relayer_entries].into(), + last_confirmed_nonce: 0, + }), + _phantom: Default::default(), + } + } + + let max_entries = BridgedChain::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX as usize; + + // when we have exactly `MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX` unrewarded relayers + assert_eq!(storage(max_entries).extra_proof_size_bytes(), 0); + + // when we have less than `MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX` unrewarded relayers + assert_eq!( + storage(max_entries - 1).extra_proof_size_bytes(), + relayer_entry().encode().len() as u64 + ); + assert_eq!( + storage(max_entries - 2).extra_proof_size_bytes(), + 2 * relayer_entry().encode().len() as u64 + ); + + // when we have more than `MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX` unrewarded relayers + // (shall not happen in practice) + assert_eq!(storage(max_entries + 1).extra_proof_size_bytes(), 0); +} + +#[test] +fn maybe_outbound_lanes_count_returns_correct_value() { + assert_eq!( + MaybeOutboundLanesCount::::get(), + Some(mock::ActiveOutboundLanes::get().len() as u32) + ); +} diff --git a/bridges/modules/messages/src/weights.rs b/bridges/modules/messages/src/weights.rs index 5bf7d56756079df8a5e469b9c50ba7607b65d983..72a06599b1655c52b9761c1b9af7c8d798631ddf 100644 --- a/bridges/modules/messages/src/weights.rs +++ b/bridges/modules/messages/src/weights.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for pallet_bridge_messages //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-03-23, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-06-22, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `covid`, CPU: `11th Gen Intel(R) Core(TM) i7-11800H @ 2.30GHz` +//! HOSTNAME: `serban-ROG-Zephyrus`, CPU: `12th Gen Intel(R) Core(TM) i7-12700H` //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: @@ -51,14 +51,13 @@ use sp_std::marker::PhantomData; /// Weight functions needed for pallet_bridge_messages. pub trait WeightInfo { fn receive_single_message_proof() -> Weight; - fn receive_two_messages_proof() -> Weight; + fn receive_n_messages_proof(n: u32) -> Weight; fn receive_single_message_proof_with_outbound_lane_state() -> Weight; - fn receive_single_message_proof_1_kb() -> Weight; - fn receive_single_message_proof_16_kb() -> Weight; + fn receive_single_n_bytes_message_proof(n: u32) -> Weight; fn receive_delivery_proof_for_single_message() -> Weight; fn receive_delivery_proof_for_two_messages_by_single_relayer() -> Weight; fn receive_delivery_proof_for_two_messages_by_two_relayers() -> Weight; - fn receive_single_message_proof_with_dispatch(i: u32) -> Weight; + fn receive_single_n_bytes_message_proof_with_dispatch(n: u32) -> Weight; } /// Weights for `pallet_bridge_messages` that are generated using one of the Bridge testnets. @@ -82,56 +81,39 @@ impl WeightInfo for BridgeWeight { /// 51655, mode: MaxEncodedLen) fn receive_single_message_proof() -> Weight { // Proof Size summary in bytes: - // Measured: `618` - // Estimated: `57170` - // Minimum execution time: 52_321 nanoseconds. - Weight::from_parts(54_478_000, 57170) + // Measured: `653` + // Estimated: `52673` + // Minimum execution time: 38_724 nanoseconds. + Weight::from_parts(40_650_000, 52673) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } - /// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0) + /// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0) /// - /// Proof: BridgeUnknownMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2), + /// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2), /// added: 497, mode: MaxEncodedLen) /// - /// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0) + /// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0) /// - /// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68), + /// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68), /// added: 2048, mode: MaxEncodedLen) /// - /// Storage: BridgeUnknownMessages InboundLanes (r:1 w:1) - /// - /// Proof: BridgeUnknownMessages InboundLanes (max_values: None, max_size: Some(49180), added: - /// 51655, mode: MaxEncodedLen) - fn receive_two_messages_proof() -> Weight { - // Proof Size summary in bytes: - // Measured: `618` - // Estimated: `57170` - // Minimum execution time: 64_597 nanoseconds. - Weight::from_parts(69_267_000, 57170) - .saturating_add(T::DbWeight::get().reads(3_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) - } - /// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0) + /// Storage: BridgeRialtoMessages InboundLanes (r:1 w:1) /// - /// Proof: BridgeUnknownMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2), - /// added: 497, mode: MaxEncodedLen) + /// Proof: BridgeRialtoMessages InboundLanes (max_values: None, max_size: Some(49208), added: + /// 51683, mode: MaxEncodedLen) /// - /// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0) + /// The range of component `n` is `[1, 1004]`. /// - /// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68), - /// added: 2048, mode: MaxEncodedLen) - /// - /// Storage: BridgeUnknownMessages InboundLanes (r:1 w:1) - /// - /// Proof: BridgeUnknownMessages InboundLanes (max_values: None, max_size: Some(49180), added: - /// 51655, mode: MaxEncodedLen) - fn receive_single_message_proof_with_outbound_lane_state() -> Weight { + /// The range of component `n` is `[1, 1004]`. + fn receive_n_messages_proof(n: u32) -> Weight { // Proof Size summary in bytes: - // Measured: `618` - // Estimated: `57170` - // Minimum execution time: 64_079 nanoseconds. - Weight::from_parts(65_905_000, 57170) + // Measured: `653` + // Estimated: `52673` + // Minimum execution time: 39_354 nanoseconds. + Weight::from_parts(29_708_543, 52673) + // Standard Error: 1_185 + .saturating_add(Weight::from_parts(7_648_787, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -149,12 +131,12 @@ impl WeightInfo for BridgeWeight { /// /// Proof: BridgeUnknownMessages InboundLanes (max_values: None, max_size: Some(49180), added: /// 51655, mode: MaxEncodedLen) - fn receive_single_message_proof_1_kb() -> Weight { + fn receive_single_message_proof_with_outbound_lane_state() -> Weight { // Proof Size summary in bytes: - // Measured: `618` - // Estimated: `57170` - // Minimum execution time: 50_588 nanoseconds. - Weight::from_parts(53_544_000, 57170) + // Measured: `653` + // Estimated: `52673` + // Minimum execution time: 45_578 nanoseconds. + Weight::from_parts(47_161_000, 52673) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -172,12 +154,16 @@ impl WeightInfo for BridgeWeight { /// /// Proof: BridgeUnknownMessages InboundLanes (max_values: None, max_size: Some(49180), added: /// 51655, mode: MaxEncodedLen) - fn receive_single_message_proof_16_kb() -> Weight { + /// + /// The range of component `n` is `[1, 16384]`. + fn receive_single_n_bytes_message_proof(n: u32) -> Weight { // Proof Size summary in bytes: - // Measured: `618` - // Estimated: `57170` - // Minimum execution time: 78_269 nanoseconds. - Weight::from_parts(81_748_000, 57170) + // Measured: `653` + // Estimated: `52673` + // Minimum execution time: 38_702 nanoseconds. + Weight::from_parts(41_040_143, 52673) + // Standard Error: 5 + .saturating_add(Weight::from_parts(1_174, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -198,16 +184,21 @@ impl WeightInfo for BridgeWeight { /// /// Storage: BridgeRelayers RelayerRewards (r:1 w:1) /// - /// Proof: BridgeRelayers RelayerRewards (max_values: None, max_size: Some(65), added: 2540, + /// Proof: BridgeRelayers RelayerRewards (max_values: None, max_size: Some(93), added: 2568, /// mode: MaxEncodedLen) + /// + /// Storage: BridgeRialtoMessages OutboundMessages (r:0 w:1) + /// + /// Proof: BridgeRialtoMessages OutboundMessages (max_values: None, max_size: Some(65596), + /// added: 68071, mode: MaxEncodedLen) fn receive_delivery_proof_for_single_message() -> Weight { // Proof Size summary in bytes: - // Measured: `579` - // Estimated: `9584` - // Minimum execution time: 45_786 nanoseconds. - Weight::from_parts(47_382_000, 9584) + // Measured: `701` + // Estimated: `3558` + // Minimum execution time: 37_197 nanoseconds. + Weight::from_parts(38_371_000, 3558) .saturating_add(T::DbWeight::get().reads(4_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + .saturating_add(T::DbWeight::get().writes(3_u64)) } /// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0) /// @@ -226,16 +217,21 @@ impl WeightInfo for BridgeWeight { /// /// Storage: BridgeRelayers RelayerRewards (r:1 w:1) /// - /// Proof: BridgeRelayers RelayerRewards (max_values: None, max_size: Some(65), added: 2540, + /// Proof: BridgeRelayers RelayerRewards (max_values: None, max_size: Some(93), added: 2568, /// mode: MaxEncodedLen) + /// + /// Storage: BridgeRialtoMessages OutboundMessages (r:0 w:2) + /// + /// Proof: BridgeRialtoMessages OutboundMessages (max_values: None, max_size: Some(65596), + /// added: 68071, mode: MaxEncodedLen) fn receive_delivery_proof_for_two_messages_by_single_relayer() -> Weight { // Proof Size summary in bytes: - // Measured: `596` - // Estimated: `9584` - // Minimum execution time: 44_544 nanoseconds. - Weight::from_parts(45_451_000, 9584) + // Measured: `701` + // Estimated: `3558` + // Minimum execution time: 38_684 nanoseconds. + Weight::from_parts(39_929_000, 3558) .saturating_add(T::DbWeight::get().reads(4_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) + .saturating_add(T::DbWeight::get().writes(4_u64)) } /// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0) /// @@ -254,16 +250,21 @@ impl WeightInfo for BridgeWeight { /// /// Storage: BridgeRelayers RelayerRewards (r:2 w:2) /// - /// Proof: BridgeRelayers RelayerRewards (max_values: None, max_size: Some(65), added: 2540, + /// Proof: BridgeRelayers RelayerRewards (max_values: None, max_size: Some(93), added: 2568, /// mode: MaxEncodedLen) + /// + /// Storage: BridgeRialtoMessages OutboundMessages (r:0 w:2) + /// + /// Proof: BridgeRialtoMessages OutboundMessages (max_values: None, max_size: Some(65596), + /// added: 68071, mode: MaxEncodedLen) fn receive_delivery_proof_for_two_messages_by_two_relayers() -> Weight { // Proof Size summary in bytes: - // Measured: `596` - // Estimated: `12124` - // Minimum execution time: 47_344 nanoseconds. - Weight::from_parts(48_311_000, 12124) + // Measured: `701` + // Estimated: `6126` + // Minimum execution time: 41_363 nanoseconds. + Weight::from_parts(42_621_000, 6126) .saturating_add(T::DbWeight::get().reads(5_u64)) - .saturating_add(T::DbWeight::get().writes(3_u64)) + .saturating_add(T::DbWeight::get().writes(5_u64)) } /// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0) /// @@ -280,15 +281,15 @@ impl WeightInfo for BridgeWeight { /// Proof: BridgeUnknownMessages InboundLanes (max_values: None, max_size: Some(49180), added: /// 51655, mode: MaxEncodedLen) /// - /// The range of component `i` is `[128, 2048]`. - fn receive_single_message_proof_with_dispatch(i: u32) -> Weight { + /// The range of component `n` is `[1, 16384]`. + fn receive_single_n_bytes_message_proof_with_dispatch(n: u32) -> Weight { // Proof Size summary in bytes: - // Measured: `618` - // Estimated: `57170` - // Minimum execution time: 52_385 nanoseconds. - Weight::from_parts(54_919_468, 57170) - // Standard Error: 108 - .saturating_add(Weight::from_parts(3_286, 0).saturating_mul(i.into())) + // Measured: `653` + // Estimated: `52673` + // Minimum execution time: 38_925 nanoseconds. + Weight::from_parts(39_617_000, 52673) + // Standard Error: 612 + .saturating_add(Weight::from_parts(372_813, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -312,33 +313,39 @@ impl WeightInfo for () { /// 51655, mode: MaxEncodedLen) fn receive_single_message_proof() -> Weight { // Proof Size summary in bytes: - // Measured: `618` - // Estimated: `57170` - // Minimum execution time: 52_321 nanoseconds. - Weight::from_parts(54_478_000, 57170) + // Measured: `653` + // Estimated: `52673` + // Minimum execution time: 38_724 nanoseconds. + Weight::from_parts(40_650_000, 52673) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } - /// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0) + /// Storage: BridgeRialtoMessages PalletOperatingMode (r:1 w:0) /// - /// Proof: BridgeUnknownMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2), + /// Proof: BridgeRialtoMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2), /// added: 497, mode: MaxEncodedLen) /// - /// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0) + /// Storage: BridgeRialtoGrandpa ImportedHeaders (r:1 w:0) /// - /// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68), + /// Proof: BridgeRialtoGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68), /// added: 2048, mode: MaxEncodedLen) /// - /// Storage: BridgeUnknownMessages InboundLanes (r:1 w:1) + /// Storage: BridgeRialtoMessages InboundLanes (r:1 w:1) /// - /// Proof: BridgeUnknownMessages InboundLanes (max_values: None, max_size: Some(49180), added: - /// 51655, mode: MaxEncodedLen) - fn receive_two_messages_proof() -> Weight { + /// Proof: BridgeRialtoMessages InboundLanes (max_values: None, max_size: Some(49208), added: + /// 51683, mode: MaxEncodedLen) + /// + /// The range of component `n` is `[1, 1004]`. + /// + /// The range of component `n` is `[1, 1004]`. + fn receive_n_messages_proof(n: u32) -> Weight { // Proof Size summary in bytes: - // Measured: `618` - // Estimated: `57170` - // Minimum execution time: 64_597 nanoseconds. - Weight::from_parts(69_267_000, 57170) + // Measured: `653` + // Estimated: `52673` + // Minimum execution time: 39_354 nanoseconds. + Weight::from_parts(29_708_543, 52673) + // Standard Error: 1_185 + .saturating_add(Weight::from_parts(7_648_787, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -358,10 +365,10 @@ impl WeightInfo for () { /// 51655, mode: MaxEncodedLen) fn receive_single_message_proof_with_outbound_lane_state() -> Weight { // Proof Size summary in bytes: - // Measured: `618` - // Estimated: `57170` - // Minimum execution time: 64_079 nanoseconds. - Weight::from_parts(65_905_000, 57170) + // Measured: `653` + // Estimated: `52673` + // Minimum execution time: 45_578 nanoseconds. + Weight::from_parts(47_161_000, 52673) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -377,37 +384,20 @@ impl WeightInfo for () { /// /// Storage: BridgeUnknownMessages InboundLanes (r:1 w:1) /// - /// Proof: BridgeUnknownMessages InboundLanes (max_values: None, max_size: Some(49180), added: - /// 51655, mode: MaxEncodedLen) - fn receive_single_message_proof_1_kb() -> Weight { - // Proof Size summary in bytes: - // Measured: `618` - // Estimated: `57170` - // Minimum execution time: 50_588 nanoseconds. - Weight::from_parts(53_544_000, 57170) - .saturating_add(RocksDbWeight::get().reads(3_u64)) - .saturating_add(RocksDbWeight::get().writes(1_u64)) - } - /// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0) - /// - /// Proof: BridgeUnknownMessages PalletOperatingMode (max_values: Some(1), max_size: Some(2), - /// added: 497, mode: MaxEncodedLen) - /// - /// Storage: BridgeUnknownGrandpa ImportedHeaders (r:1 w:0) + /// Proof: BridgeRialtoMessages InboundLanes (max_values: None, max_size: Some(49208), added: + /// 51683, mode: MaxEncodedLen) /// - /// Proof: BridgeUnknownGrandpa ImportedHeaders (max_values: Some(14400), max_size: Some(68), - /// added: 2048, mode: MaxEncodedLen) + /// The range of component `n` is `[1, 16384]`. /// - /// Storage: BridgeUnknownMessages InboundLanes (r:1 w:1) - /// - /// Proof: BridgeUnknownMessages InboundLanes (max_values: None, max_size: Some(49180), added: - /// 51655, mode: MaxEncodedLen) - fn receive_single_message_proof_16_kb() -> Weight { + /// The range of component `n` is `[1, 16384]`. + fn receive_single_n_bytes_message_proof(n: u32) -> Weight { // Proof Size summary in bytes: - // Measured: `618` - // Estimated: `57170` - // Minimum execution time: 78_269 nanoseconds. - Weight::from_parts(81_748_000, 57170) + // Measured: `653` + // Estimated: `52673` + // Minimum execution time: 38_702 nanoseconds. + Weight::from_parts(41_040_143, 52673) + // Standard Error: 5 + .saturating_add(Weight::from_parts(1_174, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -428,16 +418,21 @@ impl WeightInfo for () { /// /// Storage: BridgeRelayers RelayerRewards (r:1 w:1) /// - /// Proof: BridgeRelayers RelayerRewards (max_values: None, max_size: Some(65), added: 2540, + /// Proof: BridgeRelayers RelayerRewards (max_values: None, max_size: Some(93), added: 2568, /// mode: MaxEncodedLen) + /// + /// Storage: BridgeRialtoMessages OutboundMessages (r:0 w:1) + /// + /// Proof: BridgeRialtoMessages OutboundMessages (max_values: None, max_size: Some(65596), + /// added: 68071, mode: MaxEncodedLen) fn receive_delivery_proof_for_single_message() -> Weight { // Proof Size summary in bytes: - // Measured: `579` - // Estimated: `9584` - // Minimum execution time: 45_786 nanoseconds. - Weight::from_parts(47_382_000, 9584) + // Measured: `701` + // Estimated: `3558` + // Minimum execution time: 37_197 nanoseconds. + Weight::from_parts(38_371_000, 3558) .saturating_add(RocksDbWeight::get().reads(4_u64)) - .saturating_add(RocksDbWeight::get().writes(2_u64)) + .saturating_add(RocksDbWeight::get().writes(3_u64)) } /// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0) /// @@ -456,16 +451,21 @@ impl WeightInfo for () { /// /// Storage: BridgeRelayers RelayerRewards (r:1 w:1) /// - /// Proof: BridgeRelayers RelayerRewards (max_values: None, max_size: Some(65), added: 2540, + /// Proof: BridgeRelayers RelayerRewards (max_values: None, max_size: Some(93), added: 2568, /// mode: MaxEncodedLen) + /// + /// Storage: BridgeRialtoMessages OutboundMessages (r:0 w:2) + /// + /// Proof: BridgeRialtoMessages OutboundMessages (max_values: None, max_size: Some(65596), + /// added: 68071, mode: MaxEncodedLen) fn receive_delivery_proof_for_two_messages_by_single_relayer() -> Weight { // Proof Size summary in bytes: - // Measured: `596` - // Estimated: `9584` - // Minimum execution time: 44_544 nanoseconds. - Weight::from_parts(45_451_000, 9584) + // Measured: `701` + // Estimated: `3558` + // Minimum execution time: 38_684 nanoseconds. + Weight::from_parts(39_929_000, 3558) .saturating_add(RocksDbWeight::get().reads(4_u64)) - .saturating_add(RocksDbWeight::get().writes(2_u64)) + .saturating_add(RocksDbWeight::get().writes(4_u64)) } /// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0) /// @@ -484,16 +484,21 @@ impl WeightInfo for () { /// /// Storage: BridgeRelayers RelayerRewards (r:2 w:2) /// - /// Proof: BridgeRelayers RelayerRewards (max_values: None, max_size: Some(65), added: 2540, + /// Proof: BridgeRelayers RelayerRewards (max_values: None, max_size: Some(93), added: 2568, /// mode: MaxEncodedLen) + /// + /// Storage: BridgeRialtoMessages OutboundMessages (r:0 w:2) + /// + /// Proof: BridgeRialtoMessages OutboundMessages (max_values: None, max_size: Some(65596), + /// added: 68071, mode: MaxEncodedLen) fn receive_delivery_proof_for_two_messages_by_two_relayers() -> Weight { // Proof Size summary in bytes: - // Measured: `596` - // Estimated: `12124` - // Minimum execution time: 47_344 nanoseconds. - Weight::from_parts(48_311_000, 12124) + // Measured: `701` + // Estimated: `6126` + // Minimum execution time: 41_363 nanoseconds. + Weight::from_parts(42_621_000, 6126) .saturating_add(RocksDbWeight::get().reads(5_u64)) - .saturating_add(RocksDbWeight::get().writes(3_u64)) + .saturating_add(RocksDbWeight::get().writes(5_u64)) } /// Storage: BridgeUnknownMessages PalletOperatingMode (r:1 w:0) /// @@ -510,15 +515,15 @@ impl WeightInfo for () { /// Proof: BridgeUnknownMessages InboundLanes (max_values: None, max_size: Some(49180), added: /// 51655, mode: MaxEncodedLen) /// - /// The range of component `i` is `[128, 2048]`. - fn receive_single_message_proof_with_dispatch(i: u32) -> Weight { + /// The range of component `n` is `[1, 16384]`. + fn receive_single_n_bytes_message_proof_with_dispatch(n: u32) -> Weight { // Proof Size summary in bytes: - // Measured: `618` - // Estimated: `57170` - // Minimum execution time: 52_385 nanoseconds. - Weight::from_parts(54_919_468, 57170) - // Standard Error: 108 - .saturating_add(Weight::from_parts(3_286, 0).saturating_mul(i.into())) + // Measured: `653` + // Estimated: `52673` + // Minimum execution time: 38_925 nanoseconds. + Weight::from_parts(39_617_000, 52673) + // Standard Error: 612 + .saturating_add(Weight::from_parts(372_813, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } diff --git a/bridges/modules/messages/src/weights_ext.rs b/bridges/modules/messages/src/weights_ext.rs index c12e04f692bf8304fb58d7c97ec50d1b860ccb56..7711e212efb06da0421f57b01ab4d1eef8b48f16 100644 --- a/bridges/modules/messages/src/weights_ext.rs +++ b/bridges/modules/messages/src/weights_ext.rs @@ -40,13 +40,6 @@ pub fn ensure_weights_are_correct() { // benchmarked using `MaxEncodedLen` approach and there are no components that cause additional // db reads - // verify `receive_messages_proof` weight components - assert_ne!(W::receive_messages_proof_overhead().ref_time(), 0); - assert_ne!(W::receive_messages_proof_overhead().proof_size(), 0); - // W::receive_messages_proof_messages_overhead(1).ref_time() may be zero because: - // the message processing code (`InboundLane::receive_message`) is minimal and may not be - // accounted by our benchmarks - assert_eq!(W::receive_messages_proof_messages_overhead(1).proof_size(), 0); // W::receive_messages_proof_outbound_lane_state_overhead().ref_time() may be zero because: // the outbound lane state processing code (`InboundLane::receive_state_update`) is minimal and // may not be accounted by our benchmarks @@ -86,6 +79,19 @@ pub fn ensure_weights_are_correct() { total_messages_in_delivery_proof_does_not_affect_proof_size::(); } +/// Ensure that we are able to dispatch maximal size messages. +pub fn ensure_maximal_message_dispatch( + max_incoming_message_size: u32, + max_incoming_message_dispatch_weight: Weight, +) { + let message_dispatch_weight = W::message_dispatch_weight(max_incoming_message_size); + assert!( + message_dispatch_weight.all_lte(max_incoming_message_dispatch_weight), + "Dispatch weight of maximal message {message_dispatch_weight:?} must be lower \ + than the hardcoded {max_incoming_message_dispatch_weight:?}", + ); +} + /// Ensure that we're able to receive maximal (by-size and by-weight) message from other chain. pub fn ensure_able_to_receive_message( max_extrinsic_size: u32, @@ -98,7 +104,8 @@ pub fn ensure_able_to_receive_message( max_incoming_message_proof_size.saturating_add(SIGNED_EXTENSIONS_SIZE); assert!( max_delivery_transaction_size <= max_extrinsic_size, - "Size of maximal message delivery transaction {max_incoming_message_proof_size} + {SIGNED_EXTENSIONS_SIZE} is larger than maximal possible transaction size {max_extrinsic_size}", + "Size of maximal message delivery transaction {max_incoming_message_proof_size} + \ + {SIGNED_EXTENSIONS_SIZE} is larger than maximal possible transaction size {max_extrinsic_size}", ); // verify that we're able to receive proof of maximal-size message with maximal dispatch weight @@ -297,13 +304,11 @@ pub trait WeightInfoExt: WeightInfo { dispatch_weight: Weight, ) -> Weight { // basic components of extrinsic weight - let transaction_overhead = Self::receive_messages_proof_overhead(); + let base_weight = Self::receive_n_messages_proof(messages_count); let transaction_overhead_from_runtime = Self::receive_messages_proof_overhead_from_runtime(); let outbound_state_delivery_weight = Self::receive_messages_proof_outbound_lane_state_overhead(); - let messages_delivery_weight = - Self::receive_messages_proof_messages_overhead(MessageNonce::from(messages_count)); let messages_dispatch_weight = dispatch_weight; // proof size overhead weight @@ -315,10 +320,9 @@ pub trait WeightInfoExt: WeightInfo { actual_proof_size.saturating_sub(expected_proof_size), ); - transaction_overhead + base_weight .saturating_add(transaction_overhead_from_runtime) .saturating_add(outbound_state_delivery_weight) - .saturating_add(messages_delivery_weight) .saturating_add(messages_dispatch_weight) .saturating_add(proof_size_overhead) } @@ -354,25 +358,6 @@ pub trait WeightInfoExt: WeightInfo { // Functions that are used by extrinsics weights formulas. - /// Returns weight overhead of message delivery transaction (`receive_messages_proof`). - fn receive_messages_proof_overhead() -> Weight { - let weight_of_two_messages_and_two_tx_overheads = - Self::receive_single_message_proof().saturating_mul(2); - let weight_of_two_messages_and_single_tx_overhead = Self::receive_two_messages_proof(); - weight_of_two_messages_and_two_tx_overheads - .saturating_sub(weight_of_two_messages_and_single_tx_overhead) - } - - /// Returns weight that needs to be accounted when receiving given a number of messages with - /// message delivery transaction (`receive_messages_proof`). - fn receive_messages_proof_messages_overhead(messages: MessageNonce) -> Weight { - let weight_of_two_messages_and_single_tx_overhead = Self::receive_two_messages_proof(); - let weight_of_single_message_and_single_tx_overhead = Self::receive_single_message_proof(); - weight_of_two_messages_and_single_tx_overhead - .saturating_sub(weight_of_single_message_and_single_tx_overhead) - .saturating_mul(messages as _) - } - /// Returns weight that needs to be accounted when message delivery transaction /// (`receive_messages_proof`) is carrying outbound lane state proof. fn receive_messages_proof_outbound_lane_state_overhead() -> Weight { @@ -426,9 +411,8 @@ pub trait WeightInfoExt: WeightInfo { /// is less than that cost). fn storage_proof_size_overhead(proof_size: u32) -> Weight { let proof_size_in_bytes = proof_size; - let byte_weight = (Self::receive_single_message_proof_16_kb() - - Self::receive_single_message_proof_1_kb()) / - (15 * 1024); + let byte_weight = Self::receive_single_n_bytes_message_proof(2) - + Self::receive_single_n_bytes_message_proof(1); proof_size_in_bytes * byte_weight } @@ -440,11 +424,9 @@ pub trait WeightInfoExt: WeightInfo { /// `receive_single_message_proof_with_dispatch` benchmark. See its requirements for /// details. fn message_dispatch_weight(message_size: u32) -> Weight { - // There may be a tiny overweight/underweight here, because we don't account how message - // size affects all steps before dispatch. But the effect should be small enough and we - // may ignore it. - Self::receive_single_message_proof_with_dispatch(message_size) - .saturating_sub(Self::receive_single_message_proof()) + let message_size_in_bytes = message_size; + Self::receive_single_n_bytes_message_proof_with_dispatch(message_size_in_bytes) + .saturating_sub(Self::receive_single_n_bytes_message_proof(message_size_in_bytes)) } } @@ -479,7 +461,7 @@ impl WeightInfoExt for crate::weights::BridgeWeight #[cfg(test)] mod tests { use super::*; - use crate::{mock::TestRuntime, weights::BridgeWeight}; + use crate::{tests::mock::TestRuntime, weights::BridgeWeight}; #[test] fn ensure_default_weights_are_correct() { diff --git a/bridges/modules/parachains/Cargo.toml b/bridges/modules/parachains/Cargo.toml index 97bad724a789ea0cdf0f0c972b153606fc302e7f..cda0ee8106d5400c33e186265d672f1b9282dc0d 100644 --- a/bridges/modules/parachains/Cargo.toml +++ b/bridges/modules/parachains/Cargo.toml @@ -30,7 +30,6 @@ frame-support = { workspace = true } frame-system = { workspace = true } sp-runtime = { workspace = true } sp-std = { workspace = true } -sp-trie = { workspace = true } [dev-dependencies] bp-header-chain = { workspace = true, default-features = true } @@ -54,7 +53,6 @@ std = [ "scale-info/std", "sp-runtime/std", "sp-std/std", - "sp-trie/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/bridges/modules/parachains/src/benchmarking.rs b/bridges/modules/parachains/src/benchmarking.rs index 27e06a12a1d93486d93aa258afc1d7de4713df2c..92ece6d688cbea3bed2e5d489163f2416bef9bbc 100644 --- a/bridges/modules/parachains/src/benchmarking.rs +++ b/bridges/modules/parachains/src/benchmarking.rs @@ -22,7 +22,7 @@ use crate::{ }; use bp_polkadot_core::parachains::{ParaHash, ParaHeadsProof, ParaId}; -use bp_runtime::StorageProofSize; +use bp_runtime::UnverifiedStorageProofParams; use frame_benchmarking::{account, benchmarks_instance_pallet}; use frame_system::RawOrigin; use sp_std::prelude::*; @@ -38,7 +38,7 @@ pub trait Config: crate::Config { fn prepare_parachain_heads_proof( parachains: &[ParaId], parachain_head_size: u32, - proof_size: StorageProofSize, + proof_params: UnverifiedStorageProofParams, ) -> (RelayBlockNumber, RelayBlockHash, ParaHeadsProof, Vec<(ParaId, ParaHash)>); } @@ -68,7 +68,7 @@ benchmarks_instance_pallet! { let (relay_block_number, relay_block_hash, parachain_heads_proof, parachains_heads) = T::prepare_parachain_heads_proof( ¶chains, DEFAULT_PARACHAIN_HEAD_SIZE, - StorageProofSize::Minimal(0), + UnverifiedStorageProofParams::default(), ); let at_relay_block = (relay_block_number, relay_block_hash); }: submit_parachain_heads(RawOrigin::Signed(sender), at_relay_block, parachains_heads, parachain_heads_proof) @@ -85,7 +85,7 @@ benchmarks_instance_pallet! { let (relay_block_number, relay_block_hash, parachain_heads_proof, parachains_heads) = T::prepare_parachain_heads_proof( ¶chains, DEFAULT_PARACHAIN_HEAD_SIZE, - StorageProofSize::HasLargeLeaf(1024), + UnverifiedStorageProofParams::from_db_size(1024), ); let at_relay_block = (relay_block_number, relay_block_hash); }: submit_parachain_heads(RawOrigin::Signed(sender), at_relay_block, parachains_heads, parachain_heads_proof) @@ -102,7 +102,7 @@ benchmarks_instance_pallet! { let (relay_block_number, relay_block_hash, parachain_heads_proof, parachains_heads) = T::prepare_parachain_heads_proof( ¶chains, DEFAULT_PARACHAIN_HEAD_SIZE, - StorageProofSize::HasLargeLeaf(16 * 1024), + UnverifiedStorageProofParams::from_db_size(16 * 1024), ); let at_relay_block = (relay_block_number, relay_block_hash); }: submit_parachain_heads(RawOrigin::Signed(sender), at_relay_block, parachains_heads, parachain_heads_proof) diff --git a/bridges/modules/parachains/src/call_ext.rs b/bridges/modules/parachains/src/call_ext.rs index fe6b319205d41491ce2df36d8a1d112eb37f94b4..0f77eaf2c5a93d372cab8af0857f10fa40ca920f 100644 --- a/bridges/modules/parachains/src/call_ext.rs +++ b/bridges/modules/parachains/src/call_ext.rs @@ -289,7 +289,7 @@ mod tests { RuntimeCall::Parachains(crate::Call::::submit_parachain_heads_ex { at_relay_block: (num, [num as u8; 32].into()), parachains, - parachain_heads_proof: ParaHeadsProof { storage_proof: Vec::new() }, + parachain_heads_proof: ParaHeadsProof { storage_proof: Default::default() }, is_free_execution_expected: false, }) .check_obsolete_submit_parachain_heads() @@ -303,7 +303,7 @@ mod tests { RuntimeCall::Parachains(crate::Call::::submit_parachain_heads_ex { at_relay_block: (num, [num as u8; 32].into()), parachains, - parachain_heads_proof: ParaHeadsProof { storage_proof: Vec::new() }, + parachain_heads_proof: ParaHeadsProof { storage_proof: Default::default() }, is_free_execution_expected: true, }) .check_obsolete_submit_parachain_heads() diff --git a/bridges/modules/parachains/src/lib.rs b/bridges/modules/parachains/src/lib.rs index d323aef3b22070d1db1e4709fe0dad8bf0360caf..e2c30ce9aecc1eb3b39fc588cc6386481f82fa7f 100644 --- a/bridges/modules/parachains/src/lib.rs +++ b/bridges/modules/parachains/src/lib.rs @@ -28,11 +28,12 @@ pub use weights::WeightInfo; pub use weights_ext::WeightInfoExt; use bp_header_chain::{HeaderChain, HeaderChainError}; -use bp_parachains::{parachain_head_storage_key_at_source, ParaInfo, ParaStoredHeaderData}; -use bp_polkadot_core::parachains::{ParaHash, ParaHead, ParaHeadsProof, ParaId}; -use bp_runtime::{Chain, HashOf, HeaderId, HeaderIdOf, Parachain, StorageProofError}; +use bp_parachains::{ParaInfo, ParaStoredHeaderData}; +use bp_polkadot_core::parachains::{ParaHash, ParaHeadsProof, ParaId}; +use bp_runtime::{Chain, HashOf, HeaderId, HeaderIdOf, Parachain}; use frame_support::{dispatch::PostDispatchInfo, DefaultNoBound}; use pallet_bridge_grandpa::SubmitFinalityProofHelper; +use proofs::{ParachainsStorageProofAdapter, StorageProofAdapter}; use sp_std::{marker::PhantomData, vec::Vec}; #[cfg(feature = "runtime-benchmarks")] @@ -55,6 +56,7 @@ pub mod benchmarking; mod call_ext; #[cfg(test)] mod mock; +mod proofs; /// The target that will be used when publishing logs related to this pallet. pub const LOG_TARGET: &str = "runtime::bridge-parachains"; @@ -448,15 +450,15 @@ pub mod pallet { parachains.len() as _, ); - let mut is_updated_something = false; - let mut storage = GrandpaPalletOf::::storage_proof_checker( - relay_block_hash, - parachain_heads_proof.storage_proof, - ) - .map_err(Error::::HeaderChainStorageProof)?; + let mut storage: ParachainsStorageProofAdapter = + ParachainsStorageProofAdapter::try_new_with_verified_storage_proof( + relay_block_hash, + parachain_heads_proof.storage_proof, + ) + .map_err(Error::::HeaderChainStorageProof)?; for (parachain, parachain_head_hash) in parachains { - let parachain_head = match Self::read_parachain_head(&mut storage, parachain) { + let parachain_head = match storage.read_parachain_head(parachain) { Ok(Some(parachain_head)) => parachain_head, Ok(None) => { log::trace!( @@ -541,7 +543,6 @@ pub mod pallet { parachain_head_hash, )?; - is_updated_something = true; if is_free { free_parachain_heads = free_parachain_heads + 1; } @@ -572,7 +573,7 @@ pub mod pallet { // => treat this as an error // // (we can throw error here, because now all our calls are transactional) - storage.ensure_no_unused_nodes().map_err(|e| { + storage.ensure_no_unused_keys().map_err(|e| { Error::::HeaderChainStorageProof(HeaderChainError::StorageProof(e)) })?; @@ -633,16 +634,6 @@ pub mod pallet { ImportedParaHeads::::get(parachain, hash).map(|h| h.into_inner()) } - /// Read parachain head from storage proof. - fn read_parachain_head( - storage: &mut bp_runtime::StorageProofChecker, - parachain: ParaId, - ) -> Result, StorageProofError> { - let parachain_head_key = - parachain_head_storage_key_at_source(T::ParasPalletName::get(), parachain); - storage.read_and_decode_value(parachain_head_key.0.as_ref()) - } - /// Try to update parachain head. pub(super) fn update_parachain_head( parachain: ParaId, @@ -801,6 +792,7 @@ impl, I: 'static, C: Parachain> HeaderChain pub fn initialize_for_benchmarks, I: 'static, PC: Parachain>( header: HeaderOf, ) { + use bp_polkadot_core::parachains::ParaHead; use bp_runtime::HeaderIdProvider; use sp_runtime::traits::Header; @@ -844,9 +836,10 @@ pub(crate) mod tests { use bp_parachains::{ BestParaHeadHash, BridgeParachainCall, ImportedParaHeadsKeyProvider, ParasInfoKeyProvider, }; + use bp_polkadot_core::parachains::ParaHead; use bp_runtime::{ BasicOperatingMode, OwnedBridgeModuleError, StorageDoubleMapKeyProvider, - StorageMapKeyProvider, + StorageMapKeyProvider, StorageProofError, }; use bp_test_utils::{ authority_list, generate_owned_bridge_module_tests, make_default_justification, diff --git a/bridges/modules/parachains/src/mock.rs b/bridges/modules/parachains/src/mock.rs index dbb62845392d5fd2f408744f4f8a2321ec4bd34d..c49b5939093c50a17fbf369533d5ff9c01b625bc 100644 --- a/bridges/modules/parachains/src/mock.rs +++ b/bridges/modules/parachains/src/mock.rs @@ -23,7 +23,7 @@ use frame_support::{ use sp_runtime::{ testing::H256, traits::{BlakeTwo256, Header as HeaderT}, - MultiSignature, + MultiSignature, StateVersion, }; use crate as pallet_bridge_parachains; @@ -60,6 +60,8 @@ impl Chain for Parachain1 { type Nonce = u64; type Signature = MultiSignature; + const STATE_VERSION: StateVersion = StateVersion::V1; + fn max_extrinsic_size() -> u32 { 0 } @@ -87,6 +89,8 @@ impl Chain for Parachain2 { type Nonce = u64; type Signature = MultiSignature; + const STATE_VERSION: StateVersion = StateVersion::V1; + fn max_extrinsic_size() -> u32 { 0 } @@ -114,6 +118,8 @@ impl Chain for Parachain3 { type Nonce = u64; type Signature = MultiSignature; + const STATE_VERSION: StateVersion = StateVersion::V1; + fn max_extrinsic_size() -> u32 { 0 } @@ -142,6 +148,8 @@ impl Chain for BigParachain { type Nonce = u64; type Signature = MultiSignature; + const STATE_VERSION: StateVersion = StateVersion::V1; + fn max_extrinsic_size() -> u32 { 0 } @@ -222,7 +230,7 @@ impl pallet_bridge_parachains::benchmarking::Config<()> for TestRuntime { fn prepare_parachain_heads_proof( parachains: &[ParaId], _parachain_head_size: u32, - _proof_size: bp_runtime::StorageProofSize, + _proof_params: bp_runtime::UnverifiedStorageProofParams, ) -> ( crate::RelayBlockNumber, crate::RelayBlockHash, @@ -256,38 +264,7 @@ impl Chain for TestBridgedChain { type Nonce = u32; type Signature = sp_runtime::testing::TestSignature; - fn max_extrinsic_size() -> u32 { - unreachable!() - } - - fn max_extrinsic_weight() -> Weight { - unreachable!() - } -} - -impl ChainWithGrandpa for TestBridgedChain { - const WITH_CHAIN_GRANDPA_PALLET_NAME: &'static str = ""; - const MAX_AUTHORITIES_COUNT: u32 = 16; - const REASONABLE_HEADERS_IN_JUSTIFICATION_ANCESTRY: u32 = 8; - const MAX_MANDATORY_HEADER_SIZE: u32 = 256; - const AVERAGE_HEADER_SIZE: u32 = 64; -} - -#[derive(Debug)] -pub struct OtherBridgedChain; - -impl Chain for OtherBridgedChain { - const ID: ChainId = *b"obch"; - - type BlockNumber = u64; - type Hash = crate::RelayBlockHash; - type Hasher = crate::RelayBlockHasher; - type Header = sp_runtime::generic::Header; - - type AccountId = AccountId; - type Balance = u32; - type Nonce = u32; - type Signature = sp_runtime::testing::TestSignature; + const STATE_VERSION: StateVersion = StateVersion::V1; fn max_extrinsic_size() -> u32 { unreachable!() @@ -298,7 +275,7 @@ impl Chain for OtherBridgedChain { } } -impl ChainWithGrandpa for OtherBridgedChain { +impl ChainWithGrandpa for TestBridgedChain { const WITH_CHAIN_GRANDPA_PALLET_NAME: &'static str = ""; const MAX_AUTHORITIES_COUNT: u32 = 16; const REASONABLE_HEADERS_IN_JUSTIFICATION_ANCESTRY: u32 = 8; diff --git a/bridges/modules/parachains/src/proofs.rs b/bridges/modules/parachains/src/proofs.rs new file mode 100644 index 0000000000000000000000000000000000000000..dcf22229f3423a9a75f4be68d1af2b1bf2e7ea1e --- /dev/null +++ b/bridges/modules/parachains/src/proofs.rs @@ -0,0 +1,81 @@ +// Copyright 2019-2021 Parity Technologies (UK) Ltd. +// This file is part of Parity Bridges Common. + +// Parity Bridges Common is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Parity Bridges Common is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Parity Bridges Common. If not, see . + +//! Tools for parachain head proof verification. + +use crate::{Config, GrandpaPalletOf, RelayBlockHash, RelayBlockHasher}; +use bp_header_chain::{HeaderChain, HeaderChainError}; +use bp_parachains::parachain_head_storage_key_at_source; +use bp_polkadot_core::parachains::{ParaHead, ParaId}; +use bp_runtime::{RawStorageProof, StorageProofChecker, StorageProofError}; +use codec::Decode; +use frame_support::traits::Get; + +/// Abstraction over storage proof manipulation, hiding implementation details of actual storage +/// proofs. +pub trait StorageProofAdapter, I: 'static> { + /// Read and decode optional value from the proof. + fn read_and_decode_optional_value( + &mut self, + key: &impl AsRef<[u8]>, + ) -> Result, StorageProofError>; + + /// Checks if each key was read. + fn ensure_no_unused_keys(self) -> Result<(), StorageProofError>; + + /// Read parachain head from storage proof. + fn read_parachain_head( + &mut self, + parachain: ParaId, + ) -> Result, StorageProofError> { + let parachain_head_key = + parachain_head_storage_key_at_source(T::ParasPalletName::get(), parachain); + self.read_and_decode_optional_value(¶chain_head_key) + } +} + +/// Actual storage proof adapter for parachain proofs. +pub type ParachainsStorageProofAdapter = RawStorageProofAdapter; + +/// A `StorageProofAdapter` implementation for raw storage proofs. +pub struct RawStorageProofAdapter, I: 'static> { + storage: StorageProofChecker, + _dummy: sp_std::marker::PhantomData<(T, I)>, +} + +impl, I: 'static> RawStorageProofAdapter { + /// Try to create a new instance of `RawStorageProofAdapter`. + pub fn try_new_with_verified_storage_proof( + relay_block_hash: RelayBlockHash, + storage_proof: RawStorageProof, + ) -> Result { + GrandpaPalletOf::::verify_storage_proof(relay_block_hash, storage_proof) + .map(|storage| RawStorageProofAdapter:: { storage, _dummy: Default::default() }) + } +} + +impl, I: 'static> StorageProofAdapter for RawStorageProofAdapter { + fn read_and_decode_optional_value( + &mut self, + key: &impl AsRef<[u8]>, + ) -> Result, StorageProofError> { + self.storage.read_and_decode_opt_value(key.as_ref()) + } + + fn ensure_no_unused_keys(self) -> Result<(), StorageProofError> { + self.storage.ensure_no_unused_nodes() + } +} diff --git a/bridges/modules/parachains/src/weights.rs b/bridges/modules/parachains/src/weights.rs index abddc8768947006e574bf6bca4d2301c2047199a..1f92b7ff763c3f572efef1acf141a9eba0d3eb0e 100644 --- a/bridges/modules/parachains/src/weights.rs +++ b/bridges/modules/parachains/src/weights.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for pallet_bridge_parachains //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-03-02, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-06-22, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `covid`, CPU: `11th Gen Intel(R) Core(TM) i7-11800H @ 2.30GHz` +//! HOSTNAME: `serban-ROG-Zephyrus`, CPU: `12th Gen Intel(R) Core(TM) i7-12700H` //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: @@ -86,14 +86,12 @@ impl WeightInfo for BridgeWeight { /// Some(196), added: 1681, mode: MaxEncodedLen) /// /// The range of component `p` is `[1, 2]`. - fn submit_parachain_heads_with_n_parachains(p: u32) -> Weight { + fn submit_parachain_heads_with_n_parachains(_p: u32) -> Weight { // Proof Size summary in bytes: - // Measured: `366` - // Estimated: `4648` - // Minimum execution time: 36_701 nanoseconds. - Weight::from_parts(38_597_828, 4648) - // Standard Error: 190_859 - .saturating_add(Weight::from_parts(60_685, 0).saturating_mul(p.into())) + // Measured: `302` + // Estimated: `3038` + // Minimum execution time: 30_211 nanoseconds. + Weight::from_parts(32_633_893, 3038) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -123,10 +121,10 @@ impl WeightInfo for BridgeWeight { /// Some(196), added: 1681, mode: MaxEncodedLen) fn submit_parachain_heads_with_1kb_proof() -> Weight { // Proof Size summary in bytes: - // Measured: `366` - // Estimated: `4648` - // Minimum execution time: 38_189 nanoseconds. - Weight::from_parts(39_252_000, 4648) + // Measured: `302` + // Estimated: `3038` + // Minimum execution time: 30_830 nanoseconds. + Weight::from_parts(31_801_000, 3038) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -156,10 +154,10 @@ impl WeightInfo for BridgeWeight { /// Some(196), added: 1681, mode: MaxEncodedLen) fn submit_parachain_heads_with_16kb_proof() -> Weight { // Proof Size summary in bytes: - // Measured: `366` - // Estimated: `4648` - // Minimum execution time: 62_868 nanoseconds. - Weight::from_parts(63_581_000, 4648) + // Measured: `302` + // Estimated: `3038` + // Minimum execution time: 44_736 nanoseconds. + Weight::from_parts(45_296_000, 3038) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -193,14 +191,12 @@ impl WeightInfo for () { /// Some(196), added: 1681, mode: MaxEncodedLen) /// /// The range of component `p` is `[1, 2]`. - fn submit_parachain_heads_with_n_parachains(p: u32) -> Weight { + fn submit_parachain_heads_with_n_parachains(_p: u32) -> Weight { // Proof Size summary in bytes: - // Measured: `366` - // Estimated: `4648` - // Minimum execution time: 36_701 nanoseconds. - Weight::from_parts(38_597_828, 4648) - // Standard Error: 190_859 - .saturating_add(Weight::from_parts(60_685, 0).saturating_mul(p.into())) + // Measured: `302` + // Estimated: `3038` + // Minimum execution time: 30_211 nanoseconds. + Weight::from_parts(32_633_893, 3038) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -230,10 +226,10 @@ impl WeightInfo for () { /// Some(196), added: 1681, mode: MaxEncodedLen) fn submit_parachain_heads_with_1kb_proof() -> Weight { // Proof Size summary in bytes: - // Measured: `366` - // Estimated: `4648` - // Minimum execution time: 38_189 nanoseconds. - Weight::from_parts(39_252_000, 4648) + // Measured: `302` + // Estimated: `3038` + // Minimum execution time: 30_830 nanoseconds. + Weight::from_parts(31_801_000, 3038) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -263,10 +259,10 @@ impl WeightInfo for () { /// Some(196), added: 1681, mode: MaxEncodedLen) fn submit_parachain_heads_with_16kb_proof() -> Weight { // Proof Size summary in bytes: - // Measured: `366` - // Estimated: `4648` - // Minimum execution time: 62_868 nanoseconds. - Weight::from_parts(63_581_000, 4648) + // Measured: `302` + // Estimated: `3038` + // Minimum execution time: 44_736 nanoseconds. + Weight::from_parts(45_296_000, 3038) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } diff --git a/bridges/modules/relayers/src/payment_adapter.rs b/bridges/modules/relayers/src/payment_adapter.rs index b2d9c676bddc493700a45fc957235dbb9516296b..f75c409aca4f3ef85fab748e4dc41af12b545562 100644 --- a/bridges/modules/relayers/src/payment_adapter.rs +++ b/bridges/modules/relayers/src/payment_adapter.rs @@ -23,6 +23,7 @@ use bp_messages::{ LaneId, MessageNonce, }; use bp_relayers::{RewardsAccountOwner, RewardsAccountParams}; +use bp_runtime::Chain; use frame_support::{sp_runtime::SaturatedConversion, traits::Get}; use sp_arithmetic::traits::{Saturating, Zero}; use sp_std::{collections::vec_deque::VecDeque, marker::PhantomData, ops::RangeInclusive}; @@ -57,7 +58,7 @@ where relayers_rewards, RewardsAccountParams::new( lane_id, - T::BridgedChainId::get(), + T::BridgedChain::ID, RewardsAccountOwner::BridgedChain, ), DeliveryReward::get(), diff --git a/bridges/modules/xcm-bridge-hub/src/mock.rs b/bridges/modules/xcm-bridge-hub/src/mock.rs index 4c09bce56d73eea717ad5149084e2ae337e48e87..df72e7a3c4fcc596cd89cc119c44aeb7c6915eaf 100644 --- a/bridges/modules/xcm-bridge-hub/src/mock.rs +++ b/bridges/modules/xcm-bridge-hub/src/mock.rs @@ -20,23 +20,17 @@ use crate as pallet_xcm_bridge_hub; use bp_messages::{ target_chain::{DispatchMessage, MessageDispatch}, - LaneId, -}; -use bp_runtime::{messages::MessageDispatchResult, Chain, ChainId, UnderlyingChainProvider}; -use bridge_runtime_common::{ - messages::{ - source::TargetHeaderChainAdapter, target::SourceHeaderChainAdapter, - BridgedChainWithMessages, HashOf, MessageBridge, ThisChainWithMessages, - }, - messages_xcm_extension::{SenderAndLane, XcmBlobHauler}, + ChainWithMessages, LaneId, MessageNonce, }; +use bp_runtime::{messages::MessageDispatchResult, Chain, ChainId, HashOf}; +use bridge_runtime_common::messages_xcm_extension::{SenderAndLane, XcmBlobHauler}; use codec::Encode; -use frame_support::{derive_impl, parameter_types, traits::ConstU32, weights::RuntimeDbWeight}; +use frame_support::{derive_impl, parameter_types, weights::RuntimeDbWeight}; use sp_core::H256; use sp_runtime::{ testing::Header as SubstrateHeader, traits::{BlakeTwo256, IdentityLookup}, - AccountId32, BuildStorage, + AccountId32, BuildStorage, StateVersion, }; use xcm::prelude::*; @@ -85,20 +79,17 @@ impl pallet_bridge_messages::Config for TestRuntime { type RuntimeEvent = RuntimeEvent; type WeightInfo = TestMessagesWeights; - type BridgedChainId = (); type ActiveOutboundLanes = ActiveOutboundLanes; - type MaxUnrewardedRelayerEntriesAtInboundLane = (); - type MaxUnconfirmedMessagesAtInboundLane = (); - type MaximalOutboundPayloadSize = ConstU32<2048>; type OutboundPayload = Vec; type InboundPayload = Vec; - type InboundRelayer = (); type DeliveryPayments = (); - type TargetHeaderChain = TargetHeaderChainAdapter; type DeliveryConfirmationPayments = (); type OnMessagesDelivered = (); - type SourceHeaderChain = SourceHeaderChainAdapter; type MessageDispatch = TestMessageDispatch; + + type ThisChain = ThisUnderlyingChain; + type BridgedChain = BridgedUnderlyingChain; + type BridgedHeaderChain = BridgedHeaderChain; } pub struct TestMessagesWeights; @@ -107,34 +98,27 @@ impl pallet_bridge_messages::WeightInfo for TestMessagesWeights { fn receive_single_message_proof() -> Weight { Weight::zero() } - fn receive_single_message_proof_with_outbound_lane_state() -> Weight { + fn receive_n_messages_proof(_: u32) -> Weight { Weight::zero() } - fn receive_delivery_proof_for_single_message() -> Weight { + fn receive_single_message_proof_with_outbound_lane_state() -> Weight { Weight::zero() } - fn receive_delivery_proof_for_two_messages_by_single_relayer() -> Weight { + fn receive_single_n_bytes_message_proof(_: u32) -> Weight { Weight::zero() } - fn receive_delivery_proof_for_two_messages_by_two_relayers() -> Weight { + fn receive_delivery_proof_for_single_message() -> Weight { Weight::zero() } - - fn receive_two_messages_proof() -> Weight { + fn receive_delivery_proof_for_two_messages_by_single_relayer() -> Weight { Weight::zero() } - - fn receive_single_message_proof_1_kb() -> Weight { + fn receive_delivery_proof_for_two_messages_by_two_relayers() -> Weight { Weight::zero() } - - fn receive_single_message_proof_16_kb() -> Weight { + fn receive_single_n_bytes_message_proof_with_dispatch(_: u32) -> Weight { Weight::zero() } - - fn receive_single_message_proof_with_dispatch(_: u32) -> Weight { - Weight::from_parts(1, 0) - } } impl pallet_bridge_messages::WeightInfoExt for TestMessagesWeights { @@ -198,9 +182,9 @@ impl XcmBlobHauler for TestXcmBlobHauler { type UncongestedMessage = (); } -pub struct ThisChain; +pub struct ThisUnderlyingChain; -impl Chain for ThisChain { +impl Chain for ThisUnderlyingChain { const ID: ChainId = *b"tuch"; type BlockNumber = u64; type Hash = H256; @@ -211,6 +195,8 @@ impl Chain for ThisChain { type Nonce = u64; type Signature = sp_runtime::MultiSignature; + const STATE_VERSION: StateVersion = StateVersion::V1; + fn max_extrinsic_size() -> u32 { u32::MAX } @@ -220,12 +206,19 @@ impl Chain for ThisChain { } } -pub struct BridgedChain; +impl ChainWithMessages for ThisUnderlyingChain { + const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str = ""; + + const MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX: MessageNonce = 16; + const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce = 1000; +} + +pub struct BridgedUnderlyingChain; pub type BridgedHeaderHash = H256; pub type BridgedChainHeader = SubstrateHeader; -impl Chain for BridgedChain { - const ID: ChainId = *b"tuch"; +impl Chain for BridgedUnderlyingChain { + const ID: ChainId = *b"bgdc"; type BlockNumber = u64; type Hash = BridgedHeaderHash; type Hasher = BlakeTwo256; @@ -235,6 +228,8 @@ impl Chain for BridgedChain { type Nonce = u64; type Signature = sp_runtime::MultiSignature; + const STATE_VERSION: StateVersion = StateVersion::V1; + fn max_extrinsic_size() -> u32 { 4096 } @@ -244,6 +239,12 @@ impl Chain for BridgedChain { } } +impl ChainWithMessages for BridgedUnderlyingChain { + const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str = ""; + const MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX: MessageNonce = 16; + const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce = 1000; +} + /// Test message dispatcher. pub struct TestMessageDispatch; @@ -272,42 +273,15 @@ impl MessageDispatch for TestMessageDispatch { } } -pub struct WrappedThisChain; -impl UnderlyingChainProvider for WrappedThisChain { - type Chain = ThisChain; -} -impl ThisChainWithMessages for WrappedThisChain { - type RuntimeOrigin = RuntimeOrigin; -} - -pub struct WrappedBridgedChain; -impl UnderlyingChainProvider for WrappedBridgedChain { - type Chain = BridgedChain; -} -impl BridgedChainWithMessages for WrappedBridgedChain {} - pub struct BridgedHeaderChain; -impl bp_header_chain::HeaderChain for BridgedHeaderChain { +impl bp_header_chain::HeaderChain for BridgedHeaderChain { fn finalized_header_state_root( - _hash: HashOf, - ) -> Option> { + _hash: HashOf, + ) -> Option> { unreachable!() } } -/// Bridge that is deployed on `ThisChain` and allows sending/receiving messages to/from -/// `BridgedChain`. -#[derive(Debug, PartialEq, Eq)] -pub struct OnThisChainBridge; - -impl MessageBridge for OnThisChainBridge { - const BRIDGED_MESSAGES_PALLET_NAME: &'static str = ""; - - type ThisChain = WrappedThisChain; - type BridgedChain = WrappedBridgedChain; - type BridgedHeaderChain = BridgedHeaderChain; -} - /// Run pallet test. pub fn run_test(test: impl FnOnce() -> T) -> T { sp_io::TestExternalities::new( diff --git a/bridges/primitives/header-chain/src/lib.rs b/bridges/primitives/header-chain/src/lib.rs index af2afb65a26a7f206fdbfcf22e20cb5100a8c95f..26295dee1801a127f455ed3288bd5232cb60bc10 100644 --- a/bridges/primitives/header-chain/src/lib.rs +++ b/bridges/primitives/header-chain/src/lib.rs @@ -46,7 +46,7 @@ pub mod storage_keys; pub enum HeaderChainError { /// Header with given hash is missing from the chain. UnknownHeader, - /// Storage proof related error. + /// Error generated by the `storage_proof` module. StorageProof(StorageProofError), } @@ -78,8 +78,9 @@ impl StoredHeaderDataBuilder for H { pub trait HeaderChain { /// Returns state (storage) root of given finalized header. fn finalized_header_state_root(header_hash: HashOf) -> Option>; + /// Get storage proof checker using finalized header. - fn storage_proof_checker( + fn verify_storage_proof( header_hash: HashOf, storage_proof: RawStorageProof, ) -> Result>, HeaderChainError> { @@ -409,7 +410,9 @@ mod tests { use super::*; use bp_runtime::ChainId; use frame_support::weights::Weight; - use sp_runtime::{testing::H256, traits::BlakeTwo256, DigestItem, MultiSignature}; + use sp_runtime::{ + testing::H256, traits::BlakeTwo256, DigestItem, MultiSignature, StateVersion, + }; struct TestChain; @@ -425,6 +428,8 @@ mod tests { type Nonce = u64; type Signature = MultiSignature; + const STATE_VERSION: StateVersion = StateVersion::V1; + fn max_extrinsic_size() -> u32 { 0 } diff --git a/bridges/primitives/messages/src/lib.rs b/bridges/primitives/messages/src/lib.rs index c3f79b3ee388c4584def56056f6cdf6328032e18..9984f8ac3222780ea2fd6af56dd896beb264b2d5 100644 --- a/bridges/primitives/messages/src/lib.rs +++ b/bridges/primitives/messages/src/lib.rs @@ -38,6 +38,9 @@ pub mod source_chain; pub mod storage_keys; pub mod target_chain; +/// Hard limit on message size that can be sent over the bridge. +pub const HARD_MESSAGE_SIZE_LIMIT: u32 = 64 * 1024; + /// Substrate-based chain with messaging support. pub trait ChainWithMessages: Chain { /// Name of the bridge messages pallet (used in `construct_runtime` macro call) that is @@ -48,11 +51,63 @@ pub trait ChainWithMessages: Chain { const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str; /// Maximal number of unrewarded relayers in a single confirmation transaction at this - /// `ChainWithMessages`. + /// `ChainWithMessages`. Unrewarded means that the relayer has delivered messages, but + /// either confirmations haven't been delivered back to the source chain, or we haven't + /// received reward confirmations yet. + /// + /// This constant limits maximal number of entries in the `InboundLaneData::relayers`. Keep + /// in mind that the same relayer account may take several (non-consecutive) entries in this + /// set. const MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX: MessageNonce; /// Maximal number of unconfirmed messages in a single confirmation transaction at this - /// `ChainWithMessages`. + /// `ChainWithMessages`. Unconfirmed means that the + /// message has been delivered, but either confirmations haven't been delivered back to the + /// source chain, or we haven't received reward confirmations for these messages yet. + /// + /// This constant limits difference between last message from last entry of the + /// `InboundLaneData::relayers` and first message at the first entry. + /// + /// There is no point of making this parameter lesser than + /// `MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX`, because then maximal number of relayer entries + /// will be limited by maximal number of messages. + /// + /// This value also represents maximal number of messages in single delivery transaction. + /// Transaction that is declaring more messages than this value, will be rejected. Even if + /// these messages are from different lanes. const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce; + + /// Return maximal dispatch weight of the message we're able to receive. + fn maximal_incoming_message_dispatch_weight() -> Weight { + // we leave 1/2 of `max_extrinsic_weight` for the delivery transaction itself + Self::max_extrinsic_weight() / 2 + } + + /// Return maximal size of the message we're able to receive. + fn maximal_incoming_message_size() -> u32 { + maximal_incoming_message_size(Self::max_extrinsic_size()) + } +} + +/// Return maximal size of the message the chain with `max_extrinsic_size` is able to receive. +pub fn maximal_incoming_message_size(max_extrinsic_size: u32) -> u32 { + // The maximal size of extrinsic at Substrate-based chain depends on the + // `frame_system::Config::MaximumBlockLength` and + // `frame_system::Config::AvailableBlockRatio` constants. This check is here to be sure that + // the lane won't stuck because message is too large to fit into delivery transaction. + // + // **IMPORTANT NOTE**: the delivery transaction contains storage proof of the message, not + // the message itself. The proof is always larger than the message. But unless chain state + // is enormously large, it should be several dozens/hundreds of bytes. The delivery + // transaction also contains signatures and signed extensions. Because of this, we reserve + // 1/3 of the the maximal extrinsic size for this data. + // + // **ANOTHER IMPORTANT NOTE**: large message means not only larger proofs and heavier + // proof verification, but also heavier message decoding and dispatch. So we have a hard + // limit of `64Kb`, which in practice limits the message size on all chains. Without this + // limit the **weight** (not the size) of the message will be higher than the + // `Self::maximal_incoming_message_dispatch_weight()`. + + sp_std::cmp::min(max_extrinsic_size / 3 * 2, HARD_MESSAGE_SIZE_LIMIT) } impl ChainWithMessages for T @@ -112,7 +167,19 @@ impl OperatingMode for MessagesOperatingMode { /// Lane id which implements `TypeId`. #[derive( - Clone, Copy, Decode, Default, Encode, Eq, Ord, PartialOrd, PartialEq, TypeInfo, MaxEncodedLen, + Clone, + Copy, + Decode, + Default, + Encode, + Eq, + Ord, + PartialOrd, + PartialEq, + TypeInfo, + MaxEncodedLen, + Serialize, + Deserialize, )] pub struct LaneId(pub [u8; 4]); @@ -435,7 +502,7 @@ where AccountId: sp_std::cmp::Ord, { // remember to reward relayers that have delivered messages - // this loop is bounded by `T::MaxUnrewardedRelayerEntriesAtInboundLane` on the bridged chain + // this loop is bounded by `T::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX` on the bridged chain let mut relayers_rewards = RelayersRewards::new(); for entry in messages_relayers { let nonce_begin = sp_std::cmp::max(entry.messages.begin, *received_range.start()); @@ -486,11 +553,11 @@ pub enum VerificationError { InvalidMessageWeight, /// Declared messages count doesn't match actual value. MessagesCountMismatch, - /// Error returned while reading/decoding message data from the storage proof. + /// Error returned while reading/decoding message data from the `VerifiedStorageProof`. MessageStorage(StorageProofError), /// The message is too large. MessageTooLarge, - /// Error returned while reading/decoding outbound lane data from the storage proof. + /// Error returned while reading/decoding outbound lane data from the `VerifiedStorageProof`. OutboundLaneStorage(StorageProofError), /// Storage proof related error. StorageProof(StorageProofError), diff --git a/bridges/primitives/messages/src/source_chain.rs b/bridges/primitives/messages/src/source_chain.rs index f4aefd9735583e265c3e44713f13f81ae63ba276..64f015bdb822eb25ff42a3fdb52bf6405a5424bf 100644 --- a/bridges/primitives/messages/src/source_chain.rs +++ b/bridges/primitives/messages/src/source_chain.rs @@ -16,11 +16,11 @@ //! Primitives of messages module, that are used on the source chain. -use crate::{InboundLaneData, LaneId, MessageNonce, VerificationError}; +use crate::{LaneId, MessageNonce, UnrewardedRelayer}; -use crate::UnrewardedRelayer; -use bp_runtime::Size; -use frame_support::Parameter; +use bp_runtime::{raw_storage_proof_size, RawStorageProof, Size}; +use codec::{Decode, Encode}; +use scale_info::TypeInfo; use sp_core::RuntimeDebug; use sp_std::{ collections::{btree_map::BTreeMap, vec_deque::VecDeque}, @@ -28,42 +28,36 @@ use sp_std::{ ops::RangeInclusive, }; -/// Number of messages, delivered by relayers. -pub type RelayersRewards = BTreeMap; - -/// Target chain API. Used by source chain to verify target chain proofs. +/// Messages delivery proof from the bridged chain. /// -/// All implementations of this trait should only work with finalized data that -/// can't change. Wrong implementation may lead to invalid lane states (i.e. lane -/// that's stuck) and/or processing messages without paying fees. +/// It contains everything required to prove that our (this chain) messages have been +/// delivered to the bridged (target) chain: /// -/// The `Payload` type here means the payload of the message that is sent from the -/// source chain to the target chain. The `AccountId` type here means the account -/// type used by the source chain. -pub trait TargetHeaderChain { - /// Proof that messages have been received by target chain. - type MessagesDeliveryProof: Parameter + Size; - - /// Verify message payload before we accept it. - /// - /// **CAUTION**: this is very important function. Incorrect implementation may lead - /// to stuck lanes and/or relayers loses. - /// - /// The proper implementation must ensure that the delivery-transaction with this - /// payload would (at least) be accepted into target chain transaction pool AND - /// eventually will be successfully mined. The most obvious incorrect implementation - /// example would be implementation for BTC chain that accepts payloads larger than - /// 1MB. BTC nodes aren't accepting transactions that are larger than 1MB, so relayer - /// will be unable to craft valid transaction => this (and all subsequent) messages will - /// never be delivered. - fn verify_message(payload: &Payload) -> Result<(), VerificationError>; - - /// Verify messages delivery proof and return lane && nonce of the latest received message. - fn verify_messages_delivery_proof( - proof: Self::MessagesDeliveryProof, - ) -> Result<(LaneId, InboundLaneData), VerificationError>; +/// - hash of finalized header; +/// +/// - storage proof of the inbound lane state; +/// +/// - lane id. +#[derive(Clone, Decode, Encode, Eq, PartialEq, RuntimeDebug, TypeInfo)] +pub struct FromBridgedChainMessagesDeliveryProof { + /// Hash of the bridge header the proof is for. + pub bridged_header_hash: BridgedHeaderHash, + /// Storage trie proof generated for [`Self::bridged_header_hash`]. + pub storage_proof: RawStorageProof, + /// Lane id of which messages were delivered and the proof is for. + pub lane: LaneId, +} + +impl Size for FromBridgedChainMessagesDeliveryProof { + fn size(&self) -> u32 { + use frame_support::sp_runtime::SaturatedConversion; + raw_storage_proof_size(&self.storage_proof).saturated_into() + } } +/// Number of messages, delivered by relayers. +pub type RelayersRewards = BTreeMap; + /// Manages payments that are happening at the source chain during delivery confirmation /// transaction. pub trait DeliveryConfirmationPayments { @@ -143,28 +137,10 @@ pub trait MessagesBridge { fn send_message(message: Self::SendMessageArgs) -> SendMessageArtifacts; } -/// Structure that may be used in place of `TargetHeaderChain` and -/// `MessageDeliveryAndDispatchPayment` on chains, where outbound messages are forbidden. +/// Structure that may be used in place `MessageDeliveryAndDispatchPayment` on chains, +/// where outbound messages are forbidden. pub struct ForbidOutboundMessages; -/// Error message that is used in `ForbidOutboundMessages` implementation. -const ALL_OUTBOUND_MESSAGES_REJECTED: &str = - "This chain is configured to reject all outbound messages"; - -impl TargetHeaderChain for ForbidOutboundMessages { - type MessagesDeliveryProof = (); - - fn verify_message(_payload: &Payload) -> Result<(), VerificationError> { - Err(VerificationError::Other(ALL_OUTBOUND_MESSAGES_REJECTED)) - } - - fn verify_messages_delivery_proof( - _proof: Self::MessagesDeliveryProof, - ) -> Result<(LaneId, InboundLaneData), VerificationError> { - Err(VerificationError::Other(ALL_OUTBOUND_MESSAGES_REJECTED)) - } -} - impl DeliveryConfirmationPayments for ForbidOutboundMessages { type Error = &'static str; diff --git a/bridges/primitives/messages/src/target_chain.rs b/bridges/primitives/messages/src/target_chain.rs index 388ce16ccdc06d3e2c42c3a094aae4d6180a0d09..74fecb9d9f0d89420d2ca54a4356e23c9130e614 100644 --- a/bridges/primitives/messages/src/target_chain.rs +++ b/bridges/primitives/messages/src/target_chain.rs @@ -16,17 +16,48 @@ //! Primitives of messages module, that are used on the target chain. -use crate::{ - LaneId, Message, MessageKey, MessageNonce, MessagePayload, OutboundLaneData, VerificationError, -}; +use crate::{LaneId, Message, MessageKey, MessageNonce, MessagePayload, OutboundLaneData}; -use bp_runtime::{messages::MessageDispatchResult, Size}; +use bp_runtime::{messages::MessageDispatchResult, raw_storage_proof_size, RawStorageProof, Size}; use codec::{Decode, Encode, Error as CodecError}; -use frame_support::{weights::Weight, Parameter}; +use frame_support::weights::Weight; use scale_info::TypeInfo; use sp_core::RuntimeDebug; use sp_std::{collections::btree_map::BTreeMap, fmt::Debug, marker::PhantomData, prelude::*}; +/// Messages proof from bridged chain. +/// +/// It contains everything required to prove that bridged (source) chain has +/// sent us some messages: +/// +/// - hash of finalized header; +/// +/// - storage proof of messages and (optionally) outbound lane state; +/// +/// - lane id; +/// +/// - nonces (inclusive range) of messages which are included in this proof. +#[derive(Clone, Decode, Encode, Eq, PartialEq, RuntimeDebug, TypeInfo)] +pub struct FromBridgedChainMessagesProof { + /// Hash of the finalized bridged header the proof is for. + pub bridged_header_hash: BridgedHeaderHash, + /// A storage trie proof of messages being delivered. + pub storage_proof: RawStorageProof, + /// Messages in this proof are sent over this lane. + pub lane: LaneId, + /// Nonce of the first message being delivered. + pub nonces_start: MessageNonce, + /// Nonce of the last message being delivered. + pub nonces_end: MessageNonce, +} + +impl Size for FromBridgedChainMessagesProof { + fn size(&self) -> u32 { + use frame_support::sp_runtime::SaturatedConversion; + raw_storage_proof_size(&self.storage_proof).saturated_into() + } +} + /// Proved messages from the source chain. pub type ProvedMessages = BTreeMap>; @@ -55,33 +86,6 @@ pub struct DispatchMessage { pub data: DispatchMessageData, } -/// Source chain API. Used by target chain, to verify source chain proofs. -/// -/// All implementations of this trait should only work with finalized data that -/// can't change. Wrong implementation may lead to invalid lane states (i.e. lane -/// that's stuck) and/or processing messages without paying fees. -pub trait SourceHeaderChain { - /// Proof that messages are sent from source chain. This may also include proof - /// of corresponding outbound lane states. - type MessagesProof: Parameter + Size; - - /// Verify messages proof and return proved messages. - /// - /// Returns error if either proof is incorrect, or the number of messages in the proof - /// is not matching the `messages_count`. - /// - /// Messages vector is required to be sorted by nonce within each lane. Out-of-order - /// messages will be rejected. - /// - /// The `messages_count` argument verification (sane limits) is supposed to be made - /// outside this function. This function only verifies that the proof declares exactly - /// `messages_count` messages. - fn verify_messages_proof( - proof: Self::MessagesProof, - messages_count: u32, - ) -> Result, VerificationError>; -} - /// Called when inbound message is received. pub trait MessageDispatch { /// Decoded message payload type. Valid message may contain invalid payload. In this case @@ -167,32 +171,11 @@ impl DeliveryPayments for () { } } -/// Structure that may be used in place of `SourceHeaderChain` and `MessageDispatch` on chains, +/// Structure that may be used in place of `MessageDispatch` on chains, /// where inbound messages are forbidden. -pub struct ForbidInboundMessages( - PhantomData<(MessagesProof, DispatchPayload)>, -); - -/// Error message that is used in `ForbidInboundMessages` implementation. -const ALL_INBOUND_MESSAGES_REJECTED: &str = - "This chain is configured to reject all inbound messages"; - -impl SourceHeaderChain - for ForbidInboundMessages -{ - type MessagesProof = MessagesProof; - - fn verify_messages_proof( - _proof: Self::MessagesProof, - _messages_count: u32, - ) -> Result, VerificationError> { - Err(VerificationError::Other(ALL_INBOUND_MESSAGES_REJECTED)) - } -} +pub struct ForbidInboundMessages(PhantomData); -impl MessageDispatch - for ForbidInboundMessages -{ +impl MessageDispatch for ForbidInboundMessages { type DispatchPayload = DispatchPayload; type DispatchLevelResult = (); diff --git a/bridges/primitives/polkadot-core/src/parachains.rs b/bridges/primitives/polkadot-core/src/parachains.rs index 433cd2845abd9ae95687d6f1d024765ee3bd2ebb..d54ee108386edf50865c500eb1062c24b01c0c3e 100644 --- a/bridges/primitives/polkadot-core/src/parachains.rs +++ b/bridges/primitives/polkadot-core/src/parachains.rs @@ -22,7 +22,7 @@ //! parachains. Having pallets that are referencing polkadot, would mean that there may //! be two versions of polkadot crates included in the runtime. Which is bad. -use bp_runtime::{RawStorageProof, Size}; +use bp_runtime::{raw_storage_proof_size, RawStorageProof, Size}; use codec::{CompactAs, Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; use sp_core::Hasher; @@ -96,11 +96,7 @@ pub struct ParaHeadsProof { impl Size for ParaHeadsProof { fn size(&self) -> u32 { - u32::try_from( - self.storage_proof - .iter() - .fold(0usize, |sum, node| sum.saturating_add(node.len())), - ) - .unwrap_or(u32::MAX) + use frame_support::sp_runtime::SaturatedConversion; + raw_storage_proof_size(&self.storage_proof).saturated_into() } } diff --git a/bridges/primitives/runtime/Cargo.toml b/bridges/primitives/runtime/Cargo.toml index 5fa35e688996f1c13ea7d94f0de5a3b9813d4574..117409b37b9457f93194585b12aabd0de00d5c7f 100644 --- a/bridges/primitives/runtime/Cargo.toml +++ b/bridges/primitives/runtime/Cargo.toml @@ -53,3 +53,4 @@ std = [ "sp-trie/std", "trie-db/std", ] +test-helpers = [] diff --git a/bridges/primitives/runtime/src/chain.rs b/bridges/primitives/runtime/src/chain.rs index 369386e41b0cf9f2d911ca40fc9e6ccfb3de6e52..0db4eac79a7500bf295756efaef514f5a4429e6c 100644 --- a/bridges/primitives/runtime/src/chain.rs +++ b/bridges/primitives/runtime/src/chain.rs @@ -24,7 +24,7 @@ use sp_runtime::{ AtLeast32Bit, AtLeast32BitUnsigned, Hash as HashT, Header as HeaderT, MaybeDisplay, MaybeSerialize, MaybeSerializeDeserialize, Member, SimpleBitOps, Verify, }, - FixedPointOperand, + FixedPointOperand, StateVersion, }; use sp_std::{fmt::Debug, hash::Hash, str::FromStr, vec, vec::Vec}; @@ -196,6 +196,10 @@ pub trait Chain: Send + Sync + 'static { /// Signature type, used on this chain. type Signature: Parameter + Verify; + /// Version of the state implementation used by this chain. This is directly related with the + /// `TrieLayout` configuration used by the storage. + const STATE_VERSION: StateVersion; + /// Get the maximum size (in bytes) of a Normal extrinsic at this chain. fn max_extrinsic_size() -> u32; /// Get the maximum weight (compute time) that a Normal extrinsic at this chain can use. @@ -223,6 +227,8 @@ where type Nonce = ::Nonce; type Signature = ::Signature; + const STATE_VERSION: StateVersion = ::STATE_VERSION; + fn max_extrinsic_size() -> u32 { ::max_extrinsic_size() } diff --git a/bridges/primitives/runtime/src/lib.rs b/bridges/primitives/runtime/src/lib.rs index d13c9b40efa0b4ddf1433fdc87ce59eb13c7d9a3..8f5040ad9a1bee5efad995b4e62d5e883dfb0c9f 100644 --- a/bridges/primitives/runtime/src/lib.rs +++ b/bridges/primitives/runtime/src/lib.rs @@ -40,15 +40,18 @@ pub use chain::{ }; pub use frame_support::storage::storage_prefix as storage_value_final_key; use num_traits::{CheckedAdd, CheckedSub, One, SaturatingAdd, Zero}; +#[cfg(feature = "std")] +pub use storage_proof::craft_valid_storage_proof; +#[cfg(feature = "test-helpers")] pub use storage_proof::{ - record_all_keys as record_all_trie_keys, Error as StorageProofError, - ProofSize as StorageProofSize, RawStorageProof, StorageProofChecker, + grow_storage_proof, grow_storage_value, record_all_keys as record_all_trie_keys, + UnverifiedStorageProofParams, +}; +pub use storage_proof::{ + raw_storage_proof_size, RawStorageProof, StorageProofChecker, StorageProofError, }; pub use storage_types::BoundedStorageValue; -#[cfg(feature = "std")] -pub use storage_proof::craft_valid_storage_proof; - pub mod extensions; pub mod messages; @@ -461,38 +464,6 @@ macro_rules! generate_static_str_provider { }; } -/// Error message that is only displayable in `std` environment. -#[derive(Encode, Decode, Clone, Eq, PartialEq, PalletError, TypeInfo)] -#[scale_info(skip_type_params(T))] -pub struct StrippableError { - _phantom_data: sp_std::marker::PhantomData, - #[codec(skip)] - #[cfg(feature = "std")] - message: String, -} - -impl From for StrippableError { - fn from(_err: T) -> Self { - Self { - _phantom_data: Default::default(), - #[cfg(feature = "std")] - message: format!("{:?}", _err), - } - } -} - -impl Debug for StrippableError { - #[cfg(feature = "std")] - fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { - f.write_str(&self.message) - } - - #[cfg(not(feature = "std"))] - fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { - f.write_str("Stripped error") - } -} - /// A trait defining helper methods for `RangeInclusive` (start..=end) pub trait RangeInclusiveExt { /// Computes the length of the `RangeInclusive`, checking for underflow and overflow. diff --git a/bridges/primitives/runtime/src/storage_proof.rs b/bridges/primitives/runtime/src/storage_proof.rs index 251ceec5a9ee7b18bce428a6e8128790e0542d29..7bfa0d6fde01186f1fe09e66dd3ba1accf286ce5 100644 --- a/bridges/primitives/runtime/src/storage_proof.rs +++ b/bridges/primitives/runtime/src/storage_proof.rs @@ -14,34 +14,91 @@ // You should have received a copy of the GNU General Public License // along with Parity Bridges Common. If not, see . -//! Logic for checking Substrate storage proofs. +//! Logic for working with storage proofs. -use crate::StrippableError; -use codec::{Decode, Encode}; use frame_support::PalletError; -use hash_db::{HashDB, Hasher, EMPTY_PREFIX}; -use scale_info::TypeInfo; -use sp_std::{boxed::Box, vec::Vec}; -pub use sp_trie::RawStorageProof; +use sp_core::RuntimeDebug; +use sp_std::{default::Default, vec::Vec}; use sp_trie::{ - accessed_nodes_tracker::{AccessedNodesTracker, Error as AccessedNodesTrackerError}, - read_trie_value, - recorder_ext::RecorderExt, - LayoutV1, MemoryDB, Recorder, StorageProof, StorageProofError, Trie, TrieConfiguration, - TrieDBBuilder, TrieError, TrieHash, + accessed_nodes_tracker::AccessedNodesTracker, read_trie_value, LayoutV1, MemoryDB, StorageProof, }; -/// Storage proof size requirements. +use codec::{Decode, Encode}; +use hash_db::{HashDB, Hasher, EMPTY_PREFIX}; +use scale_info::TypeInfo; +#[cfg(feature = "test-helpers")] +use sp_trie::{recorder_ext::RecorderExt, Recorder, TrieDBBuilder, TrieError, TrieHash}; +#[cfg(feature = "test-helpers")] +use trie_db::{Trie, TrieConfiguration, TrieDBMut}; + +/// Errors that can occur when interacting with `UnverifiedStorageProof` and `VerifiedStorageProof`. +#[derive(Clone, Encode, Decode, RuntimeDebug, PartialEq, Eq, PalletError, TypeInfo)] +pub enum StorageProofError { + /// Call to `generate_trie_proof()` failed. + UnableToGenerateTrieProof, + /// Call to `verify_trie_proof()` failed. + InvalidProof, + /// The `Vec` entries weren't sorted as expected. + UnsortedEntries, + /// The provided key wasn't found. + UnavailableKey, + /// The value associated to the provided key is `None`. + EmptyVal, + /// Error decoding value associated to a provided key. + DecodeError, + /// At least one key or node wasn't read. + UnusedKey, + + /// Expected storage root is missing from the proof. (for non-compact proofs) + StorageRootMismatch, + /// Unable to reach expected storage value using provided trie nodes. (for non-compact proofs) + StorageValueUnavailable, + /// The proof contains duplicate nodes. (for non-compact proofs) + DuplicateNodes, +} + +impl From for StorageProofError { + fn from(e: sp_trie::StorageProofError) -> Self { + match e { + sp_trie::StorageProofError::DuplicateNodes => StorageProofError::DuplicateNodes, + } + } +} + +impl From for StorageProofError { + fn from(e: sp_trie::accessed_nodes_tracker::Error) -> Self { + match e { + sp_trie::accessed_nodes_tracker::Error::UnusedNodes => StorageProofError::UnusedKey, + } + } +} + +/// Raw storage proof type (just raw trie nodes). +pub type RawStorageProof = sp_trie::RawStorageProof; + +/// Calculates size for `RawStorageProof`. +pub fn raw_storage_proof_size(raw_storage_proof: &RawStorageProof) -> usize { + raw_storage_proof + .iter() + .fold(0usize, |sum, node| sum.saturating_add(node.len())) +} + +/// Storage values size requirements. /// /// This is currently used by benchmarks when generating storage proofs. -#[derive(Clone, Copy, Debug)] -pub enum ProofSize { - /// The proof is expected to be minimal. If value size may be changed, then it is expected to - /// have given size. - Minimal(u32), - /// The proof is expected to have at least given size and grow by increasing value that is - /// stored in the trie. - HasLargeLeaf(u32), +#[cfg(feature = "test-helpers")] +#[derive(Clone, Copy, Debug, Default)] +pub struct UnverifiedStorageProofParams { + /// Expected storage proof size in bytes. + pub db_size: Option, +} + +#[cfg(feature = "test-helpers")] +impl UnverifiedStorageProofParams { + /// Make storage proof parameters that require proof of at least `db_size` bytes. + pub fn from_db_size(db_size: u32) -> Self { + Self { db_size: Some(db_size) } + } } /// This struct is used to read storage values from a subset of a Merklized database. The "proof" @@ -64,15 +121,14 @@ where /// Constructs a new storage proof checker. /// /// This returns an error if the given proof is invalid with respect to the given root. - pub fn new(root: H::Out, proof: RawStorageProof) -> Result { - let proof = StorageProof::new_with_duplicate_nodes_check(proof) - .map_err(|e| Error::StorageProof(e.into()))?; + pub fn new(root: H::Out, proof: RawStorageProof) -> Result { + let proof = StorageProof::new_with_duplicate_nodes_check(proof)?; let recorder = AccessedNodesTracker::new(proof.len()); let db = proof.into_memory_db(); if !db.contains(&root, EMPTY_PREFIX) { - return Err(Error::StorageRootMismatch) + return Err(StorageProofError::StorageRootMismatch) } Ok(StorageProofChecker { root, db, accessed_nodes_tracker: recorder }) @@ -80,15 +136,13 @@ where /// Returns error if the proof has some nodes that are left intact by previous `read_value` /// calls. - pub fn ensure_no_unused_nodes(self) -> Result<(), Error> { - self.accessed_nodes_tracker - .ensure_no_unused_nodes() - .map_err(|e| Error::AccessedNodesTracker(e.into())) + pub fn ensure_no_unused_nodes(self) -> Result<(), StorageProofError> { + self.accessed_nodes_tracker.ensure_no_unused_nodes().map_err(Into::into) } /// Reads a value from the available subset of storage. If the value cannot be read due to an /// incomplete or otherwise invalid proof, this function returns an error. - pub fn read_value(&mut self, key: &[u8]) -> Result>, Error> { + pub fn read_value(&mut self, key: &[u8]) -> Result>, StorageProofError> { // LayoutV1 or LayoutV0 is identical for proof that only read values. read_trie_value::, _>( &self.db, @@ -97,53 +151,131 @@ where Some(&mut self.accessed_nodes_tracker), None, ) - .map_err(|_| Error::StorageValueUnavailable) + .map_err(|_| StorageProofError::StorageValueUnavailable) } /// Reads and decodes a value from the available subset of storage. If the value cannot be read /// due to an incomplete or otherwise invalid proof, this function returns an error. If value is /// read, but decoding fails, this function returns an error. - pub fn read_and_decode_value(&mut self, key: &[u8]) -> Result, Error> { + pub fn read_and_decode_value( + &mut self, + key: &[u8], + ) -> Result, StorageProofError> { self.read_value(key).and_then(|v| { - v.map(|v| T::decode(&mut &v[..]).map_err(|e| Error::StorageValueDecodeFailed(e.into()))) - .transpose() + v.map(|v| { + T::decode(&mut &v[..]).map_err(|e| { + log::warn!(target: "bridge-storage-proofs", "read_and_decode_value error: {e:?}"); + StorageProofError::DecodeError + }) + }) + .transpose() }) } /// Reads and decodes a value from the available subset of storage. If the value cannot be read /// due to an incomplete or otherwise invalid proof, or if the value is `None`, this function /// returns an error. If value is read, but decoding fails, this function returns an error. - pub fn read_and_decode_mandatory_value(&mut self, key: &[u8]) -> Result { - self.read_and_decode_value(key)?.ok_or(Error::StorageValueEmpty) + pub fn read_and_decode_mandatory_value( + &mut self, + key: &[u8], + ) -> Result { + self.read_and_decode_value(key)?.ok_or(StorageProofError::EmptyVal) } /// Reads and decodes a value from the available subset of storage. If the value cannot be read /// due to an incomplete or otherwise invalid proof, this function returns `Ok(None)`. /// If value is read, but decoding fails, this function returns an error. - pub fn read_and_decode_opt_value(&mut self, key: &[u8]) -> Result, Error> { + pub fn read_and_decode_opt_value( + &mut self, + key: &[u8], + ) -> Result, StorageProofError> { match self.read_and_decode_value(key) { Ok(outbound_lane_data) => Ok(outbound_lane_data), - Err(Error::StorageValueUnavailable) => Ok(None), + Err(StorageProofError::StorageValueUnavailable) => Ok(None), Err(e) => Err(e), } } } -/// Storage proof related errors. -#[derive(Encode, Decode, Clone, Eq, PartialEq, PalletError, Debug, TypeInfo)] -pub enum Error { - /// Error generated by the `AccessedNodesTrackerError`. - AccessedNodesTracker(StrippableError), - /// Error originating in the `storage_proof` module. - StorageProof(StrippableError), - /// Expected storage root is missing from the proof. - StorageRootMismatch, - /// Unable to reach expected storage value using provided trie nodes. - StorageValueUnavailable, - /// The storage value is `None`. - StorageValueEmpty, - /// Failed to decode storage value. - StorageValueDecodeFailed(StrippableError), +/// Add extra data to the storage value so that it'll be of given size. +#[cfg(feature = "test-helpers")] +pub fn grow_storage_value(mut value: Vec, params: &UnverifiedStorageProofParams) -> Vec { + if let Some(db_size) = params.db_size { + if db_size as usize > value.len() { + value.extend(sp_std::iter::repeat(42u8).take(db_size as usize - value.len())); + } + } + value +} + +/// Insert values in the provided trie at common-prefix keys in order to inflate the resulting +/// storage proof. +/// +/// This function can add at most 15 common-prefix keys per prefix nibble (4 bits). +/// Each such key adds about 33 bytes (a node) to the proof. +#[cfg(feature = "test-helpers")] +pub fn grow_storage_proof( + trie: &mut TrieDBMut, + prefix: Vec, + num_extra_nodes: usize, +) { + use sp_trie::TrieMut; + + let mut added_nodes = 0; + for i in 0..prefix.len() { + let mut prefix = prefix[0..=i].to_vec(); + // 1 byte has 2 nibbles (4 bits each) + let first_nibble = (prefix[i] & 0xf0) >> 4; + let second_nibble = prefix[i] & 0x0f; + + // create branches at the 1st nibble + for branch in 1..=15 { + if added_nodes >= num_extra_nodes { + return + } + + // create branches at the 1st nibble + prefix[i] = (first_nibble.wrapping_add(branch) % 16) << 4; + trie.insert(&prefix, &[0; 32]) + .map_err(|_| "TrieMut::insert has failed") + .expect("TrieMut::insert should not fail in benchmarks"); + added_nodes += 1; + } + + // create branches at the 2nd nibble + for branch in 1..=15 { + if added_nodes >= num_extra_nodes { + return + } + + prefix[i] = (first_nibble << 4) | (second_nibble.wrapping_add(branch) % 16); + trie.insert(&prefix, &[0; 32]) + .map_err(|_| "TrieMut::insert has failed") + .expect("TrieMut::insert should not fail in benchmarks"); + added_nodes += 1; + } + } + + assert_eq!(added_nodes, num_extra_nodes) +} + +/// Record all keys for a given root. +#[cfg(feature = "test-helpers")] +pub fn record_all_keys( + db: &DB, + root: &TrieHash, +) -> Result>> +where + DB: hash_db::HashDBRef, +{ + let mut recorder = Recorder::::new(); + let trie = TrieDBBuilder::::new(db, root).with_recorder(&mut recorder).build(); + for x in trie.iter()? { + let (key, _) = x?; + trie.get(&key)?; + } + + Ok(recorder.into_raw_storage_proof()) } /// Return valid storage proof and state root. @@ -157,7 +289,7 @@ pub fn craft_valid_storage_proof() -> (sp_core::H256, RawStorageProof) { // construct storage proof let backend = >::from(( - vec![ + sp_std::vec![ (None, vec![(b"key1".to_vec(), Some(b"value1".to_vec()))]), (None, vec![(b"key2".to_vec(), Some(b"value2".to_vec()))]), (None, vec![(b"key3".to_vec(), Some(b"value3".to_vec()))]), @@ -167,33 +299,15 @@ pub fn craft_valid_storage_proof() -> (sp_core::H256, RawStorageProof) { ], state_version, )); - let root = backend.storage_root(std::iter::empty(), state_version).0; + let root = backend.storage_root(sp_std::iter::empty(), state_version).0; let proof = prove_read(backend, &[&b"key1"[..], &b"key2"[..], &b"key4"[..], &b"key22"[..]]).unwrap(); (root, proof.into_nodes().into_iter().collect()) } -/// Record all keys for a given root. -pub fn record_all_keys( - db: &DB, - root: &TrieHash, -) -> Result>> -where - DB: hash_db::HashDBRef, -{ - let mut recorder = Recorder::::new(); - let trie = TrieDBBuilder::::new(db, root).with_recorder(&mut recorder).build(); - for x in trie.iter()? { - let (key, _) = x?; - trie.get(&key)?; - } - - Ok(recorder.into_raw_storage_proof()) -} - #[cfg(test)] -pub mod tests { +pub mod tests_for_storage_proof_checker { use super::*; use codec::Encode; @@ -207,18 +321,21 @@ pub mod tests { assert_eq!(checker.read_value(b"key1"), Ok(Some(b"value1".to_vec()))); assert_eq!(checker.read_value(b"key2"), Ok(Some(b"value2".to_vec()))); assert_eq!(checker.read_value(b"key4"), Ok(Some((42u64, 42u32, 42u16, 42u8).encode()))); - assert_eq!(checker.read_value(b"key11111"), Err(Error::StorageValueUnavailable)); + assert_eq!( + checker.read_value(b"key11111"), + Err(StorageProofError::StorageValueUnavailable) + ); assert_eq!(checker.read_value(b"key22"), Ok(None)); assert_eq!(checker.read_and_decode_value(b"key4"), Ok(Some((42u64, 42u32, 42u16, 42u8))),); assert!(matches!( checker.read_and_decode_value::<[u8; 64]>(b"key4"), - Err(Error::StorageValueDecodeFailed(_)), + Err(StorageProofError::DecodeError), )); // checking proof against invalid commitment fails assert_eq!( >::new(sp_core::H256::random(), proof).err(), - Some(Error::StorageRootMismatch) + Some(StorageProofError::StorageRootMismatch) ); } @@ -235,9 +352,6 @@ pub mod tests { assert_eq!(checker.ensure_no_unused_nodes(), Ok(())); let checker = StorageProofChecker::::new(root, proof).unwrap(); - assert_eq!( - checker.ensure_no_unused_nodes(), - Err(Error::AccessedNodesTracker(AccessedNodesTrackerError::UnusedNodes.into())) - ); + assert_eq!(checker.ensure_no_unused_nodes(), Err(StorageProofError::UnusedKey)); } } diff --git a/bridges/primitives/test-utils/Cargo.toml b/bridges/primitives/test-utils/Cargo.toml index 0b7fb3fec077df6187ded588011cf99a64c588f0..5e6e3893393534aa828f323d8a28748742a7b5bb 100644 --- a/bridges/primitives/test-utils/Cargo.toml +++ b/bridges/primitives/test-utils/Cargo.toml @@ -14,7 +14,7 @@ workspace = true bp-header-chain = { workspace = true } bp-parachains = { workspace = true } bp-polkadot-core = { workspace = true } -bp-runtime = { workspace = true } +bp-runtime = { features = ["test-helpers"], workspace = true } codec = { workspace = true } ed25519-dalek = { workspace = true } finality-grandpa = { workspace = true } diff --git a/bridges/primitives/test-utils/src/lib.rs b/bridges/primitives/test-utils/src/lib.rs index f4fe4a242e79c0e1c8a499c4dd18ed4a2164c656..9855c32a468954dd0f3011c029c793e5cd2cbc35 100644 --- a/bridges/primitives/test-utils/src/lib.rs +++ b/bridges/primitives/test-utils/src/lib.rs @@ -177,6 +177,7 @@ pub fn prepare_parachain_heads_proof( let mut parachains = Vec::with_capacity(heads.len()); let mut root = Default::default(); let mut mdb = MemoryDB::default(); + let mut storage_keys = vec![]; { let mut trie = TrieDBMutBuilderV1::::new(&mut mdb, &mut root).build(); for (parachain, head) in heads { @@ -185,11 +186,12 @@ pub fn prepare_parachain_heads_proof( trie.insert(&storage_key.0, &head.encode()) .map_err(|_| "TrieMut::insert has failed") .expect("TrieMut::insert should not fail in tests"); + storage_keys.push(storage_key.0); parachains.push((ParaId(parachain), head.hash())); } } - // generate storage proof to be delivered to This chain + // generate storage proof to be delivered to this chain let storage_proof = record_all_trie_keys::, _>(&mdb, &root) .map_err(|_| "record_all_trie_keys has failed") .expect("record_all_trie_keys should not fail in benchmarks"); diff --git a/bridges/relays/client-substrate/Cargo.toml b/bridges/relays/client-substrate/Cargo.toml index 66501d03691a949431c15060a398f1fd1c3cfa5f..969cd73d6194fcf42e03f54ae14029cfdf73d877 100644 --- a/bridges/relays/client-substrate/Cargo.toml +++ b/bridges/relays/client-substrate/Cargo.toml @@ -31,15 +31,12 @@ bp-header-chain = { workspace = true, default-features = true } bp-messages = { workspace = true, default-features = true } bp-polkadot-core = { workspace = true, default-features = true } bp-runtime = { workspace = true, default-features = true } -pallet-bridge-messages = { workspace = true, default-features = true } finality-relay = { workspace = true } relay-utils = { workspace = true } # Substrate Dependencies frame-support = { workspace = true, default-features = true } -frame-system = { workspace = true, default-features = true } -pallet-balances = { workspace = true, default-features = true } pallet-transaction-payment = { workspace = true, default-features = true } pallet-transaction-payment-rpc-runtime-api = { workspace = true, default-features = true } pallet-utility = { workspace = true, default-features = true } diff --git a/bridges/relays/client-substrate/src/client/caching.rs b/bridges/relays/client-substrate/src/client/caching.rs index cb898cf517267a173b0ef4daf374c5b16b0757ba..a574e5985bc8280e030cfad08308a2c9bebe33a4 100644 --- a/bridges/relays/client-substrate/src/client/caching.rs +++ b/bridges/relays/client-substrate/src/client/caching.rs @@ -462,7 +462,11 @@ impl> Client for CachingClient { .await } - async fn prove_storage(&self, at: HashOf, keys: Vec) -> Result { + async fn prove_storage( + &self, + at: HashOf, + keys: Vec, + ) -> Result<(StorageProof, HashOf)> { self.backend.prove_storage(at, keys).await } } diff --git a/bridges/relays/client-substrate/src/client/rpc.rs b/bridges/relays/client-substrate/src/client/rpc.rs index bf7442a95141ff168229bffbc149f686d6b2771a..9c7f769462e5693bc944ed6a6525439f00311ee7 100644 --- a/bridges/relays/client-substrate/src/client/rpc.rs +++ b/bridges/relays/client-substrate/src/client/rpc.rs @@ -52,7 +52,10 @@ use sp_core::{ storage::{StorageData, StorageKey}, Bytes, Hasher, Pair, }; -use sp_runtime::transaction_validity::{TransactionSource, TransactionValidity}; +use sp_runtime::{ + traits::Header, + transaction_validity::{TransactionSource, TransactionValidity}, +}; use sp_trie::StorageProof; use sp_version::RuntimeVersion; use std::{cmp::Ordering, future::Future, marker::PhantomData}; @@ -635,16 +638,25 @@ impl Client for RpcClient { .map_err(|e| Error::failed_state_call::(at, method_clone, arguments_clone, e)) } - async fn prove_storage(&self, at: HashOf, keys: Vec) -> Result { + async fn prove_storage( + &self, + at: HashOf, + keys: Vec, + ) -> Result<(StorageProof, HashOf)> { + let state_root = *self.header_by_hash(at).await?.state_root(); + let keys_clone = keys.clone(); - self.jsonrpsee_execute(move |client| async move { - SubstrateStateClient::::prove_storage(&*client, keys, Some(at)) - .await - .map(|proof| StorageProof::new(proof.proof.into_iter().map(|b| b.0))) - .map_err(Into::into) - }) - .await - .map_err(|e| Error::failed_to_prove_storage::(at, keys_clone, e)) + let read_proof = self + .jsonrpsee_execute(move |client| async move { + SubstrateStateClient::::prove_storage(&*client, keys_clone, Some(at)) + .await + .map(|proof| StorageProof::new(proof.proof.into_iter().map(|b| b.0))) + .map_err(Into::into) + }) + .await + .map_err(|e| Error::failed_to_prove_storage::(at, keys.clone(), e))?; + + Ok((read_proof, state_root)) } } diff --git a/bridges/relays/client-substrate/src/client/traits.rs b/bridges/relays/client-substrate/src/client/traits.rs index 49f5c001c3f7d80fd51892c8de73f41960557cba..6f4ef5aa951062ddd6586e0dadeb4ce7425eca5e 100644 --- a/bridges/relays/client-substrate/src/client/traits.rs +++ b/bridges/relays/client-substrate/src/client/traits.rs @@ -225,6 +225,10 @@ pub trait Client: 'static + Send + Sync + Clone + Debug { }) } - /// Returns storage proof of given storage keys. - async fn prove_storage(&self, at: HashOf, keys: Vec) -> Result; + /// Returns storage proof of given storage keys and state root. + async fn prove_storage( + &self, + at: HashOf, + keys: Vec, + ) -> Result<(StorageProof, HashOf)>; } diff --git a/bridges/relays/client-substrate/src/error.rs b/bridges/relays/client-substrate/src/error.rs index b09e2c7abdc666735d7481d3f39c9492d851f76a..ee3c73f806e65362a10185d5dd9090f5bbc4c300 100644 --- a/bridges/relays/client-substrate/src/error.rs +++ b/bridges/relays/client-substrate/src/error.rs @@ -213,9 +213,6 @@ pub enum Error { /// The bridge pallet is not yet initialized and all transactions will be rejected. #[error("Bridge pallet is not initialized.")] BridgePalletIsNotInitialized, - /// An error has happened when we have tried to parse storage proof. - #[error("Error when parsing storage proof: {0:?}.")] - StorageProofError(bp_runtime::StorageProofError), /// The Substrate transaction is invalid. #[error("Substrate transaction is invalid: {0:?}")] TransactionInvalid(#[from] TransactionValidityError), diff --git a/bridges/relays/client-substrate/src/test_chain.rs b/bridges/relays/client-substrate/src/test_chain.rs index cfd241c022a269da799e8e03c4398566d98a14a0..991202e9874c790e404b42b74102248cb5f6723f 100644 --- a/bridges/relays/client-substrate/src/test_chain.rs +++ b/bridges/relays/client-substrate/src/test_chain.rs @@ -24,7 +24,7 @@ use crate::{Chain, ChainWithBalances, ChainWithMessages}; use bp_messages::{ChainWithMessages as ChainWithMessagesBase, MessageNonce}; use bp_runtime::ChainId; -use frame_support::weights::Weight; +use frame_support::{sp_runtime::StateVersion, weights::Weight}; use std::time::Duration; /// Chain that may be used in tests. @@ -44,6 +44,8 @@ impl bp_runtime::Chain for TestChain { type Nonce = u32; type Signature = sp_runtime::testing::TestSignature; + const STATE_VERSION: StateVersion = StateVersion::V1; + fn max_extrinsic_size() -> u32 { 100000 } @@ -100,6 +102,8 @@ impl bp_runtime::Chain for TestParachainBase { type Nonce = u32; type Signature = sp_runtime::testing::TestSignature; + const STATE_VERSION: StateVersion = StateVersion::V1; + fn max_extrinsic_size() -> u32 { unreachable!() } diff --git a/bridges/relays/finality/src/base.rs b/bridges/relays/finality/src/base.rs index 4253468eaace1ef2a2adc47790f7e16c38160200..8704bff95494a88274f0e78f5df53aa15708cccf 100644 --- a/bridges/relays/finality/src/base.rs +++ b/bridges/relays/finality/src/base.rs @@ -45,7 +45,3 @@ pub trait SourceClientBase: RelayClient { /// Subscribe to new finality proofs. async fn finality_proofs(&self) -> Result; } - -/// Target client used in finality related loops. -#[async_trait] -pub trait TargetClientBase: RelayClient {} diff --git a/bridges/relays/lib-substrate-relay/Cargo.toml b/bridges/relays/lib-substrate-relay/Cargo.toml index 28fee5b167ffab3249a5feb96ff04c991e2fc311..b0f93e5b5485f24b230b9b2868c6301b6ed64181 100644 --- a/bridges/relays/lib-substrate-relay/Cargo.toml +++ b/bridges/relays/lib-substrate-relay/Cargo.toml @@ -25,15 +25,12 @@ strum = { features = ["derive"], workspace = true, default-features = true } thiserror = { workspace = true } # Bridge dependencies - bp-header-chain = { workspace = true, default-features = true } bp-parachains = { workspace = true, default-features = true } bp-polkadot-core = { workspace = true, default-features = true } bp-relayers = { workspace = true, default-features = true } -bridge-runtime-common = { workspace = true, default-features = true } equivocation-detector = { workspace = true } -finality-grandpa = { workspace = true, default-features = true } finality-relay = { workspace = true } parachains-relay = { workspace = true } relay-utils = { workspace = true } @@ -48,7 +45,6 @@ bp-runtime = { workspace = true, default-features = true } bp-messages = { workspace = true, default-features = true } # Substrate Dependencies - frame-support = { workspace = true, default-features = true } frame-system = { workspace = true, default-features = true } pallet-balances = { workspace = true, default-features = true } @@ -56,7 +52,9 @@ pallet-grandpa = { workspace = true, default-features = true } sp-core = { workspace = true, default-features = true } sp-consensus-grandpa = { workspace = true, default-features = true } sp-runtime = { workspace = true, default-features = true } +sp-trie = { workspace = true } [dev-dependencies] +scale-info = { features = ["derive"], workspace = true } pallet-transaction-payment = { workspace = true, default-features = true } relay-substrate-client = { features = ["test-helpers"], workspace = true } diff --git a/bridges/relays/lib-substrate-relay/src/cli/bridge.rs b/bridges/relays/lib-substrate-relay/src/cli/bridge.rs index 316f59a2b0c86e1bc78c1446bb69a90b0b0bf0f7..5631285b3c544de0e3caf85a6b74b7ee31601c56 100644 --- a/bridges/relays/lib-substrate-relay/src/cli/bridge.rs +++ b/bridges/relays/lib-substrate-relay/src/cli/bridge.rs @@ -19,7 +19,7 @@ use crate::{ equivocation::SubstrateEquivocationDetectionPipeline, finality::SubstrateFinalitySyncPipeline, - messages_lane::{MessagesRelayLimits, SubstrateMessageLane}, + messages::{MessagesRelayLimits, SubstrateMessageLane}, parachains::SubstrateParachainsPipeline, }; use pallet_bridge_parachains::{RelayBlockHash, RelayBlockHasher, RelayBlockNumber}; diff --git a/bridges/relays/lib-substrate-relay/src/cli/relay_headers_and_messages/mod.rs b/bridges/relays/lib-substrate-relay/src/cli/relay_headers_and_messages/mod.rs index 05a061c2ea606b79464908a6af46ed75af7d80ee..338dda3c63309acbefd2616d052ae5dc4bf1d1e0 100644 --- a/bridges/relays/lib-substrate-relay/src/cli/relay_headers_and_messages/mod.rs +++ b/bridges/relays/lib-substrate-relay/src/cli/relay_headers_and_messages/mod.rs @@ -38,7 +38,7 @@ use futures::{FutureExt, TryFutureExt}; use crate::{ cli::{bridge::MessagesCliBridge, DefaultClient, HexLaneId, PrometheusParams}, - messages_lane::{MessagesRelayLimits, MessagesRelayParams}, + messages::{MessagesRelayLimits, MessagesRelayParams}, on_demand::OnDemandRelay, HeadersToRelay, TaggedAccount, TransactionParams, }; @@ -298,14 +298,14 @@ where .collect::>(); { let common = self.mut_base().mut_common(); - crate::messages_metrics::add_relay_balances_metrics::<_, Self::Right>( + crate::messages::metrics::add_relay_balances_metrics::<_, Self::Right>( common.left.client.clone(), &common.metrics_params, &common.left.accounts, &lanes, ) .await?; - crate::messages_metrics::add_relay_balances_metrics::<_, Self::Left>( + crate::messages::metrics::add_relay_balances_metrics::<_, Self::Left>( common.right.client.clone(), &common.metrics_params, &common.right.accounts, @@ -318,7 +318,7 @@ where let mut message_relays = Vec::with_capacity(lanes.len() * 2); for lane in lanes { let left_to_right_messages = - crate::messages_lane::run::<::MessagesLane, _, _>( + crate::messages::run::<::MessagesLane, _, _>( self.left_to_right().messages_relay_params( left_to_right_on_demand_headers.clone(), right_to_left_on_demand_headers.clone(), @@ -331,7 +331,7 @@ where message_relays.push(left_to_right_messages); let right_to_left_messages = - crate::messages_lane::run::<::MessagesLane, _, _>( + crate::messages::run::<::MessagesLane, _, _>( self.right_to_left().messages_relay_params( right_to_left_on_demand_headers.clone(), left_to_right_on_demand_headers.clone(), diff --git a/bridges/relays/lib-substrate-relay/src/cli/relay_messages.rs b/bridges/relays/lib-substrate-relay/src/cli/relay_messages.rs index a17ae7c0c01f9b828d8a534da8143a1d983892c2..68bbe71ae599c901bdf7a9b6e55cf93c020adbb6 100644 --- a/bridges/relays/lib-substrate-relay/src/cli/relay_messages.rs +++ b/bridges/relays/lib-substrate-relay/src/cli/relay_messages.rs @@ -18,7 +18,7 @@ use crate::{ cli::{bridge::*, chain_schema::*, HexLaneId, PrometheusParams}, - messages_lane::MessagesRelayParams, + messages::MessagesRelayParams, TransactionParams, }; @@ -117,7 +117,7 @@ where let target_sign = data.target_sign.to_keypair::()?; let target_transactions_mortality = data.target_sign.transactions_mortality()?; - crate::messages_lane::run::(MessagesRelayParams { + crate::messages::run::(MessagesRelayParams { source_client, source_transaction_params: TransactionParams { signer: source_sign, @@ -161,7 +161,7 @@ where })? .id(); - crate::messages_lane::relay_messages_range::( + crate::messages::relay_messages_range::( source_client, target_client, TransactionParams { signer: source_sign, mortality: source_transactions_mortality }, @@ -197,7 +197,7 @@ where })? .id(); - crate::messages_lane::relay_messages_delivery_confirmation::( + crate::messages::relay_messages_delivery_confirmation::( source_client, target_client, TransactionParams { signer: source_sign, mortality: source_transactions_mortality }, diff --git a/bridges/relays/lib-substrate-relay/src/lib.rs b/bridges/relays/lib-substrate-relay/src/lib.rs index b3e8e7ed9a2059bb07134640aa4e0bc98494a6a1..c004540a9f4951f3aeeb43a91c74da68a3ff1064 100644 --- a/bridges/relays/lib-substrate-relay/src/lib.rs +++ b/bridges/relays/lib-substrate-relay/src/lib.rs @@ -30,10 +30,7 @@ pub mod equivocation; pub mod error; pub mod finality; pub mod finality_base; -pub mod messages_lane; -pub mod messages_metrics; -pub mod messages_source; -pub mod messages_target; +pub mod messages; pub mod on_demand; pub mod parachains; @@ -130,3 +127,17 @@ impl BatchCallBuilder for () { unreachable!("never called, because ()::new_builder() returns None; qed") } } + +/// Module for handling storage proofs compatibility. +pub mod proofs { + use bp_runtime::{HashOf, RawStorageProof}; + use relay_substrate_client::Chain; + use sp_trie::StorageProof; + + /// Converts proof to `RawStorageProof` type. + pub fn to_raw_storage_proof( + proof: (StorageProof, HashOf), + ) -> RawStorageProof { + proof.0.into_iter_nodes().collect() + } +} diff --git a/bridges/relays/lib-substrate-relay/src/messages_metrics.rs b/bridges/relays/lib-substrate-relay/src/messages/metrics.rs similarity index 100% rename from bridges/relays/lib-substrate-relay/src/messages_metrics.rs rename to bridges/relays/lib-substrate-relay/src/messages/metrics.rs diff --git a/bridges/relays/lib-substrate-relay/src/messages_lane.rs b/bridges/relays/lib-substrate-relay/src/messages/mod.rs similarity index 63% rename from bridges/relays/lib-substrate-relay/src/messages_lane.rs rename to bridges/relays/lib-substrate-relay/src/messages/mod.rs index e3786dcdc5e31dad2cdf00ba2db073adb87f78b2..e52b7020666941c9a8d9937655496acf451c5379 100644 --- a/bridges/relays/lib-substrate-relay/src/messages_lane.rs +++ b/bridges/relays/lib-substrate-relay/src/messages/mod.rs @@ -17,20 +17,21 @@ //! Tools for supporting message lanes between two Substrate-based chains. use crate::{ - messages_source::{SubstrateMessagesProof, SubstrateMessagesSource}, - messages_target::{SubstrateMessagesDeliveryProof, SubstrateMessagesTarget}, + messages::{ + source::{SubstrateMessagesProof, SubstrateMessagesSource}, + target::{SubstrateMessagesDeliveryProof, SubstrateMessagesTarget}, + }, on_demand::OnDemandRelay, BatchCallBuilder, BatchCallBuilderConstructor, TransactionParams, }; use async_std::sync::Arc; -use bp_messages::{ChainWithMessages as _, LaneId, MessageNonce}; +use bp_messages::{ + target_chain::FromBridgedChainMessagesProof, ChainWithMessages as _, LaneId, MessageNonce, +}; use bp_runtime::{ AccountIdOf, Chain as _, EncodedOrDecodedCall, HeaderIdOf, TransactionEra, WeightExtraOps, }; -use bridge_runtime_common::messages::{ - source::FromBridgedChainMessagesDeliveryProof, target::FromBridgedChainMessagesProof, -}; use codec::Encode; use frame_support::{dispatch::GetDispatchInfo, weights::Weight}; use messages_relay::{message_lane::MessageLane, message_lane_loop::BatchTransaction}; @@ -48,6 +49,10 @@ use sp_core::Pair; use sp_runtime::traits::Zero; use std::{fmt::Debug, marker::PhantomData, ops::RangeInclusive}; +pub mod metrics; +pub mod source; +pub mod target; + /// Substrate -> Substrate messages synchronization pipeline. pub trait SubstrateMessageLane: 'static + Clone + Debug + Send + Sync { /// Messages of this chain are relayed to the `TargetChain`. @@ -383,11 +388,10 @@ pub struct DirectReceiveMessagesProofCallBuilder { impl ReceiveMessagesProofCallBuilder

for DirectReceiveMessagesProofCallBuilder where P: SubstrateMessageLane, - R: BridgeMessagesConfig>, + R: BridgeMessagesConfig, I: 'static, - R::SourceHeaderChain: bp_messages::target_chain::SourceHeaderChain< - MessagesProof = FromBridgedChainMessagesProof>, - >, + R::BridgedChain: + bp_runtime::Chain, Hash = HashOf>, CallOf: From> + GetDispatchInfo, { fn build_receive_messages_proof_call( @@ -399,7 +403,7 @@ where ) -> CallOf { let call: CallOf = BridgeMessagesCall::::receive_messages_proof { relayer_id_at_bridged_chain: relayer_id_at_source, - proof: proof.1, + proof: proof.1.into(), messages_count, dispatch_weight, } @@ -432,26 +436,26 @@ macro_rules! generate_receive_message_proof_call_builder { ($pipeline:ident, $mocked_builder:ident, $bridge_messages:path, $receive_messages_proof:path) => { pub struct $mocked_builder; - impl $crate::messages_lane::ReceiveMessagesProofCallBuilder<$pipeline> + impl $crate::messages::ReceiveMessagesProofCallBuilder<$pipeline> for $mocked_builder { fn build_receive_messages_proof_call( relayer_id_at_source: relay_substrate_client::AccountIdOf< - <$pipeline as $crate::messages_lane::SubstrateMessageLane>::SourceChain + <$pipeline as $crate::messages::SubstrateMessageLane>::SourceChain >, - proof: $crate::messages_source::SubstrateMessagesProof< - <$pipeline as $crate::messages_lane::SubstrateMessageLane>::SourceChain + proof: $crate::messages::source::SubstrateMessagesProof< + <$pipeline as $crate::messages::SubstrateMessageLane>::SourceChain >, messages_count: u32, dispatch_weight: bp_messages::Weight, _trace_call: bool, ) -> relay_substrate_client::CallOf< - <$pipeline as $crate::messages_lane::SubstrateMessageLane>::TargetChain + <$pipeline as $crate::messages::SubstrateMessageLane>::TargetChain > { bp_runtime::paste::item! { $bridge_messages($receive_messages_proof { relayer_id_at_bridged_chain: relayer_id_at_source, - proof: proof.1, + proof: proof.1.into(), messages_count: messages_count, dispatch_weight: dispatch_weight, }) @@ -483,11 +487,7 @@ where P: SubstrateMessageLane, R: BridgeMessagesConfig, I: 'static, - R::TargetHeaderChain: bp_messages::source_chain::TargetHeaderChain< - R::OutboundPayload, - R::AccountId, - MessagesDeliveryProof = FromBridgedChainMessagesDeliveryProof>, - >, + R::BridgedChain: bp_runtime::Chain>, CallOf: From> + GetDispatchInfo, { fn build_receive_messages_delivery_proof_call( @@ -496,7 +496,7 @@ where ) -> CallOf { let call: CallOf = BridgeMessagesCall::::receive_messages_delivery_proof { - proof: proof.1, + proof: proof.1.into(), relayers_state: proof.0, } .into(); @@ -528,16 +528,16 @@ macro_rules! generate_receive_message_delivery_proof_call_builder { ($pipeline:ident, $mocked_builder:ident, $bridge_messages:path, $receive_messages_delivery_proof:path) => { pub struct $mocked_builder; - impl $crate::messages_lane::ReceiveMessagesDeliveryProofCallBuilder<$pipeline> + impl $crate::messages::ReceiveMessagesDeliveryProofCallBuilder<$pipeline> for $mocked_builder { fn build_receive_messages_delivery_proof_call( - proof: $crate::messages_target::SubstrateMessagesDeliveryProof< - <$pipeline as $crate::messages_lane::SubstrateMessageLane>::TargetChain + proof: $crate::messages::target::SubstrateMessagesDeliveryProof< + <$pipeline as $crate::messages::SubstrateMessageLane>::TargetChain >, _trace_call: bool, ) -> relay_substrate_client::CallOf< - <$pipeline as $crate::messages_lane::SubstrateMessageLane>::SourceChain + <$pipeline as $crate::messages::SubstrateMessageLane>::SourceChain > { bp_runtime::paste::item! { $bridge_messages($receive_messages_delivery_proof { @@ -643,13 +643,7 @@ where Weight::zero(), FromBridgedChainMessagesProof { bridged_header_hash: Default::default(), - // we may use per-chain `EXTRA_STORAGE_PROOF_SIZE`, but since we don't need - // exact values, this global estimation is fine - storage_proof: vec![vec![ - 42u8; - pallet_bridge_messages::EXTRA_STORAGE_PROOF_SIZE - as usize - ]], + storage_proof: Default::default(), lane: Default::default(), nonces_start: 1, nonces_end: messages as u64, @@ -675,3 +669,362 @@ where ) .map_err(Into::into) } + +#[cfg(test)] +mod tests { + use super::*; + use bp_messages::{ + source_chain::FromBridgedChainMessagesDeliveryProof, UnrewardedRelayersState, + }; + use relay_substrate_client::calls::{UtilityCall as MockUtilityCall, UtilityCall}; + + #[derive(codec::Decode, codec::Encode, Clone, Debug, PartialEq)] + pub enum RuntimeCall { + #[codec(index = 53)] + BridgeMessages(CodegenBridgeMessagesCall), + #[codec(index = 123)] + Utility(UtilityCall), + } + pub type CodegenBridgeMessagesCall = bp_messages::BridgeMessagesCall< + u64, + Box>, + FromBridgedChainMessagesDeliveryProof, + >; + + impl From> for RuntimeCall { + fn from(value: MockUtilityCall) -> RuntimeCall { + match value { + MockUtilityCall::batch_all(calls) => + RuntimeCall::Utility(UtilityCall::::batch_all(calls)), + } + } + } + + #[test] + fn ensure_macro_compatibility_for_generate_receive_message_proof_call_builder() { + // data + let receive_messages_proof = FromBridgedChainMessagesProof { + bridged_header_hash: Default::default(), + storage_proof: Default::default(), + lane: LaneId([0, 0, 0, 0]), + nonces_start: 0, + nonces_end: 0, + }; + let account = 1234; + let messages_count = 0; + let dispatch_weight = Default::default(); + + // construct pallet Call directly + let pallet_receive_messages_proof = + pallet_bridge_messages::Call::::receive_messages_proof { + relayer_id_at_bridged_chain: account, + proof: receive_messages_proof.clone().into(), + messages_count, + dispatch_weight, + }; + + // construct mock enum Call + let mock_enum_receive_messages_proof = CodegenBridgeMessagesCall::receive_messages_proof { + relayer_id_at_bridged_chain: account, + proof: receive_messages_proof.clone().into(), + messages_count, + dispatch_weight, + }; + + // now we should be able to use macro `generate_receive_message_proof_call_builder` + let relayer_call_builder_receive_messages_proof = relayer::ThisChainToBridgedChainMessageLaneReceiveMessagesProofCallBuilder::build_receive_messages_proof_call( + account, + (Default::default(), receive_messages_proof), + messages_count, + dispatch_weight, + false, + ); + + // ensure they are all equal + assert_eq!( + pallet_receive_messages_proof.encode(), + mock_enum_receive_messages_proof.encode() + ); + match relayer_call_builder_receive_messages_proof { + RuntimeCall::BridgeMessages(call) => match call { + call @ CodegenBridgeMessagesCall::receive_messages_proof { .. } => + assert_eq!(pallet_receive_messages_proof.encode(), call.encode()), + _ => panic!("Unexpected CodegenBridgeMessagesCall type"), + }, + _ => panic!("Unexpected RuntimeCall type"), + }; + } + + #[test] + fn ensure_macro_compatibility_for_generate_receive_message_delivery_proof_call_builder() { + // data + let receive_messages_delivery_proof = FromBridgedChainMessagesDeliveryProof { + bridged_header_hash: Default::default(), + storage_proof: Default::default(), + lane: LaneId([0, 0, 0, 0]), + }; + let relayers_state = UnrewardedRelayersState { + unrewarded_relayer_entries: 0, + messages_in_oldest_entry: 0, + total_messages: 0, + last_delivered_nonce: 0, + }; + + // construct pallet Call directly + let pallet_receive_messages_delivery_proof = + pallet_bridge_messages::Call::::receive_messages_delivery_proof { + proof: receive_messages_delivery_proof.clone(), + relayers_state: relayers_state.clone(), + }; + + // construct mock enum Call + let mock_enum_receive_messages_delivery_proof = + CodegenBridgeMessagesCall::receive_messages_delivery_proof { + proof: receive_messages_delivery_proof.clone(), + relayers_state: relayers_state.clone(), + }; + + // now we should be able to use macro `generate_receive_message_proof_call_builder` + let relayer_call_builder_receive_messages_delivery_proof = relayer::ThisChainToBridgedChainMessageLaneReceiveMessagesDeliveryProofCallBuilder::build_receive_messages_delivery_proof_call( + (relayers_state, receive_messages_delivery_proof), + false, + ); + + // ensure they are all equal + assert_eq!( + pallet_receive_messages_delivery_proof.encode(), + mock_enum_receive_messages_delivery_proof.encode() + ); + match relayer_call_builder_receive_messages_delivery_proof { + RuntimeCall::BridgeMessages(call) => match call { + call @ CodegenBridgeMessagesCall::receive_messages_delivery_proof { .. } => + assert_eq!(pallet_receive_messages_delivery_proof.encode(), call.encode()), + _ => panic!("Unexpected CodegenBridgeMessagesCall type"), + }, + _ => panic!("Unexpected RuntimeCall type"), + }; + } + + // mock runtime with `pallet_bridge_messages` + mod mock { + use super::super::*; + use bp_messages::target_chain::ForbidInboundMessages; + use bp_runtime::ChainId; + use frame_support::derive_impl; + use sp_core::H256; + use sp_runtime::{ + generic, testing::Header as SubstrateHeader, traits::BlakeTwo256, StateVersion, + }; + + type Block = frame_system::mocking::MockBlock; + pub type SignedBlock = generic::SignedBlock; + + frame_support::construct_runtime! { + pub enum TestRuntime + { + System: frame_system, + Messages: pallet_bridge_messages, + } + } + + #[derive_impl(frame_system::config_preludes::TestDefaultConfig)] + impl frame_system::Config for TestRuntime { + type Block = Block; + } + + impl pallet_bridge_messages::Config for TestRuntime { + type RuntimeEvent = RuntimeEvent; + type WeightInfo = (); + type ThisChain = ThisUnderlyingChain; + type BridgedChain = BridgedUnderlyingChain; + type BridgedHeaderChain = BridgedHeaderChain; + type ActiveOutboundLanes = (); + type OutboundPayload = Vec; + type InboundPayload = Vec; + type DeliveryPayments = (); + type DeliveryConfirmationPayments = (); + type OnMessagesDelivered = (); + type MessageDispatch = ForbidInboundMessages>; + } + + pub struct ThisUnderlyingChain; + + impl bp_runtime::Chain for ThisUnderlyingChain { + const ID: ChainId = *b"tuch"; + type BlockNumber = u64; + type Hash = H256; + type Hasher = BlakeTwo256; + type Header = SubstrateHeader; + type AccountId = u64; + type Balance = u64; + type Nonce = u64; + type Signature = sp_runtime::MultiSignature; + const STATE_VERSION: StateVersion = StateVersion::V1; + fn max_extrinsic_size() -> u32 { + u32::MAX + } + fn max_extrinsic_weight() -> Weight { + Weight::MAX + } + } + + impl bp_messages::ChainWithMessages for ThisUnderlyingChain { + const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str = ""; + const MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX: MessageNonce = 16; + const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce = 1000; + } + + pub struct BridgedUnderlyingChain; + + pub type BridgedHeaderHash = H256; + pub type BridgedChainHeader = SubstrateHeader; + + impl bp_runtime::Chain for BridgedUnderlyingChain { + const ID: ChainId = *b"bgdc"; + type BlockNumber = u64; + type Hash = BridgedHeaderHash; + type Hasher = BlakeTwo256; + type Header = BridgedChainHeader; + type AccountId = u64; + type Balance = u64; + type Nonce = u64; + type Signature = sp_runtime::MultiSignature; + const STATE_VERSION: StateVersion = StateVersion::V1; + fn max_extrinsic_size() -> u32 { + 4096 + } + fn max_extrinsic_weight() -> Weight { + Weight::MAX + } + } + + impl bp_messages::ChainWithMessages for BridgedUnderlyingChain { + const WITH_CHAIN_MESSAGES_PALLET_NAME: &'static str = ""; + const MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX: MessageNonce = 16; + const MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX: MessageNonce = 1000; + } + + pub struct BridgedHeaderChain; + + impl bp_header_chain::HeaderChain for BridgedHeaderChain { + fn finalized_header_state_root( + _hash: HashOf, + ) -> Option> { + unreachable!() + } + } + } + + // relayer configuration + mod relayer { + use super::*; + use crate::{ + messages::{ + tests::{mock, RuntimeCall}, + SubstrateMessageLane, + }, + UtilityPalletBatchCallBuilder, + }; + use bp_runtime::UnderlyingChainProvider; + use relay_substrate_client::{MockedRuntimeUtilityPallet, SignParam, UnsignedTransaction}; + use std::time::Duration; + + #[derive(Clone)] + pub struct ThisChain; + impl UnderlyingChainProvider for ThisChain { + type Chain = mock::ThisUnderlyingChain; + } + impl relay_substrate_client::Chain for ThisChain { + const NAME: &'static str = ""; + const BEST_FINALIZED_HEADER_ID_METHOD: &'static str = ""; + const FREE_HEADERS_INTERVAL_METHOD: &'static str = ""; + const AVERAGE_BLOCK_INTERVAL: Duration = Duration::from_millis(0); + type SignedBlock = mock::SignedBlock; + type Call = RuntimeCall; + } + impl relay_substrate_client::ChainWithTransactions for ThisChain { + type AccountKeyPair = sp_core::sr25519::Pair; + type SignedTransaction = (); + + fn sign_transaction( + _: SignParam, + _: UnsignedTransaction, + ) -> Result + where + Self: Sized, + { + todo!() + } + } + impl relay_substrate_client::ChainWithMessages for ThisChain { + const WITH_CHAIN_RELAYERS_PALLET_NAME: Option<&'static str> = None; + const TO_CHAIN_MESSAGE_DETAILS_METHOD: &'static str = ""; + const FROM_CHAIN_MESSAGE_DETAILS_METHOD: &'static str = ""; + } + impl relay_substrate_client::ChainWithUtilityPallet for ThisChain { + type UtilityPallet = MockedRuntimeUtilityPallet; + } + + #[derive(Clone)] + pub struct BridgedChain; + impl UnderlyingChainProvider for BridgedChain { + type Chain = mock::BridgedUnderlyingChain; + } + impl relay_substrate_client::Chain for BridgedChain { + const NAME: &'static str = ""; + const BEST_FINALIZED_HEADER_ID_METHOD: &'static str = ""; + const FREE_HEADERS_INTERVAL_METHOD: &'static str = ""; + const AVERAGE_BLOCK_INTERVAL: Duration = Duration::from_millis(0); + type SignedBlock = mock::SignedBlock; + type Call = RuntimeCall; + } + impl relay_substrate_client::ChainWithTransactions for BridgedChain { + type AccountKeyPair = sp_core::sr25519::Pair; + type SignedTransaction = (); + + fn sign_transaction( + _: SignParam, + _: UnsignedTransaction, + ) -> Result + where + Self: Sized, + { + todo!() + } + } + impl relay_substrate_client::ChainWithMessages for BridgedChain { + const WITH_CHAIN_RELAYERS_PALLET_NAME: Option<&'static str> = None; + const TO_CHAIN_MESSAGE_DETAILS_METHOD: &'static str = ""; + const FROM_CHAIN_MESSAGE_DETAILS_METHOD: &'static str = ""; + } + impl relay_substrate_client::ChainWithUtilityPallet for BridgedChain { + type UtilityPallet = MockedRuntimeUtilityPallet; + } + + #[derive(Clone, Debug)] + pub struct ThisChainToBridgedChainMessageLane; + impl SubstrateMessageLane for ThisChainToBridgedChainMessageLane { + type SourceChain = ThisChain; + type TargetChain = BridgedChain; + type ReceiveMessagesProofCallBuilder = + ThisChainToBridgedChainMessageLaneReceiveMessagesProofCallBuilder; + type ReceiveMessagesDeliveryProofCallBuilder = + ThisChainToBridgedChainMessageLaneReceiveMessagesDeliveryProofCallBuilder; + type SourceBatchCallBuilder = UtilityPalletBatchCallBuilder; + type TargetBatchCallBuilder = UtilityPalletBatchCallBuilder; + } + + generate_receive_message_proof_call_builder!( + ThisChainToBridgedChainMessageLane, + ThisChainToBridgedChainMessageLaneReceiveMessagesProofCallBuilder, + RuntimeCall::BridgeMessages, + CodegenBridgeMessagesCall::receive_messages_proof + ); + generate_receive_message_delivery_proof_call_builder!( + ThisChainToBridgedChainMessageLane, + ThisChainToBridgedChainMessageLaneReceiveMessagesDeliveryProofCallBuilder, + RuntimeCall::BridgeMessages, + CodegenBridgeMessagesCall::receive_messages_delivery_proof + ); + } +} diff --git a/bridges/relays/lib-substrate-relay/src/messages_source.rs b/bridges/relays/lib-substrate-relay/src/messages/source.rs similarity index 97% rename from bridges/relays/lib-substrate-relay/src/messages_source.rs rename to bridges/relays/lib-substrate-relay/src/messages/source.rs index 1f597e278da404a5c3d8d0dff0032030d96ed433..b75fc86d5eee20d247de3cbc26f324ed46e9ad2d 100644 --- a/bridges/relays/lib-substrate-relay/src/messages_source.rs +++ b/bridges/relays/lib-substrate-relay/src/messages/source.rs @@ -20,11 +20,12 @@ use crate::{ finality_base::best_synced_header_id, - messages_lane::{ + messages::{ BatchProofTransaction, MessageLaneAdapter, ReceiveMessagesDeliveryProofCallBuilder, SubstrateMessageLane, }, on_demand::OnDemandRelay, + proofs::to_raw_storage_proof, TransactionParams, }; @@ -32,11 +33,11 @@ use async_std::sync::Arc; use async_trait::async_trait; use bp_messages::{ storage_keys::{operating_mode_key, outbound_lane_data_key}, + target_chain::FromBridgedChainMessagesProof, ChainWithMessages as _, InboundMessageDetails, LaneId, MessageNonce, MessagePayload, MessagesOperatingMode, OutboundLaneData, OutboundMessageDetails, }; -use bp_runtime::{BasicOperatingMode, HeaderIdProvider}; -use bridge_runtime_common::messages::target::FromBridgedChainMessagesProof; +use bp_runtime::{BasicOperatingMode, HeaderIdProvider, RangeInclusiveExt}; use codec::Encode; use frame_support::weights::Weight; use messages_relay::{ @@ -320,34 +321,27 @@ where ), SubstrateError, > { - let mut storage_keys = - Vec::with_capacity(nonces.end().saturating_sub(*nonces.start()) as usize + 1); - let mut message_nonce = *nonces.start(); - while message_nonce <= *nonces.end() { + let mut storage_keys = Vec::with_capacity(nonces.saturating_len() as usize); + for message_nonce in nonces.clone() { let message_key = bp_messages::storage_keys::message_key( P::TargetChain::WITH_CHAIN_MESSAGES_PALLET_NAME, &self.lane_id, message_nonce, ); storage_keys.push(message_key); - message_nonce += 1; } if proof_parameters.outbound_state_proof_required { - storage_keys.push(bp_messages::storage_keys::outbound_lane_data_key( + storage_keys.push(outbound_lane_data_key( P::TargetChain::WITH_CHAIN_MESSAGES_PALLET_NAME, &self.lane_id, )); } - let proof = self - .source_client - .prove_storage(id.1, storage_keys) - .await? - .into_iter_nodes() - .collect(); + let storage_proof = + self.source_client.prove_storage(id.hash(), storage_keys.clone()).await?; let proof = FromBridgedChainMessagesProof { bridged_header_hash: id.1, - storage_proof: proof, + storage_proof: to_raw_storage_proof::(storage_proof), lane: self.lane_id, nonces_start: *nonces.start(), nonces_end: *nonces.end(), diff --git a/bridges/relays/lib-substrate-relay/src/messages_target.rs b/bridges/relays/lib-substrate-relay/src/messages/target.rs similarity index 94% rename from bridges/relays/lib-substrate-relay/src/messages_target.rs rename to bridges/relays/lib-substrate-relay/src/messages/target.rs index e1c7645eac6834ed8768ef6f416ce415c37653cf..a6bf169cffb67ae149d9d4c8c5a2348dc18f5b39 100644 --- a/bridges/relays/lib-substrate-relay/src/messages_target.rs +++ b/bridges/relays/lib-substrate-relay/src/messages/target.rs @@ -19,24 +19,25 @@ //! `` chain. use crate::{ - messages_lane::{ + messages::{ + source::{ + ensure_messages_pallet_active, read_client_state_from_both_chains, + SubstrateMessagesProof, + }, BatchProofTransaction, MessageLaneAdapter, ReceiveMessagesProofCallBuilder, SubstrateMessageLane, }, - messages_source::{ - ensure_messages_pallet_active, read_client_state_from_both_chains, SubstrateMessagesProof, - }, on_demand::OnDemandRelay, + proofs::to_raw_storage_proof, TransactionParams, }; use async_std::sync::Arc; use async_trait::async_trait; use bp_messages::{ - storage_keys::inbound_lane_data_key, ChainWithMessages as _, InboundLaneData, LaneId, - MessageNonce, UnrewardedRelayersState, + source_chain::FromBridgedChainMessagesDeliveryProof, storage_keys::inbound_lane_data_key, + ChainWithMessages as _, InboundLaneData, LaneId, MessageNonce, UnrewardedRelayersState, }; -use bridge_runtime_common::messages::source::FromBridgedChainMessagesDeliveryProof; use messages_relay::{ message_lane::{MessageLane, SourceHeaderIdOf, TargetHeaderIdOf}, message_lane_loop::{NoncesSubmitArtifacts, TargetClient, TargetClientState}, @@ -47,7 +48,7 @@ use relay_substrate_client::{ }; use relay_utils::relay_loop::Client as RelayClient; use sp_core::Pair; -use std::ops::RangeInclusive; +use std::{convert::TryFrom, ops::RangeInclusive}; /// Message receiving proof returned by the target Substrate node. pub type SubstrateMessagesDeliveryProof = @@ -231,19 +232,16 @@ where SubstrateError, > { let (id, relayers_state) = self.unrewarded_relayers_state(id).await?; - let inbound_data_key = bp_messages::storage_keys::inbound_lane_data_key( + let storage_keys = vec![inbound_lane_data_key( P::SourceChain::WITH_CHAIN_MESSAGES_PALLET_NAME, &self.lane_id, - ); - let proof = self - .target_client - .prove_storage(id.hash(), vec![inbound_data_key]) - .await? - .into_iter_nodes() - .collect(); + )]; + + let storage_proof = + self.target_client.prove_storage(id.hash(), storage_keys.clone()).await?; let proof = FromBridgedChainMessagesDeliveryProof { bridged_header_hash: id.1, - storage_proof: proof, + storage_proof: to_raw_storage_proof::(storage_proof), lane: self.lane_id, }; Ok((id, (relayers_state, proof))) diff --git a/bridges/relays/lib-substrate-relay/src/on_demand/parachains.rs b/bridges/relays/lib-substrate-relay/src/on_demand/parachains.rs index 654cb6628d5f062d5790a2d14ffa1ae6fadb7475..4579222a2c681c49e076f67d2eacaeb1dc8b9fca 100644 --- a/bridges/relays/lib-substrate-relay/src/on_demand/parachains.rs +++ b/bridges/relays/lib-substrate-relay/src/on_demand/parachains.rs @@ -17,7 +17,7 @@ //! On-demand Substrate -> Substrate parachain finality relay. use crate::{ - messages_source::best_finalized_peer_header_at_self, + messages::source::best_finalized_peer_header_at_self, on_demand::OnDemandRelay, parachains::{ source::ParachainsSource, target::ParachainsTarget, ParachainsPipelineAdapter, @@ -681,7 +681,7 @@ impl<'a, P: SubstrateParachainsPipeline, SourceRelayClnt, TargetClnt> async fn best_finalized_relay_block_at_target( &self, ) -> Result, SubstrateError> { - Ok(crate::messages_source::read_client_state::( + Ok(crate::messages::source::read_client_state::( &self.0.target_client, ) .await? diff --git a/bridges/relays/lib-substrate-relay/src/parachains/source.rs b/bridges/relays/lib-substrate-relay/src/parachains/source.rs index 11b9d6dbf5bd3fe12a4249ac9c2f9864291392d7..1aa12d1c913d11e13e95908db44c6302942fa94a 100644 --- a/bridges/relays/lib-substrate-relay/src/parachains/source.rs +++ b/bridges/relays/lib-substrate-relay/src/parachains/source.rs @@ -16,8 +16,10 @@ //! Parachain heads source. -use crate::parachains::{ParachainsPipelineAdapter, SubstrateParachainsPipeline}; - +use crate::{ + parachains::{ParachainsPipelineAdapter, SubstrateParachainsPipeline}, + proofs::to_raw_storage_proof, +}; use async_std::sync::{Arc, Mutex}; use async_trait::async_trait; use bp_parachains::parachain_head_storage_key_at_source; @@ -153,12 +155,9 @@ where let parachain = ParaId(P::SourceParachain::PARACHAIN_ID); let storage_key = parachain_head_storage_key_at_source(P::SourceRelayChain::PARAS_PALLET_NAME, parachain); - let parachain_heads_proof = self - .client - .prove_storage(at_block.hash(), vec![storage_key.clone()]) - .await? - .into_iter_nodes() - .collect(); + + let storage_proof = + self.client.prove_storage(at_block.hash(), vec![storage_key.clone()]).await?; // why we're reading parachain head here once again (it has already been read at the // `parachain_head`)? that's because `parachain_head` sometimes returns obsolete parachain @@ -178,6 +177,11 @@ where })?; let parachain_head_hash = parachain_head.hash(); - Ok((ParaHeadsProof { storage_proof: parachain_heads_proof }, parachain_head_hash)) + Ok(( + ParaHeadsProof { + storage_proof: to_raw_storage_proof::(storage_proof), + }, + parachain_head_hash, + )) } } diff --git a/bridges/relays/messages/Cargo.toml b/bridges/relays/messages/Cargo.toml index 96e441fc6730e808065c86d83020ea36e29a2c1b..c7a132bb3bae7ebc34728de8c94c41fb39c89751 100644 --- a/bridges/relays/messages/Cargo.toml +++ b/bridges/relays/messages/Cargo.toml @@ -13,7 +13,6 @@ workspace = true [dependencies] async-std = { features = ["attributes"], workspace = true } async-trait = { workspace = true } -env_logger = { workspace = true } futures = { workspace = true } hex = { workspace = true, default-features = true } log = { workspace = true } diff --git a/bridges/relays/parachains/src/parachains_loop.rs b/bridges/relays/parachains/src/parachains_loop.rs index fd73ca2d46c00f8e05bb05a14a7fa4104ef898c4..0fd1d72c7075bc29632280615f203e0c0028359b 100644 --- a/bridges/relays/parachains/src/parachains_loop.rs +++ b/bridges/relays/parachains/src/parachains_loop.rs @@ -680,7 +680,6 @@ impl SubmittedHeadsTracker

{ mod tests { use super::*; use async_std::sync::{Arc, Mutex}; - use codec::Encode; use futures::{SinkExt, StreamExt}; use relay_substrate_client::test_chain::{TestChain, TestParachain}; use relay_utils::{HeaderId, MaybeConnectionError}; @@ -821,8 +820,7 @@ mod tests { let head_result = SourceClient::::parachain_head(self, at_block).await?; let head = head_result.as_available().unwrap(); - let storage_proof = vec![head.hash().encode()]; - let proof = (ParaHeadsProof { storage_proof }, head.hash()); + let proof = (ParaHeadsProof { storage_proof: Default::default() }, head.hash()); self.data.lock().await.source_proof.clone().map(|_| proof) } } diff --git a/cumulus/bin/pov-validator/Cargo.toml b/cumulus/bin/pov-validator/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..9be92960ad772217635c796f0f7962384aaebfe8 --- /dev/null +++ b/cumulus/bin/pov-validator/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "cumulus-pov-validator" +version = "0.1.0" +authors.workspace = true +edition.workspace = true +repository.workspace = true +license.workspace = true +homepage.workspace = true +description = "A tool for validating PoVs locally" + +[dependencies] +codec.workspace = true +clap = { workspace = true, features = ["derive"] } +sc-executor.workspace = true +sp-io.workspace = true +sp-core.workspace = true +sp-maybe-compressed-blob.workspace = true +polkadot-node-primitives.workspace = true +polkadot-parachain-primitives.workspace = true +polkadot-primitives.workspace = true +anyhow.workspace = true +tracing.workspace = true +tracing-subscriber.workspace = true + +[lints] +workspace = true diff --git a/cumulus/bin/pov-validator/src/main.rs b/cumulus/bin/pov-validator/src/main.rs new file mode 100644 index 0000000000000000000000000000000000000000..1c08f218f6b8ae38d86764b6e5ed148944addcd9 --- /dev/null +++ b/cumulus/bin/pov-validator/src/main.rs @@ -0,0 +1,154 @@ +// This file is part of Cumulus. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0 + +// This program is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with this program. If not, see . + +use clap::Parser; +use codec::{Decode, Encode}; +use polkadot_node_primitives::{BlockData, PoV, POV_BOMB_LIMIT, VALIDATION_CODE_BOMB_LIMIT}; +use polkadot_parachain_primitives::primitives::ValidationParams; +use polkadot_primitives::{BlockNumber as RBlockNumber, Hash as RHash, HeadData}; +use sc_executor::WasmExecutor; +use sp_core::traits::{CallContext, CodeExecutor, RuntimeCode, WrappedRuntimeCode}; +use std::{fs, path::PathBuf, time::Instant}; +use tracing::level_filters::LevelFilter; + +/// Tool for validating a `PoV` locally. +#[derive(Parser)] +struct Cli { + /// The path to the validation code that should be used to validate the `PoV`. + /// + /// The validation code can either be downloaded from the relay chain that the parachain is + /// connected to or by building the runtime manually to obtain the WASM binary. + #[arg(long)] + validation_code: PathBuf, + + /// The path to the `PoV` to validate. + /// + /// The `PoV`'s can be obtained by running `polkadot-parachains --collator --chain YOUR_CHAIN + /// --export-pov-to-path PATH_TO_EXPORT` and then choose one of the exported `PoV`'s. + #[arg(long)] + pov: PathBuf, +} + +fn main() -> anyhow::Result<()> { + let _ = tracing_subscriber::fmt() + .with_env_filter( + tracing_subscriber::EnvFilter::from_default_env() + .add_directive(LevelFilter::INFO.into()), + ) + .with_writer(std::io::stderr) + .try_init(); + + let cli = Cli::parse(); + + let validation_code = fs::read(&cli.validation_code).map_err(|error| { + tracing::error!(%error, path = %cli.validation_code.display(), "Failed to read validation code"); + anyhow::anyhow!("Failed to read validation code") + })?; + + let validation_code = + sp_maybe_compressed_blob::decompress(&validation_code, VALIDATION_CODE_BOMB_LIMIT) + .map_err(|error| { + tracing::error!(%error, "Failed to decompress validation code"); + anyhow::anyhow!("Failed to decompress validation code") + })?; + + let pov_file = fs::read(&cli.pov).map_err(|error| { + tracing::error!(%error, path = %cli.pov.display(), "Failed to read PoV"); + anyhow::anyhow!("Failed to read PoV") + })?; + + let executor = WasmExecutor::::builder() + .with_allow_missing_host_functions(true) + .build(); + + let runtime_code = RuntimeCode { + code_fetcher: &WrappedRuntimeCode(validation_code.into()), + heap_pages: None, + // The hash is used for caching, which we need here, but we only use one wasm file. So, the + // actual hash is not that important. + hash: vec![1, 2, 3], + }; + + // We are calling `Core_version` to get the wasm file compiled. We don't care about the result. + let _ = executor + .call( + &mut sp_io::TestExternalities::default().ext(), + &runtime_code, + "Core_version", + &[], + CallContext::Offchain, + ) + .0; + + let pov_file_ptr = &mut &pov_file[..]; + let pov = PoV::decode(pov_file_ptr).map_err(|error| { + tracing::error!(%error, "Failed to decode `PoV`"); + anyhow::anyhow!("Failed to decode `PoV`") + })?; + let head_data = HeadData::decode(pov_file_ptr).map_err(|error| { + tracing::error!(%error, "Failed to `HeadData`"); + anyhow::anyhow!("Failed to decode `HeadData`") + })?; + let relay_parent_storage_root = RHash::decode(pov_file_ptr).map_err(|error| { + tracing::error!(%error, "Failed to relay storage root"); + anyhow::anyhow!("Failed to decode relay storage root") + })?; + let relay_parent_number = RBlockNumber::decode(pov_file_ptr).map_err(|error| { + tracing::error!(%error, "Failed to relay block number"); + anyhow::anyhow!("Failed to decode relay block number") + })?; + + let pov = sp_maybe_compressed_blob::decompress(&pov.block_data.0, POV_BOMB_LIMIT).map_err( + |error| { + tracing::error!(%error, "Failed to decompress `PoV`"); + anyhow::anyhow!("Failed to decompress `PoV`") + }, + )?; + + let validation_params = ValidationParams { + relay_parent_number, + relay_parent_storage_root, + parent_head: head_data, + block_data: BlockData(pov.into()), + }; + + tracing::info!("Starting validation"); + + let start = Instant::now(); + + let res = executor + .call( + &mut sp_io::TestExternalities::default().ext(), + &runtime_code, + "validate_block", + &validation_params.encode(), + CallContext::Offchain, + ) + .0; + + let duration = start.elapsed(); + + match res { + Ok(_) => tracing::info!("Validation was successful"), + Err(error) => tracing::error!(%error, "Validation failed"), + } + + tracing::info!("Validation took {}ms", duration.as_millis()); + + Ok(()) +} diff --git a/cumulus/client/consensus/aura/src/collators/lookahead.rs b/cumulus/client/consensus/aura/src/collators/lookahead.rs index 749b131123949de9a00801558017b6637e48380d..02d60538a7323b86948c4378c7d0d4cd5c634116 100644 --- a/cumulus/client/consensus/aura/src/collators/lookahead.rs +++ b/cumulus/client/consensus/aura/src/collators/lookahead.rs @@ -39,10 +39,13 @@ use cumulus_primitives_aura::AuraUnincludedSegmentApi; use cumulus_primitives_core::{CollectCollationInfo, PersistedValidationData}; use cumulus_relay_chain_interface::RelayChainInterface; -use polkadot_node_primitives::SubmitCollationParams; +use polkadot_node_primitives::{PoV, SubmitCollationParams}; use polkadot_node_subsystem::messages::CollationGenerationMessage; use polkadot_overseer::Handle as OverseerHandle; -use polkadot_primitives::{CollatorPair, Id as ParaId, OccupiedCoreAssumption}; +use polkadot_primitives::{ + BlockNumber as RBlockNumber, CollatorPair, Hash as RHash, HeadData, Id as ParaId, + OccupiedCoreAssumption, +}; use futures::prelude::*; use sc_client_api::{backend::AuxStore, BlockBackend, BlockOf}; @@ -54,10 +57,49 @@ use sp_consensus_aura::{AuraApi, Slot}; use sp_core::crypto::Pair; use sp_inherents::CreateInherentDataProviders; use sp_keystore::KeystorePtr; -use sp_runtime::traits::{Block as BlockT, Header as HeaderT, Member}; -use std::{sync::Arc, time::Duration}; +use sp_runtime::traits::{Block as BlockT, Header as HeaderT, Member, NumberFor}; +use std::{ + fs::{self, File}, + path::PathBuf, + sync::Arc, + time::Duration, +}; -use crate::collator::{self as collator_util}; +use crate::{collator as collator_util, LOG_TARGET}; + +/// Export the given `pov` to the file system at `path`. +/// +/// The file will be named `block_hash_block_number.pov`. +/// +/// The `parent_header`, `relay_parent_storage_root` and `relay_parent_number` will also be +/// stored in the file alongside the `pov`. This enables stateless validation of the `pov`. +fn export_pov_to_path( + path: PathBuf, + pov: PoV, + block_hash: Block::Hash, + block_number: NumberFor, + parent_header: Block::Header, + relay_parent_storage_root: RHash, + relay_parent_number: RBlockNumber, +) { + if let Err(error) = fs::create_dir_all(&path) { + tracing::error!(target: LOG_TARGET, %error, path = %path.display(), "Failed to create PoV export directory"); + return + } + + let mut file = match File::create(path.join(format!("{block_hash:?}_{block_number}.pov"))) { + Ok(f) => f, + Err(error) => { + tracing::error!(target: LOG_TARGET, %error, "Failed to export PoV."); + return + }, + }; + + pov.encode_to(&mut file); + HeadData(parent_header.encode()).encode_to(&mut file); + relay_parent_storage_root.encode_to(&mut file); + relay_parent_number.encode_to(&mut file); +} /// Parameters for [`run`]. pub struct Params { @@ -97,7 +139,58 @@ pub struct Params { /// Run async-backing-friendly Aura. pub fn run( - mut params: Params, + params: Params, +) -> impl Future + Send + 'static +where + Block: BlockT, + Client: ProvideRuntimeApi + + BlockOf + + AuxStore + + HeaderBackend + + BlockBackend + + Send + + Sync + + 'static, + Client::Api: + AuraApi + CollectCollationInfo + AuraUnincludedSegmentApi, + Backend: sc_client_api::Backend + 'static, + RClient: RelayChainInterface + Clone + 'static, + CIDP: CreateInherentDataProviders + 'static, + CIDP::InherentDataProviders: Send, + BI: BlockImport + ParachainBlockImportMarker + Send + Sync + 'static, + Proposer: ProposerInterface + Send + Sync + 'static, + CS: CollatorServiceInterface + Send + Sync + 'static, + CHP: consensus_common::ValidationCodeHashProvider + Send + 'static, + P: Pair, + P::Public: AppPublic + Member + Codec, + P::Signature: TryFrom> + Member + Codec, +{ + run_with_export::<_, P, _, _, _, _, _, _, _, _>(ParamsWithExport { params, export_pov: None }) +} + +/// Parameters for [`run_with_export`]. +pub struct ParamsWithExport { + /// The parameters. + pub params: Params, + /// When set, the collator will export every produced `POV` to this folder. + pub export_pov: Option, +} + +/// Run async-backing-friendly Aura. +/// +/// This is exactly the same as [`run`], but it supports the optional export of each produced `POV` +/// to the file system. +pub fn run_with_export( + ParamsWithExport { mut params, export_pov }: ParamsWithExport< + BI, + CIDP, + Client, + Backend, + RClient, + CHP, + Proposer, + CS, + >, ) -> impl Future + Send + 'static where Block: BlockT, @@ -339,6 +432,18 @@ where // and provides sybil-resistance, as it should. collator.collator_service().announce_block(new_block_hash, None); + if let Some(ref export_pov) = export_pov { + export_pov_to_path::( + export_pov.clone(), + collation.proof_of_validity.clone().into_compressed(), + new_block_hash, + *block_data.header().number(), + parent_header.clone(), + *relay_parent_header.state_root(), + *relay_parent_header.number(), + ); + } + // Send a submit-collation message to the collation generation subsystem, // which then distributes this to validators. // diff --git a/cumulus/client/parachain-inherent/Cargo.toml b/cumulus/client/parachain-inherent/Cargo.toml index d81f727b41b9f5382d519c7ea84f625dbd796790..0d82cf64874322c2d9e6e2cb64ed742d35bc58e5 100644 --- a/cumulus/client/parachain-inherent/Cargo.toml +++ b/cumulus/client/parachain-inherent/Cargo.toml @@ -18,7 +18,6 @@ sp-crypto-hashing = { workspace = true, default-features = true } sp-inherents = { workspace = true, default-features = true } sp-runtime = { workspace = true, default-features = true } sp-state-machine = { workspace = true, default-features = true } -sp-std = { workspace = true, default-features = true } sp-storage = { workspace = true, default-features = true } sp-trie = { workspace = true, default-features = true } diff --git a/cumulus/client/relay-chain-inprocess-interface/src/lib.rs b/cumulus/client/relay-chain-inprocess-interface/src/lib.rs index 8f8d666bd1433ff70556e9867edc7861647dbebf..38ba84748c1e38b8dd3c1fcdd2f8d6351299b18c 100644 --- a/cumulus/client/relay-chain-inprocess-interface/src/lib.rs +++ b/cumulus/client/relay-chain-inprocess-interface/src/lib.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Cumulus. If not, see . -use std::{pin::Pin, sync::Arc, time::Duration}; +use std::{collections::btree_map::BTreeMap, pin::Pin, sync::Arc, time::Duration}; use async_trait::async_trait; use cumulus_primitives_core::{ @@ -38,7 +38,7 @@ use sc_client_api::{ use sc_telemetry::TelemetryWorkerHandle; use sp_api::ProvideRuntimeApi; use sp_consensus::SyncOracle; -use sp_core::{sp_std::collections::btree_map::BTreeMap, Pair}; +use sp_core::Pair; use sp_state_machine::{Backend as StateBackend, StorageValue}; /// The timeout in seconds after that the waiting for a block should be aborted. diff --git a/cumulus/client/relay-chain-rpc-interface/src/lib.rs b/cumulus/client/relay-chain-rpc-interface/src/lib.rs index 692a1fb537a83b5493c207688fd5d40be5321be9..e32ec6a41a4bf00db5e5db07235bf43bbad1dbf6 100644 --- a/cumulus/client/relay-chain-rpc-interface/src/lib.rs +++ b/cumulus/client/relay-chain-rpc-interface/src/lib.rs @@ -30,11 +30,10 @@ use futures::{FutureExt, Stream, StreamExt}; use polkadot_overseer::Handle; use sc_client_api::StorageProof; -use sp_core::sp_std::collections::btree_map::BTreeMap; use sp_state_machine::StorageValue; use sp_storage::StorageKey; use sp_version::RuntimeVersion; -use std::pin::Pin; +use std::{collections::btree_map::BTreeMap, pin::Pin}; use cumulus_primitives_core::relay_chain::BlockId; pub use url::Url; diff --git a/cumulus/client/relay-chain-rpc-interface/src/rpc_client.rs b/cumulus/client/relay-chain-rpc-interface/src/rpc_client.rs index a5d7c22a2ec89b17c2115a4dd56e4ee935ca51b4..c7eaa45958b0b002a00ec8210d5044bd56aa0569 100644 --- a/cumulus/client/relay-chain-rpc-interface/src/rpc_client.rs +++ b/cumulus/client/relay-chain-rpc-interface/src/rpc_client.rs @@ -24,7 +24,7 @@ use jsonrpsee::{ }; use serde::de::DeserializeOwned; use serde_json::Value as JsonValue; -use std::collections::VecDeque; +use std::collections::{btree_map::BTreeMap, VecDeque}; use tokio::sync::mpsc::Sender as TokioSender; use codec::{Decode, Encode}; @@ -47,7 +47,6 @@ use sc_client_api::StorageData; use sc_rpc_api::{state::ReadProof, system::Health}; use sc_service::TaskManager; use sp_consensus_babe::Epoch; -use sp_core::sp_std::collections::btree_map::BTreeMap; use sp_storage::StorageKey; use sp_version::RuntimeVersion; diff --git a/cumulus/pallets/aura-ext/Cargo.toml b/cumulus/pallets/aura-ext/Cargo.toml index 1b6ac4cf07dff2341c366a18e103f7e0ec49e2ac..c08148928b7cec891b8f80cb856714c24b04d809 100644 --- a/cumulus/pallets/aura-ext/Cargo.toml +++ b/cumulus/pallets/aura-ext/Cargo.toml @@ -21,7 +21,6 @@ pallet-timestamp = { workspace = true } sp-application-crypto = { workspace = true } sp-consensus-aura = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } # Cumulus cumulus-pallet-parachain-system = { workspace = true } @@ -44,7 +43,6 @@ std = [ "sp-application-crypto/std", "sp-consensus-aura/std", "sp-runtime/std", - "sp-std/std", ] try-runtime = [ "cumulus-pallet-parachain-system/try-runtime", diff --git a/cumulus/pallets/aura-ext/src/consensus_hook.rs b/cumulus/pallets/aura-ext/src/consensus_hook.rs index 560d477b2a850d11fbc2202b900add53351de476..c1a8568bdd834f0e754bdad20a5a11246cc6ac31 100644 --- a/cumulus/pallets/aura-ext/src/consensus_hook.rs +++ b/cumulus/pallets/aura-ext/src/consensus_hook.rs @@ -20,6 +20,7 @@ //! The velocity `V` refers to the rate of block processing by the relay chain. use super::{pallet, Aura}; +use core::{marker::PhantomData, num::NonZeroU32}; use cumulus_pallet_parachain_system::{ self as parachain_system, consensus_hook::{ConsensusHook, UnincludedSegmentCapacity}, @@ -27,7 +28,6 @@ use cumulus_pallet_parachain_system::{ }; use frame_support::pallet_prelude::*; use sp_consensus_aura::{Slot, SlotDuration}; -use sp_std::{marker::PhantomData, num::NonZeroU32}; /// A consensus hook for a fixed block processing velocity and unincluded segment capacity. /// @@ -84,7 +84,7 @@ where ( weight, - NonZeroU32::new(sp_std::cmp::max(C, 1)) + NonZeroU32::new(core::cmp::max(C, 1)) .expect("1 is the minimum value and non-zero; qed") .into(), ) diff --git a/cumulus/pallets/aura-ext/src/lib.rs b/cumulus/pallets/aura-ext/src/lib.rs index 4605dd325bee5145974ddc7bca4b5900ad2bc0ed..4c9e61458a87c456766880351da7ecbcce30a92c 100644 --- a/cumulus/pallets/aura-ext/src/lib.rs +++ b/cumulus/pallets/aura-ext/src/lib.rs @@ -109,7 +109,7 @@ pub mod pallet { #[derive(frame_support::DefaultNoBound)] pub struct GenesisConfig { #[serde(skip)] - pub _config: sp_std::marker::PhantomData, + pub _config: core::marker::PhantomData, } #[pallet::genesis_build] @@ -125,7 +125,7 @@ pub mod pallet { /// /// When executing the block it will verify the block seal to ensure that the correct author created /// the block. -pub struct BlockExecutor(sp_std::marker::PhantomData<(T, I)>); +pub struct BlockExecutor(core::marker::PhantomData<(T, I)>); impl ExecuteBlock for BlockExecutor where diff --git a/cumulus/pallets/collator-selection/Cargo.toml b/cumulus/pallets/collator-selection/Cargo.toml index 206700b7d606c81bef4f33cbfe6e705e6efb49ad..b3512dc2ae6c9a646e63d911bdf09b132f5098cd 100644 --- a/cumulus/pallets/collator-selection/Cargo.toml +++ b/cumulus/pallets/collator-selection/Cargo.toml @@ -21,7 +21,6 @@ codec = { features = ["derive"], workspace = true } rand = { features = ["std_rng"], workspace = true } scale-info = { features = ["derive"], workspace = true } -sp-std = { workspace = true } sp-runtime = { workspace = true } sp-staking = { workspace = true } frame-support = { workspace = true } @@ -65,7 +64,6 @@ std = [ "scale-info/std", "sp-runtime/std", "sp-staking/std", - "sp-std/std", ] try-runtime = [ diff --git a/cumulus/pallets/collator-selection/src/benchmarking.rs b/cumulus/pallets/collator-selection/src/benchmarking.rs index c6b600445282534951b2c63a6c2a87181688acd1..24823661383b55f26bf19356e72394945c01f577 100644 --- a/cumulus/pallets/collator-selection/src/benchmarking.rs +++ b/cumulus/pallets/collator-selection/src/benchmarking.rs @@ -21,13 +21,14 @@ use super::*; #[allow(unused)] use crate::Pallet as CollatorSelection; +use alloc::vec::Vec; use codec::Decode; +use core::cmp; use frame_benchmarking::{account, v2::*, whitelisted_caller, BenchmarkError}; use frame_support::traits::{Currency, EnsureOrigin, Get, ReservableCurrency}; use frame_system::{pallet_prelude::BlockNumberFor, EventRecord, RawOrigin}; use pallet_authorship::EventHandler; use pallet_session::{self as session, SessionManager}; -use sp_std::{cmp, prelude::*}; pub type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; diff --git a/cumulus/pallets/collator-selection/src/lib.rs b/cumulus/pallets/collator-selection/src/lib.rs index 2fa384367528a1f1306a6c34c0c45d3ef94843a2..17dc1a552c2de40455933fe8a72d05caa4317a32 100644 --- a/cumulus/pallets/collator-selection/src/lib.rs +++ b/cumulus/pallets/collator-selection/src/lib.rs @@ -81,6 +81,8 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + use core::marker::PhantomData; use frame_support::traits::TypedGet; pub use pallet::*; @@ -101,6 +103,7 @@ const LOG_TARGET: &str = "runtime::collator-selection"; #[frame_support::pallet] pub mod pallet { pub use crate::weights::WeightInfo; + use alloc::vec::Vec; use core::ops::Div; use frame_support::{ dispatch::{DispatchClass, DispatchResultWithPostInfo}, @@ -118,7 +121,6 @@ pub mod pallet { RuntimeDebug, }; use sp_staking::SessionIndex; - use sp_std::vec::Vec; /// The in-code storage version. const STORAGE_VERSION: StorageVersion = StorageVersion::new(2); @@ -244,7 +246,7 @@ pub mod pallet { let duplicate_invulnerables = self .invulnerables .iter() - .collect::>(); + .collect::>(); assert!( duplicate_invulnerables.len() == self.invulnerables.len(), "duplicate invulnerables in genesis." diff --git a/cumulus/pallets/collator-selection/src/migration.rs b/cumulus/pallets/collator-selection/src/migration.rs index 425acdd8bfb59768241399e3be5efb44a13c8a74..c52016948069a65c641fa014a390f1a6a85d3cb3 100644 --- a/cumulus/pallets/collator-selection/src/migration.rs +++ b/cumulus/pallets/collator-selection/src/migration.rs @@ -17,6 +17,8 @@ //! A module that is responsible for migration of storage for Collator Selection. use super::*; +#[cfg(feature = "try-runtime")] +use alloc::vec::Vec; use frame_support::traits::{OnRuntimeUpgrade, UncheckedOnRuntimeUpgrade}; use log; @@ -29,8 +31,6 @@ pub mod v2 { traits::{Currency, ReservableCurrency}, }; use sp_runtime::traits::{Saturating, Zero}; - #[cfg(feature = "try-runtime")] - use sp_std::vec::Vec; /// [`UncheckedMigrationToV2`] wrapped in a /// [`VersionedMigration`](frame_support::migrations::VersionedMigration), ensuring the @@ -51,7 +51,7 @@ pub mod v2 { >; /// Migrate to V2. - pub struct UncheckedMigrationToV2(sp_std::marker::PhantomData); + pub struct UncheckedMigrationToV2(PhantomData); impl UncheckedOnRuntimeUpgrade for UncheckedMigrationToV2 { fn on_runtime_upgrade() -> Weight { let mut weight = Weight::zero(); @@ -123,10 +123,8 @@ pub mod v2 { pub mod v1 { use super::*; use frame_support::pallet_prelude::*; - #[cfg(feature = "try-runtime")] - use sp_std::prelude::*; - pub struct MigrateToV1(sp_std::marker::PhantomData); + pub struct MigrateToV1(PhantomData); impl OnRuntimeUpgrade for MigrateToV1 { fn on_runtime_upgrade() -> Weight { let on_chain_version = Pallet::::on_chain_storage_version(); diff --git a/cumulus/pallets/collator-selection/src/weights.rs b/cumulus/pallets/collator-selection/src/weights.rs index 1c01ad6cd6fe8e8ed4bc02c3c2d6703eb2882df4..12e6b755e9769cb4234bc15016c0a3b47650054f 100644 --- a/cumulus/pallets/collator-selection/src/weights.rs +++ b/cumulus/pallets/collator-selection/src/weights.rs @@ -18,11 +18,11 @@ #![allow(unused_parens)] #![allow(unused_imports)] +use core::marker::PhantomData; use frame_support::{ traits::Get, weights::{constants::RocksDbWeight, Weight}, }; -use sp_std::marker::PhantomData; // The weight info trait for `pallet_collator_selection`. pub trait WeightInfo { diff --git a/cumulus/pallets/dmp-queue/Cargo.toml b/cumulus/pallets/dmp-queue/Cargo.toml index 052a2547e788b0837cf224cb38095d40c20ed0fd..936526290d93ecd8935620c8f1f6045faadecb64 100644 --- a/cumulus/pallets/dmp-queue/Cargo.toml +++ b/cumulus/pallets/dmp-queue/Cargo.toml @@ -21,7 +21,6 @@ scale-info = { features = ["derive"], workspace = true } frame-benchmarking = { optional = true, workspace = true } frame-support = { workspace = true } frame-system = { workspace = true } -sp-std = { workspace = true } sp-runtime = { workspace = true } sp-io = { workspace = true } @@ -48,7 +47,6 @@ std = [ "scale-info/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", "xcm/std", ] diff --git a/cumulus/pallets/dmp-queue/src/benchmarking.rs b/cumulus/pallets/dmp-queue/src/benchmarking.rs index 91d1e0eab7e406a214088d8c0e47d03e20cd0286..432d6f3bc7ae54432e3687b7d73e70a11ec2da04 100644 --- a/cumulus/pallets/dmp-queue/src/benchmarking.rs +++ b/cumulus/pallets/dmp-queue/src/benchmarking.rs @@ -19,9 +19,9 @@ use crate::*; +use alloc::vec; use frame_benchmarking::v2::*; use frame_support::{pallet_prelude::*, traits::Hooks}; -use sp_std::vec; #[benchmarks] mod benchmarks { diff --git a/cumulus/pallets/dmp-queue/src/lib.rs b/cumulus/pallets/dmp-queue/src/lib.rs index 9b3ec684febab81fb535c52118cbadb64b61e984..cedca6f3fb97f2186318718d068a2fa120a71bc3 100644 --- a/cumulus/pallets/dmp-queue/src/lib.rs +++ b/cumulus/pallets/dmp-queue/src/lib.rs @@ -23,6 +23,8 @@ #![cfg_attr(not(feature = "std"), no_std)] #![allow(deprecated)] // The pallet itself is deprecated. +extern crate alloc; + use migration::*; pub use pallet::*; diff --git a/cumulus/pallets/dmp-queue/src/migration.rs b/cumulus/pallets/dmp-queue/src/migration.rs index 349635cce547d81c1be527cb366f67679a471945..b1945e8eb37b85e9c39cbafeba4b6d7ec15502c0 100644 --- a/cumulus/pallets/dmp-queue/src/migration.rs +++ b/cumulus/pallets/dmp-queue/src/migration.rs @@ -17,9 +17,9 @@ //! Migrates the storage from the previously deleted DMP pallet. use crate::*; +use alloc::vec::Vec; use cumulus_primitives_core::relay_chain::BlockNumber as RelayBlockNumber; use frame_support::{pallet_prelude::*, storage_alias, traits::HandleMessage}; -use sp_std::vec::Vec; pub(crate) const LOG: &str = "runtime::dmp-queue-export-xcms"; diff --git a/cumulus/pallets/parachain-system/proc-macro/src/lib.rs b/cumulus/pallets/parachain-system/proc-macro/src/lib.rs index 8ab5d81efdcf486dff67db6a1f5a62a5a8454ae8..f284fbdc64c600f130b0e5bb531021ecfd2e0e73 100644 --- a/cumulus/pallets/parachain-system/proc-macro/src/lib.rs +++ b/cumulus/pallets/parachain-system/proc-macro/src/lib.rs @@ -122,8 +122,8 @@ pub fn register_validate_block(input: proc_macro::TokenStream) -> proc_macro::To #[no_mangle] unsafe fn validate_block(arguments: *mut u8, arguments_len: usize) -> u64 { // We convert the `arguments` into a boxed slice and then into `Bytes`. - let args = #crate_::validate_block::sp_std::boxed::Box::from_raw( - #crate_::validate_block::sp_std::slice::from_raw_parts_mut( + let args = #crate_::validate_block::Box::from_raw( + #crate_::validate_block::slice::from_raw_parts_mut( arguments, arguments_len, ) diff --git a/cumulus/pallets/parachain-system/src/consensus_hook.rs b/cumulus/pallets/parachain-system/src/consensus_hook.rs index 91353fc7bbda7ce05cfb5259e05bde64c758bbe4..3062396a4e7865bf4e3545b39c6ad9fa6ded6a24 100644 --- a/cumulus/pallets/parachain-system/src/consensus_hook.rs +++ b/cumulus/pallets/parachain-system/src/consensus_hook.rs @@ -18,8 +18,8 @@ //! of parachain blocks ready to submit to the relay chain, as well as some basic implementations. use super::relay_state_snapshot::RelayChainStateProof; +use core::num::NonZeroU32; use frame_support::weights::Weight; -use sp_std::num::NonZeroU32; /// The possible capacity of the unincluded segment. #[derive(Clone)] @@ -95,7 +95,7 @@ impl ConsensusHook for FixedCapacityUnincludedSegment { fn on_state_proof(_state_proof: &RelayChainStateProof) -> (Weight, UnincludedSegmentCapacity) { ( Weight::zero(), - NonZeroU32::new(sp_std::cmp::max(N, 1)) + NonZeroU32::new(core::cmp::max(N, 1)) .expect("1 is the minimum value and non-zero; qed") .into(), ) diff --git a/cumulus/pallets/parachain-system/src/lib.rs b/cumulus/pallets/parachain-system/src/lib.rs index bbb74a1b053886b90740562e077ce40804eb01fd..9e0a68d09a14a685da6a66facdd0ac2822d4c6d4 100644 --- a/cumulus/pallets/parachain-system/src/lib.rs +++ b/cumulus/pallets/parachain-system/src/lib.rs @@ -27,7 +27,11 @@ //! //! Users must ensure that they register this pallet as an inherent provider. +extern crate alloc; + +use alloc::{collections::btree_map::BTreeMap, vec, vec::Vec}; use codec::{Decode, Encode}; +use core::cmp; use cumulus_primitives_core::{ relay_chain, AbridgedHostConfiguration, ChannelInfo, ChannelStatus, CollationInfo, GetChannelInfo, InboundDownwardMessage, InboundHrmpMessage, ListChannelInfos, MessageSendError, @@ -54,7 +58,6 @@ use sp_runtime::{ }, BoundedSlice, FixedU128, RuntimeDebug, Saturating, }; -use sp_std::{cmp, collections::btree_map::BTreeMap, prelude::*}; use xcm::{latest::XcmHash, VersionedLocation, VersionedXcm}; use xcm_builder::InspectMessageQueues; @@ -938,7 +941,7 @@ pub mod pallet { #[derive(frame_support::DefaultNoBound)] pub struct GenesisConfig { #[serde(skip)] - pub _config: sp_std::marker::PhantomData, + pub _config: core::marker::PhantomData, } #[pallet::genesis_build] @@ -1530,7 +1533,7 @@ impl Pallet { } /// Type that implements `SetCode`. -pub struct ParachainSetCode(sp_std::marker::PhantomData); +pub struct ParachainSetCode(core::marker::PhantomData); impl frame_system::SetCode for ParachainSetCode { fn set_code(code: Vec) -> DispatchResult { Pallet::::schedule_code_upgrade(code) @@ -1645,7 +1648,7 @@ pub trait CheckInherents { /// Struct that always returns `Ok` on inherents check, needed for backwards-compatibility. #[doc(hidden)] -pub struct DummyCheckInherents(sp_std::marker::PhantomData); +pub struct DummyCheckInherents(core::marker::PhantomData); #[allow(deprecated)] impl CheckInherents for DummyCheckInherents { @@ -1718,7 +1721,7 @@ pub type RelaychainBlockNumberProvider = RelaychainDataProvider; /// of [`RelayChainState`]. /// - [`current_block_number`](Self::current_block_number): Will return /// [`Pallet::last_relay_block_number()`]. -pub struct RelaychainDataProvider(sp_std::marker::PhantomData); +pub struct RelaychainDataProvider(core::marker::PhantomData); impl BlockNumberProvider for RelaychainDataProvider { type BlockNumber = relay_chain::BlockNumber; diff --git a/cumulus/pallets/parachain-system/src/mock.rs b/cumulus/pallets/parachain-system/src/mock.rs index da904c0079a00a39dcca24c2d408d0bb381b2252..7bea72224b8ba36c6155597f4b957a2ed3a8d822 100644 --- a/cumulus/pallets/parachain-system/src/mock.rs +++ b/cumulus/pallets/parachain-system/src/mock.rs @@ -20,7 +20,9 @@ use super::*; +use alloc::collections::vec_deque::VecDeque; use codec::Encode; +use core::num::NonZeroU32; use cumulus_primitives_core::{ relay_chain::BlockNumber as RelayBlockNumber, AggregateMessageOrigin, InboundDownwardMessage, InboundHrmpMessage, PersistedValidationData, @@ -37,7 +39,6 @@ use frame_support::{ }; use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; use sp_runtime::{traits::BlakeTwo256, BuildStorage}; -use sp_std::{collections::vec_deque::VecDeque, num::NonZeroU32}; use sp_version::RuntimeVersion; use std::cell::RefCell; diff --git a/cumulus/pallets/parachain-system/src/relay_state_snapshot.rs b/cumulus/pallets/parachain-system/src/relay_state_snapshot.rs index 60eccfb072f41e87223d54f34b5c7eb59c00b2ad..323aaf6503808c954300e27179aa16bc531047c9 100644 --- a/cumulus/pallets/parachain-system/src/relay_state_snapshot.rs +++ b/cumulus/pallets/parachain-system/src/relay_state_snapshot.rs @@ -16,6 +16,7 @@ //! Relay chain state proof provides means for accessing part of relay chain storage for reads. +use alloc::vec::Vec; use codec::{Decode, Encode}; use cumulus_primitives_core::{ relay_chain, AbridgedHostConfiguration, AbridgedHrmpChannel, ParaId, @@ -23,7 +24,6 @@ use cumulus_primitives_core::{ use scale_info::TypeInfo; use sp_runtime::traits::HashingFor; use sp_state_machine::{Backend, TrieBackend, TrieBackendBuilder}; -use sp_std::vec::Vec; use sp_trie::{HashDBT, MemoryDB, StorageProof, EMPTY_PREFIX}; /// The capacity of the upward message queue of a parachain on the relay chain. diff --git a/cumulus/pallets/parachain-system/src/tests.rs b/cumulus/pallets/parachain-system/src/tests.rs index 5ff15036fb6e48b5e1a0567730b1f9035357edc2..51c6e83c113191250c3c2ebe60e2dfad1263d682 100755 --- a/cumulus/pallets/parachain-system/src/tests.rs +++ b/cumulus/pallets/parachain-system/src/tests.rs @@ -19,6 +19,7 @@ use super::*; use crate::mock::*; +use core::num::NonZeroU32; use cumulus_primitives_core::{AbridgedHrmpChannel, InboundDownwardMessage, InboundHrmpMessage}; use frame_support::{assert_ok, parameter_types, weights::Weight}; use frame_system::RawOrigin; @@ -26,7 +27,6 @@ use hex_literal::hex; use rand::Rng; use relay_chain::HrmpChannelId; use sp_core::H256; -use sp_std::num::NonZeroU32; #[test] #[should_panic] diff --git a/cumulus/pallets/parachain-system/src/unincluded_segment.rs b/cumulus/pallets/parachain-system/src/unincluded_segment.rs index 1e83a945c4ee37f2ad8ee1c45d11892f47c40be4..814bb83aa1acb0541c9cf73ead07e3e3cca84680 100644 --- a/cumulus/pallets/parachain-system/src/unincluded_segment.rs +++ b/cumulus/pallets/parachain-system/src/unincluded_segment.rs @@ -21,11 +21,12 @@ //! sent to relay chain. use super::relay_state_snapshot::{MessagingStateSnapshot, RelayDispatchQueueRemainingCapacity}; +use alloc::collections::btree_map::BTreeMap; use codec::{Decode, Encode}; +use core::marker::PhantomData; use cumulus_primitives_core::{relay_chain, ParaId}; use scale_info::TypeInfo; use sp_runtime::RuntimeDebug; -use sp_std::{collections::btree_map::BTreeMap, marker::PhantomData}; /// Constraints on outbound HRMP channel. #[derive(Clone, RuntimeDebug)] @@ -398,6 +399,7 @@ pub(crate) fn size_after_included(included_hash: H, segment: &[Anc #[cfg(test)] mod tests { use super::*; + use alloc::{vec, vec::Vec}; use assert_matches::assert_matches; #[test] diff --git a/cumulus/pallets/parachain-system/src/validate_block/implementation.rs b/cumulus/pallets/parachain-system/src/validate_block/implementation.rs index 956962fce157d3c5d090dd4bd8de78bba4d80405..42311ca9d8340d038df126175df096777cf989a9 100644 --- a/cumulus/pallets/parachain-system/src/validate_block/implementation.rs +++ b/cumulus/pallets/parachain-system/src/validate_block/implementation.rs @@ -26,6 +26,7 @@ use polkadot_parachain_primitives::primitives::{ HeadData, RelayChainBlockNumber, ValidationResult, }; +use alloc::vec::Vec; use codec::Encode; use frame_support::traits::{ExecuteBlock, ExtrinsicCall, Get, IsSubType}; @@ -33,7 +34,6 @@ use sp_core::storage::{ChildInfo, StateVersion}; use sp_externalities::{set_and_run_with_externalities, Externalities}; use sp_io::KillStorageResult; use sp_runtime::traits::{Block as BlockT, Extrinsic, HashingFor, Header as HeaderT}; -use sp_std::prelude::*; use sp_trie::{MemoryDB, ProofSizeProvider}; use trie_recorder::SizeOnlyRecorderProvider; @@ -124,7 +124,7 @@ where Err(_) => panic!("Compact proof decoding failure."), }; - sp_std::mem::drop(storage_proof); + core::mem::drop(storage_proof); let mut recorder = SizeOnlyRecorderProvider::new(); let cache_provider = trie_cache::CacheProvider::new(); @@ -294,7 +294,7 @@ fn host_storage_read(key: &[u8], value_out: &mut [u8], value_offset: u32) -> Opt Some(value) => { let value_offset = value_offset as usize; let data = &value[value_offset.min(value.len())..]; - let written = sp_std::cmp::min(data.len(), value_out.len()); + let written = core::cmp::min(data.len(), value_out.len()); value_out[..written].copy_from_slice(&data[..written]); Some(value.len() as u32) }, @@ -368,7 +368,7 @@ fn host_default_child_storage_read( Some(value) => { let value_offset = value_offset as usize; let data = &value[value_offset.min(value.len())..]; - let written = sp_std::cmp::min(data.len(), value_out.len()); + let written = core::cmp::min(data.len(), value_out.len()); value_out[..written].copy_from_slice(&data[..written]); Some(value.len() as u32) }, diff --git a/cumulus/pallets/parachain-system/src/validate_block/mod.rs b/cumulus/pallets/parachain-system/src/validate_block/mod.rs index 763a4cffd77f92171c1f102cfc70485a02e5f27e..3a00d4d352a69830ff225221d2fb63450c96b9e9 100644 --- a/cumulus/pallets/parachain-system/src/validate_block/mod.rs +++ b/cumulus/pallets/parachain-system/src/validate_block/mod.rs @@ -30,6 +30,9 @@ mod trie_cache; #[doc(hidden)] mod trie_recorder; +#[cfg(not(feature = "std"))] +#[doc(hidden)] +pub use alloc::{boxed::Box, slice}; #[cfg(not(feature = "std"))] #[doc(hidden)] pub use bytes; diff --git a/cumulus/pallets/parachain-system/src/validate_block/trie_cache.rs b/cumulus/pallets/parachain-system/src/validate_block/trie_cache.rs index 5d785910fbe026fba487980d1244262146f86a5b..5999b3ce87f9d285412ea8bccdf1258ae1f66733 100644 --- a/cumulus/pallets/parachain-system/src/validate_block/trie_cache.rs +++ b/cumulus/pallets/parachain-system/src/validate_block/trie_cache.rs @@ -15,12 +15,12 @@ // See the License for the specific language governing permissions and // limitations under the License. -use sp_state_machine::TrieCacheProvider; -use sp_std::{ +use alloc::{ boxed::Box, - cell::{RefCell, RefMut}, collections::btree_map::{BTreeMap, Entry}, }; +use core::cell::{RefCell, RefMut}; +use sp_state_machine::TrieCacheProvider; use sp_trie::NodeCodec; use trie_db::{node::NodeOwned, Hasher}; diff --git a/cumulus/pallets/parachain-system/src/validate_block/trie_recorder.rs b/cumulus/pallets/parachain-system/src/validate_block/trie_recorder.rs index 48310670c074d1be2ec86f582c0c84622abc086c..19801340719526ac6775a9a92fc0b3d879f84afb 100644 --- a/cumulus/pallets/parachain-system/src/validate_block/trie_recorder.rs +++ b/cumulus/pallets/parachain-system/src/validate_block/trie_recorder.rs @@ -22,11 +22,11 @@ use codec::Encode; -use sp_std::{ - cell::{RefCell, RefMut}, +use alloc::{ collections::{btree_map::BTreeMap, btree_set::BTreeSet}, rc::Rc, }; +use core::cell::{RefCell, RefMut}; use sp_trie::{NodeCodec, ProofSizeProvider, StorageProof}; use trie_db::{Hasher, RecordedForKey, TrieAccess}; diff --git a/cumulus/pallets/parachain-system/src/weights.rs b/cumulus/pallets/parachain-system/src/weights.rs index da7f64237e9b6a8b39096b761f6ff923f903529a..5c61879b4d36b903f9f9d81cde76ff3ce42cc747 100644 --- a/cumulus/pallets/parachain-system/src/weights.rs +++ b/cumulus/pallets/parachain-system/src/weights.rs @@ -50,7 +50,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::{Weight, constants::RocksDbWeight}}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weight functions needed for cumulus_pallet_parachain_system. pub trait WeightInfo { diff --git a/cumulus/pallets/session-benchmarking/Cargo.toml b/cumulus/pallets/session-benchmarking/Cargo.toml index df671566cdc24b8fca9486d0444aad6a1688eedb..e182ac45edebd9c22df15d18f9d3548176c538c5 100644 --- a/cumulus/pallets/session-benchmarking/Cargo.toml +++ b/cumulus/pallets/session-benchmarking/Cargo.toml @@ -17,7 +17,6 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { workspace = true } -sp-std = { workspace = true } sp-runtime = { workspace = true } frame-support = { workspace = true } frame-system = { workspace = true } @@ -39,5 +38,4 @@ std = [ "frame-system/std", "pallet-session/std", "sp-runtime/std", - "sp-std/std", ] diff --git a/cumulus/pallets/session-benchmarking/src/inner.rs b/cumulus/pallets/session-benchmarking/src/inner.rs index 36411d3d71afa2c1ae74870a1eed5ad1ad916a8c..8d5954304878dfd5ff4c4bf912168d70e4e5e53f 100644 --- a/cumulus/pallets/session-benchmarking/src/inner.rs +++ b/cumulus/pallets/session-benchmarking/src/inner.rs @@ -15,7 +15,7 @@ //! Benchmarking setup for pallet-session. -use sp_std::{prelude::*, vec}; +use alloc::{vec, vec::Vec}; use codec::Decode; use frame_benchmarking::{benchmarks, whitelisted_caller}; diff --git a/cumulus/pallets/session-benchmarking/src/lib.rs b/cumulus/pallets/session-benchmarking/src/lib.rs index a95d6fb7d591460f2055f076f60199b213b055b8..f5bfef006169035797d17957beb574200fd153ab 100644 --- a/cumulus/pallets/session-benchmarking/src/lib.rs +++ b/cumulus/pallets/session-benchmarking/src/lib.rs @@ -20,6 +20,8 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + #[cfg(feature = "runtime-benchmarks")] pub mod inner; diff --git a/cumulus/pallets/solo-to-para/Cargo.toml b/cumulus/pallets/solo-to-para/Cargo.toml index ced1b24f1d2bf52f1f6db128affe3bd8595411ba..5fd1939e93a03397dda15bae0eb638f823cbb1ce 100644 --- a/cumulus/pallets/solo-to-para/Cargo.toml +++ b/cumulus/pallets/solo-to-para/Cargo.toml @@ -18,7 +18,6 @@ frame-support = { workspace = true } frame-system = { workspace = true } pallet-sudo = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } # Polkadot polkadot-primitives = { workspace = true } @@ -37,7 +36,6 @@ std = [ "polkadot-primitives/std", "scale-info/std", "sp-runtime/std", - "sp-std/std", ] try-runtime = [ "cumulus-pallet-parachain-system/try-runtime", diff --git a/cumulus/pallets/solo-to-para/src/lib.rs b/cumulus/pallets/solo-to-para/src/lib.rs index da948615d4e90a5f109cb56b47f796acead6535c..b42cc74f1cf32220f7767f829cd4a65c9e2e0532 100644 --- a/cumulus/pallets/solo-to-para/src/lib.rs +++ b/cumulus/pallets/solo-to-para/src/lib.rs @@ -16,12 +16,14 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + +use alloc::vec::Vec; use cumulus_pallet_parachain_system as parachain_system; use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; pub use pallet::*; use polkadot_primitives::PersistedValidationData; -use sp_std::vec::Vec; #[frame_support::pallet] pub mod pallet { diff --git a/cumulus/pallets/xcm/Cargo.toml b/cumulus/pallets/xcm/Cargo.toml index 1f0cef70e3a72920d6c789acb9051ddf2a7ff8e8..35d7a083b061d204de339407c6e26c4ef948dbb8 100644 --- a/cumulus/pallets/xcm/Cargo.toml +++ b/cumulus/pallets/xcm/Cargo.toml @@ -13,7 +13,6 @@ workspace = true codec = { features = ["derive"], workspace = true } scale-info = { features = ["derive"], workspace = true } -sp-std = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } frame-support = { workspace = true } @@ -33,7 +32,6 @@ std = [ "scale-info/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", "xcm/std", ] try-runtime = [ diff --git a/cumulus/pallets/xcm/src/lib.rs b/cumulus/pallets/xcm/src/lib.rs index 90a0ec76defe2b0df8d99faacfb611c0f7834a3b..e31df8471c26698d115d798bfc9358dbc4a1b982 100644 --- a/cumulus/pallets/xcm/src/lib.rs +++ b/cumulus/pallets/xcm/src/lib.rs @@ -25,7 +25,6 @@ use cumulus_primitives_core::ParaId; pub use pallet::*; use scale_info::TypeInfo; use sp_runtime::{traits::BadOrigin, RuntimeDebug}; -use sp_std::prelude::*; use xcm::latest::{ExecuteXcm, Outcome}; #[frame_support::pallet] diff --git a/cumulus/pallets/xcmp-queue/Cargo.toml b/cumulus/pallets/xcmp-queue/Cargo.toml index c542fa373b5ed352edc4e00ea032b6dd64c97415..9c7470eda6da4aeaba942c25f04f4aeb13ee471e 100644 --- a/cumulus/pallets/xcmp-queue/Cargo.toml +++ b/cumulus/pallets/xcmp-queue/Cargo.toml @@ -20,7 +20,6 @@ frame-system = { workspace = true } sp-io = { workspace = true } sp-core = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } pallet-message-queue = { workspace = true } # Polkadot @@ -68,7 +67,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", "xcm-builder/std", "xcm-executor/std", "xcm/std", diff --git a/cumulus/pallets/xcmp-queue/src/benchmarking.rs b/cumulus/pallets/xcmp-queue/src/benchmarking.rs index 49e2cc8367348ad6a81c0017405f8c3148734be5..9cb1301addfe5c9bb29c1b034c76793b6eaeda64 100644 --- a/cumulus/pallets/xcmp-queue/src/benchmarking.rs +++ b/cumulus/pallets/xcmp-queue/src/benchmarking.rs @@ -17,6 +17,7 @@ use crate::*; +use alloc::vec; use codec::DecodeAll; use frame_benchmarking::v2::*; use frame_support::traits::Hooks; diff --git a/cumulus/pallets/xcmp-queue/src/bridging.rs b/cumulus/pallets/xcmp-queue/src/bridging.rs index 9db4b6e74c3987ae08a6d38eb75ffcacb9e5e713..eff4a37b0cef7033c15f2629e54fb7763a35a975 100644 --- a/cumulus/pallets/xcmp-queue/src/bridging.rs +++ b/cumulus/pallets/xcmp-queue/src/bridging.rs @@ -21,7 +21,7 @@ use frame_support::pallet_prelude::Get; /// both `OutboundXcmpStatus` and `InboundXcmpStatus` for defined `ParaId` if any of those is /// suspended. pub struct InAndOutXcmpChannelStatusProvider( - sp_std::marker::PhantomData<(SiblingBridgeHubParaId, Runtime)>, + core::marker::PhantomData<(SiblingBridgeHubParaId, Runtime)>, ); impl, Runtime: crate::Config> bp_xcm_bridge_hub_router::XcmChannelStatusProvider @@ -45,7 +45,7 @@ impl, Runtime: crate::Config> /// Adapter implementation for `bp_xcm_bridge_hub_router::XcmChannelStatusProvider` which checks /// only `OutboundXcmpStatus` for defined `SiblingParaId` if is suspended. pub struct OutXcmpChannelStatusProvider( - sp_std::marker::PhantomData<(SiblingBridgeHubParaId, Runtime)>, + core::marker::PhantomData<(SiblingBridgeHubParaId, Runtime)>, ); impl, Runtime: crate::Config> bp_xcm_bridge_hub_router::XcmChannelStatusProvider diff --git a/cumulus/pallets/xcmp-queue/src/lib.rs b/cumulus/pallets/xcmp-queue/src/lib.rs index 45126a9425d4c0400c7b76f55173339fd4c4a2bb..8c4446a925d4da281d11f09c9e3e3e3b4feb6697 100644 --- a/cumulus/pallets/xcmp-queue/src/lib.rs +++ b/cumulus/pallets/xcmp-queue/src/lib.rs @@ -50,6 +50,9 @@ pub mod bridging; pub mod weights; pub use weights::WeightInfo; +extern crate alloc; + +use alloc::vec::Vec; use bounded_collections::BoundedBTreeSet; use codec::{Decode, DecodeLimit, Encode, MaxEncodedLen}; use cumulus_primitives_core::{ @@ -69,7 +72,6 @@ use polkadot_runtime_parachains::FeeTracker; use scale_info::TypeInfo; use sp_core::MAX_POSSIBLE_ALLOCATION; use sp_runtime::{FixedU128, RuntimeDebug, Saturating, WeakBoundedVec}; -use sp_std::prelude::*; use xcm::{latest::prelude::*, VersionedLocation, VersionedXcm, WrapVersion, MAX_XCM_DECODE_DEPTH}; use xcm_builder::InspectMessageQueues; use xcm_executor::traits::ConvertOrigin; diff --git a/cumulus/pallets/xcmp-queue/src/migration.rs b/cumulus/pallets/xcmp-queue/src/migration.rs index b64982a893029f51aeb689d94d54066165ac40a3..d0657aaea9fd0d1daab6003b9721434c8ea769e1 100644 --- a/cumulus/pallets/xcmp-queue/src/migration.rs +++ b/cumulus/pallets/xcmp-queue/src/migration.rs @@ -19,6 +19,7 @@ pub mod v5; use crate::{Config, OverweightIndex, Pallet, QueueConfig, QueueConfigData, DEFAULT_POV_SIZE}; +use alloc::vec::Vec; use cumulus_primitives_core::XcmpMessageFormat; use frame_support::{ pallet_prelude::*, diff --git a/cumulus/pallets/xcmp-queue/src/migration/v5.rs b/cumulus/pallets/xcmp-queue/src/migration/v5.rs index 247adab7108fac8a278ee81827a9e65e27c320f0..818365f36f605ea3ddceceeb8654cf11ca690e44 100644 --- a/cumulus/pallets/xcmp-queue/src/migration/v5.rs +++ b/cumulus/pallets/xcmp-queue/src/migration/v5.rs @@ -17,6 +17,7 @@ //! Migrates the storage to version 5. use crate::*; +use alloc::vec::Vec; use cumulus_primitives_core::ListChannelInfos; use frame_support::{pallet_prelude::*, traits::UncheckedOnRuntimeUpgrade}; diff --git a/cumulus/parachains/chain-specs/asset-hub-kusama.json b/cumulus/parachains/chain-specs/asset-hub-kusama.json index 36cccd9b0b0dbad4a5f6c7240a69181ec7ffe5f3..58b8ac01922712234ad81a56fde825026af904e2 100644 --- a/cumulus/parachains/chain-specs/asset-hub-kusama.json +++ b/cumulus/parachains/chain-specs/asset-hub-kusama.json @@ -7,8 +7,8 @@ "/dns/kusama-asset-hub-connect-0.polkadot.io/tcp/443/wss/p2p/12D3KooWMzvdGcUXxacLdMQzRVrsP1mJrZHcrz8LtGbhLzve84Qx", "/dns/kusama-asset-hub-connect-1.polkadot.io/tcp/30334/p2p/12D3KooWQmGf5z3DU1kKcZoLzMNgdbP31ybjuwxS1VGLKMUjq5ez", "/dns/kusama-asset-hub-connect-1.polkadot.io/tcp/443/wss/p2p/12D3KooWQmGf5z3DU1kKcZoLzMNgdbP31ybjuwxS1VGLKMUjq5ez", - "/dns/boot.stake.plus/tcp/34333/p2p/12D3KooWAzSSZ7jLqMw1WPomYEKCYANQaKemXQ8BKoFvNEvfmdqR", - "/dns/boot.stake.plus/tcp/34334/wss/p2p/12D3KooWAzSSZ7jLqMw1WPomYEKCYANQaKemXQ8BKoFvNEvfmdqR", + "/dns/asset-hub-kusama.boot.stake.plus/tcp/30332/wss/p2p/12D3KooWGfJsBTxWttMwFkyBi6ZvEzAU3mvcVAzE7yFXMZuasicr", + "/dns/asset-hub-kusama.boot.stake.plus/tcp/31332/wss/p2p/12D3KooWK7hHQbFEhhgZURY7V4LzY6BkqLsnCCpEJ69eUF7ucPcE", "/dns/boot.metaspan.io/tcp/26052/p2p/12D3KooW9z9hKqe3mqYAp5UJMhZiCqhkTHyiR43fegnGmTJ3JAba", "/dns/boot.metaspan.io/tcp/26056/wss/p2p/12D3KooW9z9hKqe3mqYAp5UJMhZiCqhkTHyiR43fegnGmTJ3JAba", "/dns/boot.gatotech.network/tcp/33210/p2p/12D3KooWRMUYeWMPkadDG8baX9j1e95fspfp8MhPGym5BQza7Fm5", diff --git a/cumulus/parachains/chain-specs/asset-hub-polkadot.json b/cumulus/parachains/chain-specs/asset-hub-polkadot.json index f7f53f8d7246f42dda05901298831190e5d81802..3e46501b00785d9d92b3bde19e5dd08e00d7e86d 100644 --- a/cumulus/parachains/chain-specs/asset-hub-polkadot.json +++ b/cumulus/parachains/chain-specs/asset-hub-polkadot.json @@ -7,8 +7,8 @@ "/dns/polkadot-asset-hub-connect-0.polkadot.io/tcp/443/wss/p2p/12D3KooWLHqbcQtoBygf7GJgVjVa3TaeLuf7VbicNdooaCmQM2JZ", "/dns/polkadot-asset-hub-connect-1.polkadot.io/tcp/30334/p2p/12D3KooWNDrKSayoZXGGE2dRSFW2g1iGPq3fTZE2U39ma9yZGKd3", "/dns/polkadot-asset-hub-connect-1.polkadot.io/tcp/443/wss/p2p/12D3KooWNDrKSayoZXGGE2dRSFW2g1iGPq3fTZE2U39ma9yZGKd3", - "/dns/boot.stake.plus/tcp/35333/p2p/12D3KooWFrQjYaPZSSLLxEVmoaHFcrF6VoY4awG4KRSLaqy3JCdQ", - "/dns/boot.stake.plus/tcp/35334/wss/p2p/12D3KooWFrQjYaPZSSLLxEVmoaHFcrF6VoY4awG4KRSLaqy3JCdQ", + "/dns/asset-hub-polkadot.boot.stake.plus/tcp/30332/wss/p2p/12D3KooWJzTrFcc11AZKTMUmmLr5XLJ9qKVupZXkwHUMx4ULbwm2", + "/dns/asset-hub-polkadot.boot.stake.plus/tcp/31332/wss/p2p/12D3KooWNWF2zwxWDuZfXEzL29yeXAAubFy8tCCMjPwWLCZdLRqc", "/dns/boot.metaspan.io/tcp/16052/p2p/12D3KooWLwiJuvqQUB4kYaSjLenFKH9dWZhGZ4qi7pSb3sUYU651", "/dns/boot.metaspan.io/tcp/16056/wss/p2p/12D3KooWLwiJuvqQUB4kYaSjLenFKH9dWZhGZ4qi7pSb3sUYU651", "/dns/boot.gatotech.network/tcp/33110/p2p/12D3KooWKgwQfAeDoJARdtxFNNWfbYmcu6s4yUuSifnNoDgzHZgm", diff --git a/cumulus/parachains/chain-specs/asset-hub-westend.json b/cumulus/parachains/chain-specs/asset-hub-westend.json index b4334bdfe1243eb4d6726ab3464d619aebac394a..42717974a0b34e31420fe08ad51195dd3a1b2c4e 100644 --- a/cumulus/parachains/chain-specs/asset-hub-westend.json +++ b/cumulus/parachains/chain-specs/asset-hub-westend.json @@ -9,8 +9,8 @@ "/dns/westend-asset-hub-bootnode-1.polkadot.io/tcp/30335/ws/p2p/12D3KooWGL3hpWycWyeqyL9gHNnmmsL474WkPZdqraBHu4L6fQrW", "/dns/westend-asset-hub-connect-0.polkadot.io/tcp/443/wss/p2p/12D3KooWJaAfPyiye7ZQBuHengTJJoMrcaz7Jj1UzHiKdNxA1Nkd", "/dns/westend-asset-hub-connect-1.polkadot.io/tcp/443/wss/p2p/12D3KooWGL3hpWycWyeqyL9gHNnmmsL474WkPZdqraBHu4L6fQrW", - "/dns/boot.stake.plus/tcp/33333/p2p/12D3KooWNiB27rpXX7EYongoWWUeRKzLQxWGms6MQU2B9LX7Ztzo", - "/dns/boot.stake.plus/tcp/33334/wss/p2p/12D3KooWNiB27rpXX7EYongoWWUeRKzLQxWGms6MQU2B9LX7Ztzo", + "/dns/asset-hub-westend.boot.stake.plus/tcp/30332/wss/p2p/12D3KooWG4YUe7AfSxVwyLQBRRMU99krssmGAUghqUFoVY1iPkQs", + "/dns/asset-hub-westend.boot.stake.plus/tcp/31332/wss/p2p/12D3KooWFLR2UN6PMAUwNAjiWBAiEDoYcWRrtjDrUfRkdUssge4v", "/dns/boot.metaspan.io/tcp/36052/p2p/12D3KooWBCqfNb6Y39DXTr4UBWXyjuS3hcZM1qTbHhDXxF6HkAJJ", "/dns/boot.metaspan.io/tcp/36056/wss/p2p/12D3KooWBCqfNb6Y39DXTr4UBWXyjuS3hcZM1qTbHhDXxF6HkAJJ", "/dns/boot.gatotech.network/tcp/33310/p2p/12D3KooWMSW6hr8KcNBhGFN1bg8kYC76o67PnuDEbxRhxacW6dui", diff --git a/cumulus/parachains/chain-specs/bridge-hub-kusama.json b/cumulus/parachains/chain-specs/bridge-hub-kusama.json index 2c63b52d78395167f5a60e1b96ffede355b3eddc..36558b325bbf315144c69e8f6c4294bd6d5dfdff 100644 --- a/cumulus/parachains/chain-specs/bridge-hub-kusama.json +++ b/cumulus/parachains/chain-specs/bridge-hub-kusama.json @@ -7,8 +7,8 @@ "/dns/kusama-bridge-hub-connect-ew1-1.polkadot.io/tcp/30334/p2p/12D3KooWPcF9Yk4gYrMju9CyWCV69hAFXbYsnxCLogwLGu9QFTRn", "/dns/kusama-bridge-hub-connect-ew1-0.polkadot.io/tcp/443/wss/p2p/12D3KooWPQQPivrqQ51kRTDc2R1mtqwKT4GGtk2rapkY4FrwHrEp", "/dns/kusama-bridge-hub-connect-ew1-1.polkadot.io/tcp/443/wss/p2p/12D3KooWPcF9Yk4gYrMju9CyWCV69hAFXbYsnxCLogwLGu9QFTRn", - "/dns/boot.stake.plus/tcp/41333/p2p/12D3KooWBzbs2jsXjG5dipktGPKaUm9XWvkmeJFsEAGkVt946Aa7", - "/dns/boot.stake.plus/tcp/41334/wss/p2p/12D3KooWBzbs2jsXjG5dipktGPKaUm9XWvkmeJFsEAGkVt946Aa7", + "/dns/bridge-hub-kusama.boot.stake.plus/tcp/30332/wss/p2p/12D3KooWCujTih2WeQr51xSpopt5LoYVyXy3bgGgcN5ftPQViBmh", + "/dns/bridge-hub-kusama.boot.stake.plus/tcp/31332/wss/p2p/12D3KooWDSxWZ8RcuPfKSpybYHWUdhQHG328Euyo2PwkNUTXcXuw", "/dns/boot.metaspan.io/tcp/26032/p2p/12D3KooWKfuSaZrLNz43PDgM4inMALXRHTSh2WBuqQtZRq8zmT1Z", "/dns/boot.metaspan.io/tcp/26036/wss/p2p/12D3KooWKfuSaZrLNz43PDgM4inMALXRHTSh2WBuqQtZRq8zmT1Z", "/dns/boot.gatotech.network/tcp/33230/p2p/12D3KooWFQFmg8UqAYLDNc2onySB6o5LLvpbx3eXZVqz9YFxAmXs", diff --git a/cumulus/parachains/chain-specs/bridge-hub-polkadot.json b/cumulus/parachains/chain-specs/bridge-hub-polkadot.json index 7d3ba8357037d7310c56ed609cbc43e0359ca2bc..eb22e09035f34b85cecbbc923ea1e68081f14a8d 100644 --- a/cumulus/parachains/chain-specs/bridge-hub-polkadot.json +++ b/cumulus/parachains/chain-specs/bridge-hub-polkadot.json @@ -11,8 +11,8 @@ "/dns/polkadot-bridge-hub-boot-ng.dwellir.com/tcp/443/wss/p2p/12D3KooWPZ38PL3PhRVcUVYDNn7nRcZF8MykmWWLBKeDV2yna1vV", "/dns/boot.gatotech.network/tcp/33130/p2p/12D3KooWCnFzfEdd7MwUNrrDv66FuS2DM5MGuiaB4y48XS7qNjF6", "/dns/boot.gatotech.network/tcp/35130/wss/p2p/12D3KooWCnFzfEdd7MwUNrrDv66FuS2DM5MGuiaB4y48XS7qNjF6", - "/dns/boot.stake.plus/tcp/42333/p2p/12D3KooWEoTCu22Uab6prbfcD1FPpPZmfhkAVeMZQJ3fHnkCVmJz", - "/dns/boot.stake.plus/tcp/42334/wss/p2p/12D3KooWEoTCu22Uab6prbfcD1FPpPZmfhkAVeMZQJ3fHnkCVmJz", + "/dns/bridge-hub-polkadot.boot.stake.plus/tcp/30332/wss/p2p/12D3KooWGqVn69EWriuszxcuBVMgTtpKUHYcULEiuLiqkC3kf35F", + "/dns/bridge-hub-polkadot.boot.stake.plus/tcp/31332/wss/p2p/12D3KooWMiMJbunJa7ETaeanKB7hgchjQEbmhmtNPRRiHYtZHCTZ", "/dns/bridge-hub-polkadot-bootnode.turboflakes.io/tcp/30610/p2p/12D3KooWNEgaQRQHJHvGDh8Rg4RyLmDCCz3yAf2gAdHZZJAUUD8Q", "/dns/bridge-hub-polkadot-bootnode.turboflakes.io/tcp/30710/wss/p2p/12D3KooWNEgaQRQHJHvGDh8Rg4RyLmDCCz3yAf2gAdHZZJAUUD8Q", "/dns/boot.metaspan.io/tcp/16032/p2p/12D3KooWQTfRnrK3FfbrotpSP5RVJbjBHVBSu8VSzhj9qcvjaqnZ", diff --git a/cumulus/parachains/chain-specs/bridge-hub-westend.json b/cumulus/parachains/chain-specs/bridge-hub-westend.json index f98a046040f2226b5345d4d793e15ec3e24d6c43..40c7c7460c2359c855adac91a0dbf2dbec2c008b 100644 --- a/cumulus/parachains/chain-specs/bridge-hub-westend.json +++ b/cumulus/parachains/chain-specs/bridge-hub-westend.json @@ -11,8 +11,8 @@ "/dns/westend-bridge-hub-collator-node-1.parity-testnet.parity.io/tcp/443/wss/p2p/12D3KooWBpvudthz61XC4oP2YYFFJdhWohBeQ1ffn1BMSGWhapjd", "/dns/westend-bridge-hub-boot-ng.dwellir.com/tcp/30338/p2p/12D3KooWJWWRYTAwBLqYkh7iMBGDr5ouJ3MHj7M3fZ7zWS4zEk6F", "/dns/westend-bridge-hub-boot-ng.dwellir.com/tcp/443/wss/p2p/12D3KooWJWWRYTAwBLqYkh7iMBGDr5ouJ3MHj7M3fZ7zWS4zEk6F", - "/dns/boot.stake.plus/tcp/40333/p2p/12D3KooWPGMsGPdGJx6HrByiKUyz91wgUHmjG5UXTmkJ9tUphAQn", - "/dns/boot.stake.plus/tcp/40334/wss/p2p/12D3KooWPGMsGPdGJx6HrByiKUyz91wgUHmjG5UXTmkJ9tUphAQn", + "/dns/bridge-hub-westend.boot.stake.plus/tcp/30332/wss/p2p/12D3KooW9rqdajWEpC3i65zaTVR1ER2RmY6e26vndPsKhBB6WJ1k", + "/dns/bridge-hub-westend.boot.stake.plus/tcp/31332/wss/p2p/12D3KooWN55mz6EQb5nrCgTiNL6nroVrRXygCiFDvHpeKk97Jqqc", "/dns/boot.gatotech.network/tcp/33330/p2p/12D3KooWJHG6qznPzTSEbuujHNcvyzBZcR9zNRPFcXWUaoVWZBEw", "/dns/boot.gatotech.network/tcp/35330/wss/p2p/12D3KooWJHG6qznPzTSEbuujHNcvyzBZcR9zNRPFcXWUaoVWZBEw", "/dns/bridge-hub-westend-bootnode.turboflakes.io/tcp/30620/p2p/12D3KooWLeExhPWCDUjcxCdzxTP5TpPbNBVG5t9MPvk1dZUM5naU", diff --git a/cumulus/parachains/chain-specs/collectives-polkadot.json b/cumulus/parachains/chain-specs/collectives-polkadot.json index a6ba01ffa394dfdba05e65014006f10eb68ea858..5ccccbec905326da8ca7b45013f38e1bb5da9926 100644 --- a/cumulus/parachains/chain-specs/collectives-polkadot.json +++ b/cumulus/parachains/chain-specs/collectives-polkadot.json @@ -7,8 +7,8 @@ "/dns/polkadot-collectives-connect-ew6-1.polkadot.io/tcp/30334/p2p/12D3KooWC9BwKMDyRUTXsE7teSmoKMgbyxqAp3zi2MTGRJR5nhCL", "/dns/polkadot-collectives-connect-ew6-0.polkadot.io/tcp/443/wss/p2p/12D3KooWLDZT5gAjMtC8fojiCwiz17SC61oeX2C7GWBCqqf9TwVD", "/dns/polkadot-collectives-connect-ew6-1.polkadot.io/tcp/443/wss/p2p/12D3KooWC9BwKMDyRUTXsE7teSmoKMgbyxqAp3zi2MTGRJR5nhCL", - "/dns/boot.stake.plus/tcp/37333/p2p/12D3KooWRgFfEtwPo3xorKGYALRHRteKNgF37iN9q8xTLPYc34LA", - "/dns/boot.stake.plus/tcp/37334/wss/p2p/12D3KooWRgFfEtwPo3xorKGYALRHRteKNgF37iN9q8xTLPYc34LA", + "/dns/collectives-polkadot.boot.stake.plus/tcp/30332/wss/p2p/12D3KooWKLVfjCpW2syecz39UPe4QkJhwME9HUehBvf8oRcT4kot", + "/dns/collectives-polkadot.boot.stake.plus/tcp/31332/wss/p2p/12D3KooWBCewTdMPoXNvs1ky1VLidMdS28Jnh8fNbCP81FYiQHn4", "/dns/boot.metaspan.io/tcp/16072/p2p/12D3KooWJWTTu2t2yg5bFRH6tjEpfzKwZir5R9JRRjQpgFPXdDfp", "/dns/boot.metaspan.io/tcp/16076/wss/p2p/12D3KooWJWTTu2t2yg5bFRH6tjEpfzKwZir5R9JRRjQpgFPXdDfp", "/dns/boot.gatotech.network/tcp/33120/p2p/12D3KooWGZsa9tSeLQ1VeC996e1YsCPuyRYMipHQuXikPjcKcpVQ", diff --git a/cumulus/parachains/chain-specs/collectives-westend.json b/cumulus/parachains/chain-specs/collectives-westend.json index 6182218d3670cfc661fe528d715bbf222c747900..f583eddcef1f145500a68f48965cc15f8333a3a7 100644 --- a/cumulus/parachains/chain-specs/collectives-westend.json +++ b/cumulus/parachains/chain-specs/collectives-westend.json @@ -9,8 +9,8 @@ "/dns/westend-collectives-collator-node-1.parity-testnet.parity.io/tcp/30335/ws/p2p/12D3KooWAujYtHbCs4MiDD57JNTntTJnYnikfnaPa7JdnMyAUrHB", "/dns/westend-collectives-collator-0.polkadot.io/tcp/443/wss/p2p/12D3KooWBMAuyzQu3yAf8YXyoyxsSzSsgoaqAepgnNyQcPaPjPXe", "/dns/westend-collectives-collator-1.polkadot.io/tcp/443/wss/p2p/12D3KooWAujYtHbCs4MiDD57JNTntTJnYnikfnaPa7JdnMyAUrHB", - "/dns/boot.stake.plus/tcp/38333/p2p/12D3KooWQoVsFCfgu21iu6kdtQsU9T6dPn1wsyLn1U34yPerR6zQ", - "/dns/boot.stake.plus/tcp/38334/wss/p2p/12D3KooWQoVsFCfgu21iu6kdtQsU9T6dPn1wsyLn1U34yPerR6zQ", + "/dns/collectives-westend.boot.stake.plus/tcp/30332/wss/p2p/12D3KooWH4MtT6T9BE1nm2TL9ABmY3mSr61mZcge37pEch7Qw15S", + "/dns/collectives-westend.boot.stake.plus/tcp/31332/wss/p2p/12D3KooWBMRn31J3wJh3eu96XFUiAmgP3eKUxyNCv7249NXrAarZ", "/dns/boot.metaspan.io/tcp/36072/p2p/12D3KooWEf2QXWq5pAbFJLfbnexA7KYtRRDSPkqTP64n1KtdsdV2", "/dns/boot.metaspan.io/tcp/36076/wss/p2p/12D3KooWEf2QXWq5pAbFJLfbnexA7KYtRRDSPkqTP64n1KtdsdV2", "/dns/boot.gatotech.network/tcp/33320/p2p/12D3KooWMedtdBGiSn7HLZusHwafXkZAdmWD18ciGQBfS4X1fv9K", diff --git a/cumulus/parachains/chain-specs/coretime-kusama.json b/cumulus/parachains/chain-specs/coretime-kusama.json index f9310d6c7cc6e14f54b4cc6620bece8b626725d1..3e4ffae403bdb7118fe94befc32e15f497e71fcc 100644 --- a/cumulus/parachains/chain-specs/coretime-kusama.json +++ b/cumulus/parachains/chain-specs/coretime-kusama.json @@ -9,8 +9,8 @@ "/dns/kusama-coretime-connect-a-1.polkadot.io/tcp/443/wss/p2p/12D3KooWAGFiMZDF9RxdacrkenzGdo8nhfSe9EXofHc5mHeJ9vGX", "/dns/boot.metaspan.io/tcp/33024/p2p/12D3KooWPmwMhG54ixDv2b3sCfYEJ1DWDrjaduBCBwqFFdqvVsmS", "/dns/boot.metaspan.io/tcp/33026/wss/p2p/12D3KooWPmwMhG54ixDv2b3sCfYEJ1DWDrjaduBCBwqFFdqvVsmS", - "/dns/boot.stake.plus/tcp/47333/p2p/12D3KooWKKKoyywqdkkpZzCzVWt5VXEk5PbS9tUm635L5ohyf8bU", - "/dns/boot.stake.plus/tcp/47334/wss/p2p/12D3KooWKKKoyywqdkkpZzCzVWt5VXEk5PbS9tUm635L5ohyf8bU", + "/dns/coretime-kusama.boot.stake.plus/tcp/30332/wss/p2p/12D3KooWDG2iif5zcFB7E1huEZUPAauEP34mqt8UVUacHTxC1wJY", + "/dns/coretime-kusama.boot.stake.plus/tcp/31332/wss/p2p/12D3KooWAcZ2FG9uPa3YXzk4Mots94Zm6NYzKKaWvyAFEu2k4WMy", "/dns/coretime-kusama-boot-ng.dwellir.com/tcp/30358/p2p/12D3KooWSoPisbYQTAj79Dtsxx1qAiEFTouvXCfNJ1A3SQWQzuct", "/dns/coretime-kusama-boot-ng.dwellir.com/tcp/443/wss/p2p/12D3KooWSoPisbYQTAj79Dtsxx1qAiEFTouvXCfNJ1A3SQWQzuct", "/dns/boot.gatotech.network/tcp/33250/p2p/12D3KooWMpgcWr5pb7em7rWaQV4J6P2kn3YCjCeP1ESMsJPffn1a", diff --git a/cumulus/parachains/chain-specs/coretime-westend.json b/cumulus/parachains/chain-specs/coretime-westend.json index ca723aacd881cbe56dbedc123b062465c68ec40b..42f67526c29ac5bcf94fd3741a577c68667fc226 100644 --- a/cumulus/parachains/chain-specs/coretime-westend.json +++ b/cumulus/parachains/chain-specs/coretime-westend.json @@ -17,8 +17,8 @@ "/dns/boot-node.helikon.io/tcp/9422/wss/p2p/12D3KooWFBPartM873MNm1AmVK3etUz34cAE9A9rwPztPno2epQ3", "/dns/coretime-westend-boot-ng.dwellir.com/tcp/443/wss/p2p/12D3KooWHewSFwJueRprNZNfkncdjud9DrGzvP1qfmgPd7VK66gw", "/dns/coretime-westend-boot-ng.dwellir.com/tcp/30356/p2p/12D3KooWHewSFwJueRprNZNfkncdjud9DrGzvP1qfmgPd7VK66gw", - "/dns/boot.stake.plus/tcp/45333/p2p/12D3KooWEFQapPJXNyZMt892qXZ8YgDuHWt2vhLeRvny98oUjEto", - "/dns/boot.stake.plus/tcp/45334/wss/p2p/12D3KooWEFQapPJXNyZMt892qXZ8YgDuHWt2vhLeRvny98oUjEto", + "/dns/coretime-westend.boot.stake.plus/tcp/30332/wss/p2p/12D3KooWBFffQL6MvzM9rc8yVwR1Z8GcC9jfLhZpU2NRjsAAFeTX", + "/dns/coretime-westend.boot.stake.plus/tcp/31332/wss/p2p/12D3KooWH2qnUkKjV9Sevp8soFXdcs6r1mj2D2DAoBH8L1ziLzs3", "/dns/coretime-westend-bootnode.radiumblock.com/tcp/30333/p2p/12D3KooWK7Zj1mCPg6h3eMp7v6akJ1o6AocRr59NLusDwBXQgrhw", "/dns/coretime-westend-bootnode.radiumblock.com/tcp/30336/wss/p2p/12D3KooWK7Zj1mCPg6h3eMp7v6akJ1o6AocRr59NLusDwBXQgrhw", "/dns/ibp-boot-westend-coretime.luckyfriday.io/tcp/443/wss/p2p/12D3KooWBzfzNhvyRVTb9KtNYpkRf26yTRHorBZR2LmYhH5ArCey", diff --git a/cumulus/parachains/chain-specs/people-kusama.json b/cumulus/parachains/chain-specs/people-kusama.json index 3352cb25a2898f5442b1e28b340def69fc4168f2..300b9fcfb183c262ce1fc2279d6ca7bf457bc1db 100644 --- a/cumulus/parachains/chain-specs/people-kusama.json +++ b/cumulus/parachains/chain-specs/people-kusama.json @@ -26,7 +26,9 @@ "/dns/boot.metaspan.io/tcp/25068/p2p/12D3KooWDoDLtLvQi8hhFVyubPZhaYuAwSAJrPFtyGWJ2NSfBiyP", "/dns/boot.metaspan.io/tcp/25069/wss/p2p/12D3KooWDoDLtLvQi8hhFVyubPZhaYuAwSAJrPFtyGWJ2NSfBiyP", "/dns/ibp-boot-kusama-people.luckyfriday.io/tcp/30342/p2p/12D3KooWM4bRafMH2StfBEQtyj5cMWfGLYbuikCZmvKv9m1MQVPn", - "/dns/ibp-boot-kusama-people.luckyfriday.io/tcp/443/wss/p2p/12D3KooWM4bRafMH2StfBEQtyj5cMWfGLYbuikCZmvKv9m1MQVPn" + "/dns/ibp-boot-kusama-people.luckyfriday.io/tcp/443/wss/p2p/12D3KooWM4bRafMH2StfBEQtyj5cMWfGLYbuikCZmvKv9m1MQVPn", + "/dns4/people-kusama.boot.stake.plus/tcp/30332/wss/p2p/12D3KooWRuKr3ogzXwD8zE2CTWenGdy8vSfViAjYMwGiwvFCsz8n", + "/dns/people-kusama.boot.stake.plus/tcp/31332/wss/p2p/12D3KooWFkDKdFxBJFyj9zumuJ4Mmctec2GqdYHcKYq8MTVe8dxf" ], "telemetryEndpoints": null, "protocolId": null, diff --git a/cumulus/parachains/chain-specs/people-westend.json b/cumulus/parachains/chain-specs/people-westend.json index 8bfbb33264150f5d28fa80a93128f9708998db53..ac24b2e6435922e67e2cb07d66b90b2bac2fa5b8 100644 --- a/cumulus/parachains/chain-specs/people-westend.json +++ b/cumulus/parachains/chain-specs/people-westend.json @@ -17,8 +17,8 @@ "/dns/boot-node.helikon.io/tcp/9522/wss/p2p/12D3KooWHhZk21Wzvsd3Un1Cp63diXqr6idbG1MEiUWaitUZuX4c", "/dns/boot.metaspan.io/tcp/35068/p2p/12D3KooWAtw8ybFXNmNdTUsvt2gfKwtuea9wDQT2b8FpbVNKYGwc", "/dns/boot.metaspan.io/tcp/35069/wss/p2p/12D3KooWAtw8ybFXNmNdTUsvt2gfKwtuea9wDQT2b8FpbVNKYGwc", - "/dns/boot.stake.plus/tcp/46333/p2p/12D3KooWLNWUF4H5WE3dy2rPB56gVcR48XY2rHwEaZ6pGTK6HYFi", - "/dns/boot.stake.plus/tcp/46334/wss/p2p/12D3KooWLNWUF4H5WE3dy2rPB56gVcR48XY2rHwEaZ6pGTK6HYFi", + "/dns/people-westend.boot.stake.plus/tcp/30332/wss/p2p/12D3KooWD5T1YN8oZUEsRXWod69kYH67jrSXHm6tSvs7RvH4Cb3p", + "/dns/people-westend.boot.stake.plus/tcp/31332/wss/p2p/12D3KooWSByQrekhxx7pyDMTZcnnWBBFdj2LtqN9QtTCBDckc2zi", "/dns/boot.gatotech.network/tcp/33340/p2p/12D3KooWHwURYtEHpexfrZa8k8hVgVi5FTFr4N8HBnn9kPDsWfgA", "/dns/boot.gatotech.network/tcp/35340/wss/p2p/12D3KooWHwURYtEHpexfrZa8k8hVgVi5FTFr4N8HBnn9kPDsWfgA", "/dns/people-westend.bootnode.amforc.com/tcp/29999/wss/p2p/12D3KooWE1btdwDhNpApg8BEe2QwJxdVDtz6a6BRhgTeUh9HMhWs", diff --git a/cumulus/parachains/common/Cargo.toml b/cumulus/parachains/common/Cargo.toml index 6eac9a09672675c3cb46d1eb49392bb0651eb7dd..6d436bdf799a4f7682ced2098f4926ec9bc50379 100644 --- a/cumulus/parachains/common/Cargo.toml +++ b/cumulus/parachains/common/Cargo.toml @@ -29,7 +29,6 @@ sp-consensus-aura = { workspace = true } sp-core = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } # Polkadot pallet-xcm = { workspace = true } @@ -73,7 +72,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", "xcm-executor/std", "xcm/std", ] diff --git a/cumulus/parachains/common/src/impls.rs b/cumulus/parachains/common/src/impls.rs index 16cda1a4ed83850f4e67765a5e7092dad4a24305..42ea50c75a8d4e207ffa6b6ad7682013218de64d 100644 --- a/cumulus/parachains/common/src/impls.rs +++ b/cumulus/parachains/common/src/impls.rs @@ -16,6 +16,8 @@ //! Auxiliary struct/enums for parachain runtimes. //! Taken from polkadot/runtime/common (at a21cd64) and adapted for parachains. +use alloc::boxed::Box; +use core::marker::PhantomData; use frame_support::traits::{ fungible, fungibles, tokens::imbalance::ResolveTo, Contains, ContainsPair, Currency, Defensive, Get, Imbalance, OnUnbalanced, OriginTrait, @@ -23,7 +25,6 @@ use frame_support::traits::{ use pallet_asset_tx_payment::HandleCredit; use pallet_collator_selection::StakingPotAccountId; use sp_runtime::traits::Zero; -use sp_std::{marker::PhantomData, prelude::*}; use xcm::latest::{ Asset, AssetId, Fungibility, Fungibility::Fungible, Junction, Junctions::Here, Location, Parent, WeightLimit, diff --git a/cumulus/parachains/common/src/lib.rs b/cumulus/parachains/common/src/lib.rs index b01d623d2b93da529f37bbfd8cf139ea5b98d9ae..3cffb69daac3fae6d5729a985489433f442bf22c 100644 --- a/cumulus/parachains/common/src/lib.rs +++ b/cumulus/parachains/common/src/lib.rs @@ -15,6 +15,8 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + pub mod impls; pub mod message_queue; pub mod xcm_config; diff --git a/cumulus/parachains/common/src/message_queue.rs b/cumulus/parachains/common/src/message_queue.rs index 0c9f4b840c9166ba9380f06970ad15bb1cac14c6..511d6243cb8c47a0e137f9eec03bbb1afdf5e644 100644 --- a/cumulus/parachains/common/src/message_queue.rs +++ b/cumulus/parachains/common/src/message_queue.rs @@ -16,10 +16,10 @@ //! Helpers to deal with configuring the message queue in the runtime. +use core::marker::PhantomData; use cumulus_primitives_core::{AggregateMessageOrigin, ParaId}; use frame_support::traits::{QueueFootprint, QueuePausedQuery}; use pallet_message_queue::OnQueueChanged; -use sp_std::marker::PhantomData; /// Narrow the scope of the `Inner` query from `AggregateMessageOrigin` to `ParaId`. /// diff --git a/cumulus/parachains/common/src/xcm_config.rs b/cumulus/parachains/common/src/xcm_config.rs index a9756af7aed245ea792d12addbbb2fff529eedaf..7c58a2b2405c73477b0b88b95f99af870fdb5c90 100644 --- a/cumulus/parachains/common/src/xcm_config.rs +++ b/cumulus/parachains/common/src/xcm_config.rs @@ -14,13 +14,13 @@ // limitations under the License. use crate::impls::AccountIdOf; +use core::marker::PhantomData; use cumulus_primitives_core::{IsSystem, ParaId}; use frame_support::{ traits::{fungibles::Inspect, tokens::ConversionToAssetBalance, Contains, ContainsPair}, weights::Weight, }; use sp_runtime::traits::Get; -use sp_std::marker::PhantomData; use xcm::latest::prelude::*; /// A `ChargeFeeInFungibles` implementation that converts the output of diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-rococo/src/lib.rs b/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-rococo/src/lib.rs index d8b8edaf2409ba1da0aef01874792d6ef21e6a8a..5ef0993f70a1ce33daa68ec23b474716e6bee956 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-rococo/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-rococo/src/lib.rs @@ -17,6 +17,7 @@ pub mod genesis; pub use bridge_hub_rococo_runtime::{ xcm_config::XcmConfig as BridgeHubRococoXcmConfig, EthereumBeaconClient, EthereumInboundQueue, + ExistentialDeposit as BridgeHubRococoExistentialDeposit, RuntimeOrigin as BridgeHubRococoRuntimeOrigin, }; diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-westend/src/lib.rs b/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-westend/src/lib.rs index f701b3096994a3da7bd59726bedb0802e1b14276..feb59c411c8df488c748fe79e3fd485757fd0de0 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-westend/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-westend/src/lib.rs @@ -15,7 +15,10 @@ pub mod genesis; -pub use bridge_hub_westend_runtime::xcm_config::XcmConfig as BridgeHubWestendXcmConfig; +pub use bridge_hub_westend_runtime::{ + xcm_config::XcmConfig as BridgeHubWestendXcmConfig, + ExistentialDeposit as BridgeHubWestendExistentialDeposit, +}; // Substrate use frame_support::traits::OnInitialize; diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/coretime/coretime-rococo/Cargo.toml b/cumulus/parachains/integration-tests/emulated/chains/parachains/coretime/coretime-rococo/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..6af3f270a905f504b471374d0b29687f766409e4 --- /dev/null +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/coretime/coretime-rococo/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "coretime-rococo-emulated-chain" +version = "0.0.0" +authors.workspace = true +edition.workspace = true +license = "Apache-2.0" +description = "Coretime Rococo emulated chain" +publish = false + +[lints] +workspace = true + +[dependencies] + +# Substrate +sp-core = { workspace = true } +frame-support = { workspace = true } + +# Cumulus +parachains-common = { workspace = true, default-features = true } +cumulus-primitives-core = { workspace = true } +coretime-rococo-runtime = { workspace = true, default-features = true } +emulated-integration-tests-common = { workspace = true } +testnet-parachains-constants = { features = ["rococo"], workspace = true, default-features = true } diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/coretime/coretime-rococo/src/genesis.rs b/cumulus/parachains/integration-tests/emulated/chains/parachains/coretime/coretime-rococo/src/genesis.rs new file mode 100644 index 0000000000000000000000000000000000000000..f72de52c4932474243f1bb06b775145df11779b6 --- /dev/null +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/coretime/coretime-rococo/src/genesis.rs @@ -0,0 +1,66 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Substrate +use sp_core::storage::Storage; + +// Cumulus +use emulated_integration_tests_common::{ + accounts, build_genesis_storage, collators, SAFE_XCM_VERSION, +}; +use parachains_common::Balance; + +pub const PARA_ID: u32 = 1005; +pub const ED: Balance = testnet_parachains_constants::rococo::currency::EXISTENTIAL_DEPOSIT; + +pub fn genesis() -> Storage { + let genesis_config = coretime_rococo_runtime::RuntimeGenesisConfig { + system: coretime_rococo_runtime::SystemConfig::default(), + balances: coretime_rococo_runtime::BalancesConfig { + balances: accounts::init_balances().iter().cloned().map(|k| (k, ED * 4096)).collect(), + }, + parachain_info: coretime_rococo_runtime::ParachainInfoConfig { + parachain_id: PARA_ID.into(), + ..Default::default() + }, + collator_selection: coretime_rococo_runtime::CollatorSelectionConfig { + invulnerables: collators::invulnerables().iter().cloned().map(|(acc, _)| acc).collect(), + candidacy_bond: ED * 16, + ..Default::default() + }, + session: coretime_rococo_runtime::SessionConfig { + keys: collators::invulnerables() + .into_iter() + .map(|(acc, aura)| { + ( + acc.clone(), // account id + acc, // validator id + coretime_rococo_runtime::SessionKeys { aura }, // session keys + ) + }) + .collect(), + }, + polkadot_xcm: coretime_rococo_runtime::PolkadotXcmConfig { + safe_xcm_version: Some(SAFE_XCM_VERSION), + ..Default::default() + }, + ..Default::default() + }; + + build_genesis_storage( + &genesis_config, + coretime_rococo_runtime::WASM_BINARY.expect("WASM binary was not built, please build it!"), + ) +} diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/coretime/coretime-rococo/src/lib.rs b/cumulus/parachains/integration-tests/emulated/chains/parachains/coretime/coretime-rococo/src/lib.rs new file mode 100644 index 0000000000000000000000000000000000000000..a15303a22e12d44020364fe173000ad4ded467d8 --- /dev/null +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/coretime/coretime-rococo/src/lib.rs @@ -0,0 +1,53 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +pub use coretime_rococo_runtime; + +pub mod genesis; + +// Substrate +use frame_support::traits::OnInitialize; + +// Cumulus +use emulated_integration_tests_common::{ + impl_accounts_helpers_for_parachain, impl_assert_events_helpers_for_parachain, + impls::Parachain, xcm_emulator::decl_test_parachains, +}; + +// CoretimeRococo Parachain declaration +decl_test_parachains! { + pub struct CoretimeRococo { + genesis = genesis::genesis(), + on_init = { + coretime_rococo_runtime::AuraExt::on_initialize(1); + }, + runtime = coretime_rococo_runtime, + core = { + XcmpMessageHandler: coretime_rococo_runtime::XcmpQueue, + LocationToAccountId: coretime_rococo_runtime::xcm_config::LocationToAccountId, + ParachainInfo: coretime_rococo_runtime::ParachainInfo, + MessageOrigin: cumulus_primitives_core::AggregateMessageOrigin, + }, + pallets = { + PolkadotXcm: coretime_rococo_runtime::PolkadotXcm, + Balances: coretime_rococo_runtime::Balances, + Broker: coretime_rococo_runtime::Broker, + } + }, +} + +// CoretimeRococo implementation +impl_accounts_helpers_for_parachain!(CoretimeRococo); +impl_assert_events_helpers_for_parachain!(CoretimeRococo); diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/coretime/coretime-westend/Cargo.toml b/cumulus/parachains/integration-tests/emulated/chains/parachains/coretime/coretime-westend/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..895a984eccb2d049d849f8cf65b44cc667990e4f --- /dev/null +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/coretime/coretime-westend/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "coretime-westend-emulated-chain" +version = "0.0.0" +authors.workspace = true +edition.workspace = true +license = "Apache-2.0" +description = "Coretime Westend emulated chain" +publish = false + +[lints] +workspace = true + +[dependencies] + +# Substrate +sp-core = { workspace = true } +frame-support = { workspace = true } + +# Cumulus +parachains-common = { workspace = true, default-features = true } +cumulus-primitives-core = { workspace = true } +coretime-westend-runtime = { workspace = true, default-features = true } +emulated-integration-tests-common = { workspace = true } +testnet-parachains-constants = { features = ["westend"], workspace = true, default-features = true } diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/coretime/coretime-westend/src/genesis.rs b/cumulus/parachains/integration-tests/emulated/chains/parachains/coretime/coretime-westend/src/genesis.rs new file mode 100644 index 0000000000000000000000000000000000000000..222ffe7a63ab48d007496db31114b769a335b7bb --- /dev/null +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/coretime/coretime-westend/src/genesis.rs @@ -0,0 +1,66 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Substrate +use sp_core::storage::Storage; + +// Cumulus +use emulated_integration_tests_common::{ + accounts, build_genesis_storage, collators, SAFE_XCM_VERSION, +}; +use parachains_common::Balance; + +pub const PARA_ID: u32 = 1005; +pub const ED: Balance = testnet_parachains_constants::westend::currency::EXISTENTIAL_DEPOSIT; + +pub fn genesis() -> Storage { + let genesis_config = coretime_westend_runtime::RuntimeGenesisConfig { + system: coretime_westend_runtime::SystemConfig::default(), + balances: coretime_westend_runtime::BalancesConfig { + balances: accounts::init_balances().iter().cloned().map(|k| (k, ED * 4096)).collect(), + }, + parachain_info: coretime_westend_runtime::ParachainInfoConfig { + parachain_id: PARA_ID.into(), + ..Default::default() + }, + collator_selection: coretime_westend_runtime::CollatorSelectionConfig { + invulnerables: collators::invulnerables().iter().cloned().map(|(acc, _)| acc).collect(), + candidacy_bond: ED * 16, + ..Default::default() + }, + session: coretime_westend_runtime::SessionConfig { + keys: collators::invulnerables() + .into_iter() + .map(|(acc, aura)| { + ( + acc.clone(), // account id + acc, // validator id + coretime_westend_runtime::SessionKeys { aura }, // session keys + ) + }) + .collect(), + }, + polkadot_xcm: coretime_westend_runtime::PolkadotXcmConfig { + safe_xcm_version: Some(SAFE_XCM_VERSION), + ..Default::default() + }, + ..Default::default() + }; + + build_genesis_storage( + &genesis_config, + coretime_westend_runtime::WASM_BINARY.expect("WASM binary was not built, please build it!"), + ) +} diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/coretime/coretime-westend/src/lib.rs b/cumulus/parachains/integration-tests/emulated/chains/parachains/coretime/coretime-westend/src/lib.rs new file mode 100644 index 0000000000000000000000000000000000000000..41949843b02be666c7c95a404ed89326f2e59983 --- /dev/null +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/coretime/coretime-westend/src/lib.rs @@ -0,0 +1,53 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +pub use coretime_westend_runtime; + +pub mod genesis; + +// Substrate +use frame_support::traits::OnInitialize; + +// Cumulus +use emulated_integration_tests_common::{ + impl_accounts_helpers_for_parachain, impl_assert_events_helpers_for_parachain, + impls::Parachain, xcm_emulator::decl_test_parachains, +}; + +// CoretimeWestend Parachain declaration +decl_test_parachains! { + pub struct CoretimeWestend { + genesis = genesis::genesis(), + on_init = { + coretime_westend_runtime::AuraExt::on_initialize(1); + }, + runtime = coretime_westend_runtime, + core = { + XcmpMessageHandler: coretime_westend_runtime::XcmpQueue, + LocationToAccountId: coretime_westend_runtime::xcm_config::LocationToAccountId, + ParachainInfo: coretime_westend_runtime::ParachainInfo, + MessageOrigin: cumulus_primitives_core::AggregateMessageOrigin, + }, + pallets = { + PolkadotXcm: coretime_westend_runtime::PolkadotXcm, + Balances: coretime_westend_runtime::Balances, + Broker: coretime_westend_runtime::Broker, + } + }, +} + +// CoretimeWestend implementation +impl_accounts_helpers_for_parachain!(CoretimeWestend); +impl_assert_events_helpers_for_parachain!(CoretimeWestend); diff --git a/cumulus/parachains/integration-tests/emulated/common/src/macros.rs b/cumulus/parachains/integration-tests/emulated/common/src/macros.rs index 6f6bbe41e01bd208ee6d40a9f3b4ba8f98f7975b..b11adacbde5cb6ddfbdf7cf9a1c192aa20ef7584 100644 --- a/cumulus/parachains/integration-tests/emulated/common/src/macros.rs +++ b/cumulus/parachains/integration-tests/emulated/common/src/macros.rs @@ -27,7 +27,7 @@ pub use xcm::{ prelude::{ AccountId32, All, Asset, AssetId, BuyExecution, DepositAsset, ExpectTransactStatus, Fungible, Here, Location, MaybeErrorCode, OriginKind, RefundSurplus, Transact, Unlimited, - VersionedXcm, WeightLimit, WithdrawAsset, Xcm, + VersionedAssets, VersionedXcm, WeightLimit, WithdrawAsset, Xcm, }, v3::Location as V3Location, }; @@ -130,3 +130,279 @@ macro_rules! test_parachain_is_trusted_teleporter { } }; } + +#[macro_export] +macro_rules! test_relay_is_trusted_teleporter { + ( $sender_relay:ty, $sender_xcm_config:ty, vec![$( $receiver_para:ty ),+], ($assets:expr, $amount:expr) ) => { + $crate::macros::paste::paste! { + // init Origin variables + let sender = [<$sender_relay Sender>]::get(); + let mut relay_sender_balance_before = + <$sender_relay as $crate::macros::Chain>::account_data_of(sender.clone()).free; + let origin = <$sender_relay as $crate::macros::Chain>::RuntimeOrigin::signed(sender.clone()); + let fee_asset_item = 0; + let weight_limit = $crate::macros::WeightLimit::Unlimited; + + $( + { + // init Destination variables + let receiver = [<$receiver_para Receiver>]::get(); + let para_receiver_balance_before = + <$receiver_para as $crate::macros::Chain>::account_data_of(receiver.clone()).free; + let para_destination = + <$sender_relay>::child_location_of(<$receiver_para>::para_id()); + let beneficiary: Location = + $crate::macros::AccountId32 { network: None, id: receiver.clone().into() }.into(); + + // Send XCM message from Relay + <$sender_relay>::execute_with(|| { + assert_ok!(<$sender_relay as [<$sender_relay Pallet>]>::XcmPallet::limited_teleport_assets( + origin.clone(), + bx!(para_destination.clone().into()), + bx!(beneficiary.clone().into()), + bx!($assets.clone().into()), + fee_asset_item, + weight_limit.clone(), + )); + + type RuntimeEvent = <$sender_relay as $crate::macros::Chain>::RuntimeEvent; + + assert_expected_events!( + $sender_relay, + vec![ + RuntimeEvent::XcmPallet( + $crate::macros::pallet_xcm::Event::Attempted { outcome: Outcome::Complete { .. } } + ) => {}, + RuntimeEvent::Balances( + $crate::macros::pallet_balances::Event::Burned { who: sender, amount } + ) => {}, + RuntimeEvent::XcmPallet( + $crate::macros::pallet_xcm::Event::Sent { .. } + ) => {}, + ] + ); + }); + + // Receive XCM message in Destination Parachain + <$receiver_para>::execute_with(|| { + type RuntimeEvent = <$receiver_para as $crate::macros::Chain>::RuntimeEvent; + + assert_expected_events!( + $receiver_para, + vec![ + RuntimeEvent::Balances( + $crate::macros::pallet_balances::Event::Minted { who: receiver, .. } + ) => {}, + RuntimeEvent::MessageQueue( + $crate::macros::pallet_message_queue::Event::Processed { success: true, .. } + ) => {}, + ] + ); + }); + + // Check if balances are updated accordingly in Origin and Parachain + let relay_sender_balance_after = + <$sender_relay as $crate::macros::Chain>::account_data_of(sender.clone()).free; + let para_receiver_balance_after = + <$receiver_para as $crate::macros::Chain>::account_data_of(receiver.clone()).free; + let delivery_fees = <$sender_relay>::execute_with(|| { + $crate::macros::asset_test_utils::xcm_helpers::teleport_assets_delivery_fees::< + <$sender_xcm_config as xcm_executor::Config>::XcmSender, + >($assets.clone(), fee_asset_item, weight_limit.clone(), beneficiary, para_destination) + }); + + assert_eq!(relay_sender_balance_before - $amount - delivery_fees, relay_sender_balance_after); + assert!(para_receiver_balance_after > para_receiver_balance_before); + + // Update sender balance + relay_sender_balance_before = <$sender_relay as $crate::macros::Chain>::account_data_of(sender.clone()).free; + } + )+ + } + }; +} + +#[macro_export] +macro_rules! test_parachain_is_trusted_teleporter_for_relay { + ( $sender_para:ty, $sender_xcm_config:ty, $receiver_relay:ty, $amount:expr ) => { + $crate::macros::paste::paste! { + // init Origin variables + let sender = [<$sender_para Sender>]::get(); + let mut para_sender_balance_before = + <$sender_para as $crate::macros::Chain>::account_data_of(sender.clone()).free; + let origin = <$sender_para as $crate::macros::Chain>::RuntimeOrigin::signed(sender.clone()); + let assets: Assets = (Parent, $amount).into(); + let fee_asset_item = 0; + let weight_limit = $crate::macros::WeightLimit::Unlimited; + + // init Destination variables + let receiver = [<$receiver_relay Receiver>]::get(); + let relay_receiver_balance_before = + <$receiver_relay as $crate::macros::Chain>::account_data_of(receiver.clone()).free; + let relay_destination: Location = Parent.into(); + let beneficiary: Location = + $crate::macros::AccountId32 { network: None, id: receiver.clone().into() }.into(); + + // Send XCM message from Parachain + <$sender_para>::execute_with(|| { + assert_ok!(<$sender_para as [<$sender_para Pallet>]>::PolkadotXcm::limited_teleport_assets( + origin.clone(), + bx!(relay_destination.clone().into()), + bx!(beneficiary.clone().into()), + bx!(assets.clone().into()), + fee_asset_item, + weight_limit.clone(), + )); + + type RuntimeEvent = <$sender_para as $crate::macros::Chain>::RuntimeEvent; + + assert_expected_events!( + $sender_para, + vec![ + RuntimeEvent::PolkadotXcm( + $crate::macros::pallet_xcm::Event::Attempted { outcome: Outcome::Complete { .. } } + ) => {}, + RuntimeEvent::Balances( + $crate::macros::pallet_balances::Event::Burned { who: sender, amount } + ) => {}, + RuntimeEvent::PolkadotXcm( + $crate::macros::pallet_xcm::Event::Sent { .. } + ) => {}, + ] + ); + }); + + // Receive XCM message in Destination Parachain + <$receiver_relay>::execute_with(|| { + type RuntimeEvent = <$receiver_relay as $crate::macros::Chain>::RuntimeEvent; + + assert_expected_events!( + $receiver_relay, + vec![ + RuntimeEvent::Balances( + $crate::macros::pallet_balances::Event::Minted { who: receiver, .. } + ) => {}, + RuntimeEvent::MessageQueue( + $crate::macros::pallet_message_queue::Event::Processed { success: true, .. } + ) => {}, + ] + ); + }); + + // Check if balances are updated accordingly in Origin and Relay Chain + let para_sender_balance_after = + <$sender_para as $crate::macros::Chain>::account_data_of(sender.clone()).free; + let relay_receiver_balance_after = + <$receiver_relay as $crate::macros::Chain>::account_data_of(receiver.clone()).free; + let delivery_fees = <$sender_para>::execute_with(|| { + $crate::macros::asset_test_utils::xcm_helpers::teleport_assets_delivery_fees::< + <$sender_xcm_config as xcm_executor::Config>::XcmSender, + >(assets, fee_asset_item, weight_limit.clone(), beneficiary, relay_destination) + }); + + assert_eq!(para_sender_balance_before - $amount - delivery_fees, para_sender_balance_after); + assert!(relay_receiver_balance_after > relay_receiver_balance_before); + + // Update sender balance + para_sender_balance_before = <$sender_para as $crate::macros::Chain>::account_data_of(sender.clone()).free; + } + }; +} + +#[macro_export] +macro_rules! test_chain_can_claim_assets { + ( $sender_para:ty, $runtime_call:ty, $network_id:expr, $assets:expr, $amount:expr ) => { + $crate::macros::paste::paste! { + let sender = [<$sender_para Sender>]::get(); + let origin = <$sender_para as $crate::macros::Chain>::RuntimeOrigin::signed(sender.clone()); + // Receiver is the same as sender + let beneficiary: Location = + $crate::macros::AccountId32 { network: Some($network_id), id: sender.clone().into() }.into(); + let versioned_assets: $crate::macros::VersionedAssets = $assets.clone().into(); + + <$sender_para>::execute_with(|| { + // Assets are trapped for whatever reason. + // The possible reasons for this might differ from runtime to runtime, so here we just drop them directly. + <$sender_para as [<$sender_para Pallet>]>::PolkadotXcm::drop_assets( + &beneficiary, + $assets.clone().into(), + &XcmContext { origin: None, message_id: [0u8; 32], topic: None }, + ); + + type RuntimeEvent = <$sender_para as $crate::macros::Chain>::RuntimeEvent; + assert_expected_events!( + $sender_para, + vec![ + RuntimeEvent::PolkadotXcm( + $crate::macros::pallet_xcm::Event::AssetsTrapped { origin: beneficiary, assets: versioned_assets, .. } + ) => {}, + ] + ); + + let balance_before = <$sender_para as [<$sender_para Pallet>]>::Balances::free_balance(&sender); + + // Different origin or different assets won't work. + let other_origin = <$sender_para as $crate::macros::Chain>::RuntimeOrigin::signed([<$sender_para Receiver>]::get()); + assert!(<$sender_para as [<$sender_para Pallet>]>::PolkadotXcm::claim_assets( + other_origin, + bx!(versioned_assets.clone().into()), + bx!(beneficiary.clone().into()), + ).is_err()); + let other_versioned_assets: $crate::macros::VersionedAssets = Assets::new().into(); + assert!(<$sender_para as [<$sender_para Pallet>]>::PolkadotXcm::claim_assets( + origin.clone(), + bx!(other_versioned_assets.into()), + bx!(beneficiary.clone().into()), + ).is_err()); + + // Assets will be claimed to `beneficiary`, which is the same as `sender`. + assert_ok!(<$sender_para as [<$sender_para Pallet>]>::PolkadotXcm::claim_assets( + origin.clone(), + bx!(versioned_assets.clone().into()), + bx!(beneficiary.clone().into()), + )); + + assert_expected_events!( + $sender_para, + vec![ + RuntimeEvent::PolkadotXcm( + $crate::macros::pallet_xcm::Event::AssetsClaimed { origin: beneficiary, assets: versioned_assets, .. } + ) => {}, + ] + ); + + // After claiming the assets, the balance has increased. + let balance_after = <$sender_para as [<$sender_para Pallet>]>::Balances::free_balance(&sender); + assert_eq!(balance_after, balance_before + $amount); + + // Claiming the assets again doesn't work. + assert!(<$sender_para as [<$sender_para Pallet>]>::PolkadotXcm::claim_assets( + origin.clone(), + bx!(versioned_assets.clone().into()), + bx!(beneficiary.clone().into()), + ).is_err()); + + let balance = <$sender_para as [<$sender_para Pallet>]>::Balances::free_balance(&sender); + assert_eq!(balance, balance_after); + + // You can also claim assets and send them to a different account. + <$sender_para as [<$sender_para Pallet>]>::PolkadotXcm::drop_assets( + &beneficiary, + $assets.clone().into(), + &XcmContext { origin: None, message_id: [0u8; 32], topic: None }, + ); + let receiver = [<$sender_para Receiver>]::get(); + let other_beneficiary: Location = + $crate::macros::AccountId32 { network: Some($network_id), id: receiver.clone().into() }.into(); + let balance_before = <$sender_para as [<$sender_para Pallet>]>::Balances::free_balance(&receiver); + assert_ok!(<$sender_para as [<$sender_para Pallet>]>::PolkadotXcm::claim_assets( + origin.clone(), + bx!(versioned_assets.clone().into()), + bx!(other_beneficiary.clone().into()), + )); + let balance_after = <$sender_para as [<$sender_para Pallet>]>::Balances::free_balance(&receiver); + assert_eq!(balance_after, balance_before + $amount); + }); + } + }; +} diff --git a/cumulus/parachains/integration-tests/emulated/networks/rococo-system/Cargo.toml b/cumulus/parachains/integration-tests/emulated/networks/rococo-system/Cargo.toml index 298be7362ec3a4e63bb4139b1050d1b0223c9382..864f3c6edd7e3f91566666c65c509d2494009d4d 100644 --- a/cumulus/parachains/integration-tests/emulated/networks/rococo-system/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/networks/rococo-system/Cargo.toml @@ -18,3 +18,4 @@ asset-hub-rococo-emulated-chain = { workspace = true } bridge-hub-rococo-emulated-chain = { workspace = true } people-rococo-emulated-chain = { workspace = true } penpal-emulated-chain = { workspace = true } +coretime-rococo-emulated-chain = { workspace = true } diff --git a/cumulus/parachains/integration-tests/emulated/networks/rococo-system/src/lib.rs b/cumulus/parachains/integration-tests/emulated/networks/rococo-system/src/lib.rs index 70f23ef8260ca408e55079e5797b09cc817872cd..53808bc5a8010128c6e490361127eadda56fecbb 100644 --- a/cumulus/parachains/integration-tests/emulated/networks/rococo-system/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/networks/rococo-system/src/lib.rs @@ -15,12 +15,14 @@ pub use asset_hub_rococo_emulated_chain; pub use bridge_hub_rococo_emulated_chain; +pub use coretime_rococo_emulated_chain; pub use penpal_emulated_chain; pub use people_rococo_emulated_chain; pub use rococo_emulated_chain; use asset_hub_rococo_emulated_chain::AssetHubRococo; use bridge_hub_rococo_emulated_chain::BridgeHubRococo; +use coretime_rococo_emulated_chain::CoretimeRococo; use penpal_emulated_chain::{PenpalA, PenpalB}; use people_rococo_emulated_chain::PeopleRococo; use rococo_emulated_chain::Rococo; @@ -37,6 +39,7 @@ decl_test_networks! { parachains = vec![ AssetHubRococo, BridgeHubRococo, + CoretimeRococo, PenpalA, PenpalB, PeopleRococo, @@ -49,6 +52,7 @@ decl_test_sender_receiver_accounts_parameter_types! { RococoRelay { sender: ALICE, receiver: BOB }, AssetHubRococoPara { sender: ALICE, receiver: BOB }, BridgeHubRococoPara { sender: ALICE, receiver: BOB }, + CoretimeRococoPara { sender: ALICE, receiver: BOB }, PenpalAPara { sender: ALICE, receiver: BOB }, PenpalBPara { sender: ALICE, receiver: BOB }, PeopleRococoPara { sender: ALICE, receiver: BOB } diff --git a/cumulus/parachains/integration-tests/emulated/networks/westend-system/Cargo.toml b/cumulus/parachains/integration-tests/emulated/networks/westend-system/Cargo.toml index 37c14aa30352922b6f9f44ab89c6501484c3212d..cec2e3733b2a0fbe83608f75981e5c288c70ea7f 100644 --- a/cumulus/parachains/integration-tests/emulated/networks/westend-system/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/networks/westend-system/Cargo.toml @@ -19,3 +19,4 @@ bridge-hub-westend-emulated-chain = { workspace = true } collectives-westend-emulated-chain = { workspace = true } penpal-emulated-chain = { workspace = true } people-westend-emulated-chain = { workspace = true } +coretime-westend-emulated-chain = { workspace = true } diff --git a/cumulus/parachains/integration-tests/emulated/networks/westend-system/src/lib.rs b/cumulus/parachains/integration-tests/emulated/networks/westend-system/src/lib.rs index 9fbc773bc50e136af3272e851f826d7cf63bc0b6..6949a985629d9cce5b774d3dce5a93e76d6e46c9 100644 --- a/cumulus/parachains/integration-tests/emulated/networks/westend-system/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/networks/westend-system/src/lib.rs @@ -16,6 +16,7 @@ pub use asset_hub_westend_emulated_chain; pub use bridge_hub_westend_emulated_chain; pub use collectives_westend_emulated_chain; +pub use coretime_westend_emulated_chain; pub use penpal_emulated_chain; pub use people_westend_emulated_chain; pub use westend_emulated_chain; @@ -23,6 +24,7 @@ pub use westend_emulated_chain; use asset_hub_westend_emulated_chain::AssetHubWestend; use bridge_hub_westend_emulated_chain::BridgeHubWestend; use collectives_westend_emulated_chain::CollectivesWestend; +use coretime_westend_emulated_chain::CoretimeWestend; use penpal_emulated_chain::{PenpalA, PenpalB}; use people_westend_emulated_chain::PeopleWestend; use westend_emulated_chain::Westend; @@ -40,6 +42,7 @@ decl_test_networks! { AssetHubWestend, BridgeHubWestend, CollectivesWestend, + CoretimeWestend, PeopleWestend, PenpalA, PenpalB, @@ -53,6 +56,7 @@ decl_test_sender_receiver_accounts_parameter_types! { AssetHubWestendPara { sender: ALICE, receiver: BOB }, BridgeHubWestendPara { sender: ALICE, receiver: BOB }, CollectivesWestendPara { sender: ALICE, receiver: BOB }, + CoretimeWestendPara { sender: ALICE, receiver: BOB }, PeopleWestendPara { sender: ALICE, receiver: BOB }, PenpalAPara { sender: ALICE, receiver: BOB }, PenpalBPara { sender: ALICE, receiver: BOB } diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/lib.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/lib.rs index f00945926963cb562c627eba90171f7ad58c70a5..eca35831705493c1ab7961b62f75ed26cde38c6c 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/lib.rs @@ -52,6 +52,7 @@ mod imports { XcmConfig as AssetHubRococoXcmConfig, }, AssetConversionOrigin as AssetHubRococoAssetConversionOrigin, + ExistentialDeposit as AssetHubRococoExistentialDeposit, }, genesis::{AssetHubRococoAssetOwner, ED as ASSET_HUB_ROCOCO_ED}, AssetHubRococoParaPallet as AssetHubRococoPallet, diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/claim_assets.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/claim_assets.rs new file mode 100644 index 0000000000000000000000000000000000000000..99b31aba4be010f48f0551cc1115b97caa63f409 --- /dev/null +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/claim_assets.rs @@ -0,0 +1,29 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Tests related to claiming assets trapped during XCM execution. + +use crate::imports::*; + +use emulated_integration_tests_common::test_chain_can_claim_assets; +use xcm_executor::traits::DropAssets; + +#[test] +fn assets_can_be_claimed() { + let amount = AssetHubRococoExistentialDeposit::get(); + let assets: Assets = (Parent, amount).into(); + + test_chain_can_claim_assets!(AssetHubRococo, RuntimeCall, NetworkId::Rococo, assets, amount); +} diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/mod.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/mod.rs index 138ce419757b98b03d4e9a6b26259d81ca779d69..8fffec23d73a58efc51a433ae2eb66c4028aca95 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/mod.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/src/tests/mod.rs @@ -13,6 +13,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +mod claim_assets; mod hybrid_transfers; mod reserve_transfer; mod send; diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/lib.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/lib.rs index db8ada3f4ea281a61e9daaf3fa2cc2ba19747090..9401621c5ba371b516cbda874d9a729f6f7d1808 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/lib.rs @@ -52,6 +52,7 @@ mod imports { XcmConfig as AssetHubWestendXcmConfig, }, AssetConversionOrigin as AssetHubWestendAssetConversionOrigin, + ExistentialDeposit as AssetHubWestendExistentialDeposit, }, genesis::{AssetHubWestendAssetOwner, ED as ASSET_HUB_WESTEND_ED}, AssetHubWestendParaPallet as AssetHubWestendPallet, diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/claim_assets.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/claim_assets.rs new file mode 100644 index 0000000000000000000000000000000000000000..de58839634f1b438c50d369bb025fc8750bda396 --- /dev/null +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/claim_assets.rs @@ -0,0 +1,29 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Tests related to claiming assets trapped during XCM execution. + +use crate::imports::*; + +use emulated_integration_tests_common::test_chain_can_claim_assets; +use xcm_executor::traits::DropAssets; + +#[test] +fn assets_can_be_claimed() { + let amount = AssetHubWestendExistentialDeposit::get(); + let assets: Assets = (Parent, amount).into(); + + test_chain_can_claim_assets!(AssetHubWestend, RuntimeCall, NetworkId::Westend, assets, amount); +} diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/mod.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/mod.rs index 61eb70524fc9ae2a23e5061400c57ca719bae4e1..73b73b239a1bb54e818cad575084ae775c6f9db1 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/mod.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/mod.rs @@ -13,6 +13,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +mod claim_assets; mod fellowship_treasury; mod hybrid_transfers; mod reserve_transfer; diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/lib.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/lib.rs index 04466a611c71318280d135324ba3de418f9348d9..3ee509389c67ccb5105f249667815aa587b1d29d 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/lib.rs @@ -48,7 +48,7 @@ mod imports { genesis::ED as ASSET_HUB_WESTEND_ED, AssetHubWestendParaPallet as AssetHubWestendPallet, }, bridge_hub_rococo_emulated_chain::{ - genesis::ED as BRIDGE_HUB_ROCOCO_ED, + genesis::ED as BRIDGE_HUB_ROCOCO_ED, BridgeHubRococoExistentialDeposit, BridgeHubRococoParaPallet as BridgeHubRococoPallet, BridgeHubRococoRuntimeOrigin, BridgeHubRococoXcmConfig, EthereumBeaconClient, EthereumInboundQueue, }, diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/claim_assets.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/claim_assets.rs new file mode 100644 index 0000000000000000000000000000000000000000..e61dc35bdf8a3cecbaa1cb42582582b1b7c1183f --- /dev/null +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/claim_assets.rs @@ -0,0 +1,29 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Tests related to claiming assets trapped during XCM execution. + +use crate::imports::*; + +use emulated_integration_tests_common::test_chain_can_claim_assets; +use xcm_executor::traits::DropAssets; + +#[test] +fn assets_can_be_claimed() { + let amount = BridgeHubRococoExistentialDeposit::get(); + let assets: Assets = (Parent, amount).into(); + + test_chain_can_claim_assets!(AssetHubRococo, RuntimeCall, NetworkId::Rococo, assets, amount); +} diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/mod.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/mod.rs index 58c52e1328c81f60c9a60d3fd9677a1bf8f66e95..ceccf98a0240dade42b8a00372e1ee8737cf1e03 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/mod.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/src/tests/mod.rs @@ -16,6 +16,7 @@ use crate::imports::*; mod asset_transfers; +mod claim_assets; mod send_xcm; mod snowbridge; mod teleport; diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/lib.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/lib.rs index 3b0fcea57a26f3e06080c28e9d6495f1b71e3680..782b83bac4754ba6888b8d513a13887d5cb7ecf3 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/lib.rs @@ -48,7 +48,7 @@ mod imports { genesis::ED as ASSET_HUB_WESTEND_ED, AssetHubWestendParaPallet as AssetHubWestendPallet, }, bridge_hub_westend_emulated_chain::{ - genesis::ED as BRIDGE_HUB_WESTEND_ED, + genesis::ED as BRIDGE_HUB_WESTEND_ED, BridgeHubWestendExistentialDeposit, BridgeHubWestendParaPallet as BridgeHubWestendPallet, BridgeHubWestendXcmConfig, }, penpal_emulated_chain::{ diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/claim_assets.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/claim_assets.rs new file mode 100644 index 0000000000000000000000000000000000000000..e62ce6843258e641ddd1e86dc0c5b006db31e4df --- /dev/null +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/claim_assets.rs @@ -0,0 +1,29 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Tests related to claiming assets trapped during XCM execution. + +use crate::imports::*; + +use emulated_integration_tests_common::test_chain_can_claim_assets; +use xcm_executor::traits::DropAssets; + +#[test] +fn assets_can_be_claimed() { + let amount = BridgeHubWestendExistentialDeposit::get(); + let assets: Assets = (Parent, amount).into(); + + test_chain_can_claim_assets!(AssetHubWestend, RuntimeCall, NetworkId::Westend, assets, amount); +} diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/mod.rs b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/mod.rs index 92e864229a9cd605fbe0f8ca843deef6d74d30c2..768b647a13fc19fae244a6ede2f8d527726e9963 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/mod.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/src/tests/mod.rs @@ -16,6 +16,7 @@ use crate::imports::*; mod asset_transfers; +mod claim_assets; mod send_xcm; mod teleport; diff --git a/cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend/src/lib.rs b/cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend/src/lib.rs index 8af93a62f4a17e7f134b9d2f3d53ef7e267370de..e2048b62c311254ab474172ee49494aa87166c85 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend/src/lib.rs @@ -15,24 +15,42 @@ pub use xcm::{prelude::*, v3}; -pub use emulated_integration_tests_common::xcm_emulator::{ - assert_expected_events, bx, Chain, RelayChain as Relay, TestExt, +pub use emulated_integration_tests_common::{ + accounts::ALICE, + test_parachain_is_trusted_teleporter, + xcm_emulator::{assert_expected_events, bx, Chain, Parachain, RelayChain as Relay, TestExt}, }; pub use westend_system_emulated_network::{ asset_hub_westend_emulated_chain::{ - asset_hub_westend_runtime::xcm_config::LocationToAccountId as AssetHubLocationToAccountId, + asset_hub_westend_runtime::xcm_config::{ + LocationToAccountId as AssetHubLocationToAccountId, + XcmConfig as AssetHubWestendXcmConfig, + }, + genesis::ED as ASSET_HUB_WESTEND_ED, AssetHubWestendParaPallet as AssetHubWestendPallet, }, collectives_westend_emulated_chain::{ - collectives_westend_runtime::fellowship as collectives_fellowship, + collectives_westend_runtime::{ + fellowship as collectives_fellowship, + xcm_config::XcmConfig as CollectivesWestendXcmConfig, + }, + genesis::ED as COLLECTIVES_WESTEND_ED, CollectivesWestendParaPallet as CollectivesWestendPallet, }, westend_emulated_chain::{ - westend_runtime::{governance as westend_governance, OriginCaller as WestendOriginCaller}, + genesis::ED as WESTEND_ED, + westend_runtime::{ + governance as westend_governance, xcm_config::XcmConfig as WestendXcmConfig, + OriginCaller as WestendOriginCaller, + }, WestendRelayPallet as WestendPallet, }, - AssetHubWestendPara as AssetHubWestend, CollectivesWestendPara as CollectivesWestend, - WestendRelay as Westend, + AssetHubWestendPara as AssetHubWestend, AssetHubWestendParaReceiver as AssetHubWestendReceiver, + AssetHubWestendParaSender as AssetHubWestendSender, + CollectivesWestendPara as CollectivesWestend, + CollectivesWestendParaReceiver as CollectivesWestendReceiver, + CollectivesWestendParaSender as CollectivesWestendSender, WestendRelay as Westend, + WestendRelayReceiver as WestendReceiver, WestendRelaySender as WestendSender, }; #[cfg(test)] diff --git a/cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend/src/tests/fellowship_treasury.rs b/cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend/src/tests/fellowship_treasury.rs index abd9a982c8ed5e5407776d3bb6d84686009f59f4..943f8965540d5cb0c17c7a0b1aac8797cbd3ed42 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend/src/tests/fellowship_treasury.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend/src/tests/fellowship_treasury.rs @@ -14,7 +14,6 @@ // limitations under the License. use crate::*; -use emulated_integration_tests_common::accounts::ALICE; use frame_support::{ assert_ok, dispatch::RawOrigin, instances::Instance1, sp_runtime::traits::Dispatchable, traits::fungible::Inspect, diff --git a/cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend/src/tests/mod.rs b/cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend/src/tests/mod.rs index a9f65df34b647835b4ce5585be6b53b0489de578..40e98a8b68694b48d9554e98555770a97c3e6b46 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend/src/tests/mod.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend/src/tests/mod.rs @@ -14,3 +14,4 @@ // limitations under the License. mod fellowship_treasury; +mod teleport; diff --git a/cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend/src/tests/teleport.rs b/cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend/src/tests/teleport.rs new file mode 100644 index 0000000000000000000000000000000000000000..32f543406d759da1a5f0d06de851930f8ae2b00f --- /dev/null +++ b/cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend/src/tests/teleport.rs @@ -0,0 +1,66 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::*; +use emulated_integration_tests_common::{ + test_parachain_is_trusted_teleporter_for_relay, test_relay_is_trusted_teleporter, +}; +use frame_support::assert_ok; + +#[test] +fn teleport_from_and_to_relay() { + let amount = WESTEND_ED * 10; + let native_asset: Assets = (Here, amount).into(); + + test_relay_is_trusted_teleporter!( + Westend, // Origin + WestendXcmConfig, // XCM Configuration + vec![CollectivesWestend], // Destinations + (native_asset, amount) + ); + + test_parachain_is_trusted_teleporter_for_relay!( + CollectivesWestend, // Origin + CollectivesWestendXcmConfig, // XCM Configuration + Westend, // Destination + amount + ); +} + +#[test] +fn teleport_from_collectives_to_asset_hub() { + let amount = ASSET_HUB_WESTEND_ED * 100; + let native_asset: Assets = (Parent, amount).into(); + + test_parachain_is_trusted_teleporter!( + CollectivesWestend, // Origin + CollectivesWestendXcmConfig, // XCM Configuration + vec![AssetHubWestend], // Destinations + (native_asset, amount) + ); +} + +#[test] +fn teleport_from_asset_hub_to_collectives() { + let amount = COLLECTIVES_WESTEND_ED * 100; + let native_asset: Assets = (Parent, amount).into(); + + test_parachain_is_trusted_teleporter!( + AssetHubWestend, // Origin + AssetHubWestendXcmConfig, // XCM Configuration + vec![CollectivesWestend], // Destinations + (native_asset, amount) + ); +} diff --git a/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-rococo/Cargo.toml b/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-rococo/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..259be790c3e5f789b8ee180fef068e596b2c1fdd --- /dev/null +++ b/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-rococo/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "coretime-rococo-integration-tests" +version = "0.1.0" +authors.workspace = true +edition.workspace = true +license = "Apache-2.0" +description = "Coretime Rococo runtime integration tests with xcm-emulator" +publish = false + +[dependencies] + +# Substrate +frame-support = { workspace = true } +pallet-balances = { workspace = true } +pallet-message-queue = { workspace = true } +pallet-identity = { workspace = true } +sp-runtime = { workspace = true } + +# Polkadot +polkadot-runtime-common = { workspace = true, default-features = true } +rococo-runtime-constants = { workspace = true, default-features = true } +xcm = { workspace = true } +xcm-executor = { workspace = true } + +# Cumulus +emulated-integration-tests-common = { workspace = true } +rococo-system-emulated-network = { workspace = true } diff --git a/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-rococo/src/lib.rs b/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-rococo/src/lib.rs new file mode 100644 index 0000000000000000000000000000000000000000..ad3c4fd58da991af243db4b611fd1e6279429f5d --- /dev/null +++ b/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-rococo/src/lib.rs @@ -0,0 +1,40 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#[cfg(test)] +mod imports { + + // Substrate + pub use frame_support::assert_ok; + + // Polkadot + pub use xcm::prelude::*; + + // Cumulus + pub use emulated_integration_tests_common::xcm_emulator::{ + assert_expected_events, bx, TestExt, + }; + pub use rococo_system_emulated_network::{ + coretime_rococo_emulated_chain::{ + coretime_rococo_runtime::ExistentialDeposit as CoretimeRococoExistentialDeposit, + CoretimeRococoParaPallet as CoretimeRococoPallet, + }, + CoretimeRococoPara as CoretimeRococo, CoretimeRococoParaReceiver as CoretimeRococoReceiver, + CoretimeRococoParaSender as CoretimeRococoSender, + }; +} + +#[cfg(test)] +mod tests; diff --git a/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-rococo/src/tests/claim_assets.rs b/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-rococo/src/tests/claim_assets.rs new file mode 100644 index 0000000000000000000000000000000000000000..e37b915174d36d33d86ce0ff2c7fbef2b3c91024 --- /dev/null +++ b/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-rococo/src/tests/claim_assets.rs @@ -0,0 +1,29 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Tests related to claiming assets trapped during XCM execution. + +use crate::imports::*; + +use emulated_integration_tests_common::test_chain_can_claim_assets; +use xcm_executor::traits::DropAssets; + +#[test] +fn assets_can_be_claimed() { + let amount = CoretimeRococoExistentialDeposit::get(); + let assets: Assets = (Parent, amount).into(); + + test_chain_can_claim_assets!(CoretimeRococo, RuntimeCall, NetworkId::Rococo, assets, amount); +} diff --git a/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-rococo/src/tests/mod.rs b/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-rococo/src/tests/mod.rs new file mode 100644 index 0000000000000000000000000000000000000000..0e78351bce03110a3722cf699c7c70fa9b9a5341 --- /dev/null +++ b/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-rococo/src/tests/mod.rs @@ -0,0 +1,16 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +mod claim_assets; diff --git a/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-westend/Cargo.toml b/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-westend/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..a8fa905d2e5ee4f1905bcf420fa135f8612c7796 --- /dev/null +++ b/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-westend/Cargo.toml @@ -0,0 +1,27 @@ +[package] +name = "coretime-westend-integration-tests" +version = "0.1.0" +authors.workspace = true +edition.workspace = true +license = "Apache-2.0" +description = "Coretime Westend runtime integration tests with xcm-emulator" +publish = false + +[dependencies] + +# Substrate +frame-support = { workspace = true } +pallet-balances = { workspace = true } +pallet-message-queue = { workspace = true } +pallet-identity = { workspace = true } +sp-runtime = { workspace = true } + +# Polkadot +polkadot-runtime-common = { workspace = true, default-features = true } +westend-runtime-constants = { workspace = true, default-features = true } +xcm = { workspace = true } +xcm-executor = { workspace = true } + +# Cumulus +emulated-integration-tests-common = { workspace = true } +westend-system-emulated-network = { workspace = true } diff --git a/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-westend/src/lib.rs b/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-westend/src/lib.rs new file mode 100644 index 0000000000000000000000000000000000000000..838ca6eeafb67db1c78159f78877a35a207c2a41 --- /dev/null +++ b/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-westend/src/lib.rs @@ -0,0 +1,41 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#[cfg(test)] +mod imports { + + // Substrate + pub use frame_support::assert_ok; + + // Polkadot + pub use xcm::prelude::*; + + // Cumulus + pub use emulated_integration_tests_common::xcm_emulator::{ + assert_expected_events, bx, TestExt, + }; + pub use westend_system_emulated_network::{ + coretime_westend_emulated_chain::{ + coretime_westend_runtime::ExistentialDeposit as CoretimeWestendExistentialDeposit, + CoretimeWestendParaPallet as CoretimeWestendPallet, + }, + CoretimeWestendPara as CoretimeWestend, + CoretimeWestendParaReceiver as CoretimeWestendReceiver, + CoretimeWestendParaSender as CoretimeWestendSender, + }; +} + +#[cfg(test)] +mod tests; diff --git a/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-westend/src/tests/claim_assets.rs b/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-westend/src/tests/claim_assets.rs new file mode 100644 index 0000000000000000000000000000000000000000..c8d853698444c3dfc047ae1b860eee742efca004 --- /dev/null +++ b/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-westend/src/tests/claim_assets.rs @@ -0,0 +1,29 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Tests related to claiming assets trapped during XCM execution. + +use crate::imports::*; + +use emulated_integration_tests_common::test_chain_can_claim_assets; +use xcm_executor::traits::DropAssets; + +#[test] +fn assets_can_be_claimed() { + let amount = CoretimeWestendExistentialDeposit::get(); + let assets: Assets = (Parent, amount).into(); + + test_chain_can_claim_assets!(CoretimeWestend, RuntimeCall, NetworkId::Westend, assets, amount); +} diff --git a/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-westend/src/tests/mod.rs b/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-westend/src/tests/mod.rs new file mode 100644 index 0000000000000000000000000000000000000000..0e78351bce03110a3722cf699c7c70fa9b9a5341 --- /dev/null +++ b/cumulus/parachains/integration-tests/emulated/tests/coretime/coretime-westend/src/tests/mod.rs @@ -0,0 +1,16 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +mod claim_assets; diff --git a/cumulus/parachains/integration-tests/emulated/tests/people/people-rococo/src/lib.rs b/cumulus/parachains/integration-tests/emulated/tests/people/people-rococo/src/lib.rs index 6c23c2f1f292e9f8235b1f862e2ac934877609d8..43cd5bb85d3dd9a953698478bf5de2bd9ac17804 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/people/people-rococo/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/people/people-rococo/src/lib.rs @@ -38,7 +38,10 @@ mod imports { pub use rococo_system_emulated_network::{ people_rococo_emulated_chain::{ genesis::ED as PEOPLE_ROCOCO_ED, - people_rococo_runtime::{people, xcm_config::XcmConfig as PeopleRococoXcmConfig}, + people_rococo_runtime::{ + people, xcm_config::XcmConfig as PeopleRococoXcmConfig, + ExistentialDeposit as PeopleRococoExistentialDeposit, + }, PeopleRococoParaPallet as PeopleRococoPallet, }, rococo_emulated_chain::{ diff --git a/cumulus/parachains/integration-tests/emulated/tests/people/people-rococo/src/tests/claim_assets.rs b/cumulus/parachains/integration-tests/emulated/tests/people/people-rococo/src/tests/claim_assets.rs new file mode 100644 index 0000000000000000000000000000000000000000..793200e1d06b870327942229252d56bcb46405f9 --- /dev/null +++ b/cumulus/parachains/integration-tests/emulated/tests/people/people-rococo/src/tests/claim_assets.rs @@ -0,0 +1,29 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Tests related to claiming assets trapped during XCM execution. + +use crate::imports::*; + +use emulated_integration_tests_common::test_chain_can_claim_assets; +use xcm_executor::traits::DropAssets; + +#[test] +fn assets_can_be_claimed() { + let amount = PeopleRococoExistentialDeposit::get(); + let assets: Assets = (Parent, amount).into(); + + test_chain_can_claim_assets!(PeopleRococo, RuntimeCall, NetworkId::Rococo, assets, amount); +} diff --git a/cumulus/parachains/integration-tests/emulated/tests/people/people-rococo/src/tests/mod.rs b/cumulus/parachains/integration-tests/emulated/tests/people/people-rococo/src/tests/mod.rs index 80c00021ca53db3850d6d32c1584ae7ae924933f..3f18621224acabcbb5a2df4de4344db6b2408999 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/people/people-rococo/src/tests/mod.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/people/people-rococo/src/tests/mod.rs @@ -13,5 +13,6 @@ // See the License for the specific language governing permissions and // limitations under the License. +mod claim_assets; mod reap_identity; mod teleport; diff --git a/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/src/lib.rs b/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/src/lib.rs index ce1ed9751a2e68ab1cb087983dbb01e21d34bcc8..92f5d291ac849b3c4404fc122abe24afc49a4828 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/src/lib.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/src/lib.rs @@ -38,7 +38,10 @@ mod imports { self, people_westend_emulated_chain::{ genesis::ED as PEOPLE_WESTEND_ED, - people_westend_runtime::{people, xcm_config::XcmConfig as PeopleWestendXcmConfig}, + people_westend_runtime::{ + people, xcm_config::XcmConfig as PeopleWestendXcmConfig, + ExistentialDeposit as PeopleWestendExistentialDeposit, + }, PeopleWestendParaPallet as PeopleWestendPallet, }, westend_emulated_chain::{ diff --git a/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/src/tests/claim_assets.rs b/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/src/tests/claim_assets.rs new file mode 100644 index 0000000000000000000000000000000000000000..42ccc459286a2dde06c0fc96dc125a527e649973 --- /dev/null +++ b/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/src/tests/claim_assets.rs @@ -0,0 +1,29 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Tests related to claiming assets trapped during XCM execution. + +use crate::imports::*; + +use emulated_integration_tests_common::test_chain_can_claim_assets; +use xcm_executor::traits::DropAssets; + +#[test] +fn assets_can_be_claimed() { + let amount = PeopleWestendExistentialDeposit::get(); + let assets: Assets = (Parent, amount).into(); + + test_chain_can_claim_assets!(PeopleWestend, RuntimeCall, NetworkId::Westend, assets, amount); +} diff --git a/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/src/tests/mod.rs b/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/src/tests/mod.rs index 80c00021ca53db3850d6d32c1584ae7ae924933f..3f18621224acabcbb5a2df4de4344db6b2408999 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/src/tests/mod.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/src/tests/mod.rs @@ -13,5 +13,6 @@ // See the License for the specific language governing permissions and // limitations under the License. +mod claim_assets; mod reap_identity; mod teleport; diff --git a/cumulus/parachains/pallets/collective-content/Cargo.toml b/cumulus/parachains/pallets/collective-content/Cargo.toml index 61cbe7850090195af08bccfd3f0b172dcbb85b60..c52021f67e36233eb46c2fe703c9c6cef963ab76 100644 --- a/cumulus/parachains/pallets/collective-content/Cargo.toml +++ b/cumulus/parachains/pallets/collective-content/Cargo.toml @@ -19,7 +19,6 @@ frame-system = { workspace = true } sp-core = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] sp-io = { workspace = true } @@ -48,5 +47,4 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] diff --git a/cumulus/parachains/pallets/collective-content/src/lib.rs b/cumulus/parachains/pallets/collective-content/src/lib.rs index b1c960ad6a0d337d6b84aaaba59f7fa0625a8124..7ea3c2d79fa793fd3726bf9ee0b59eaac598eb38 100644 --- a/cumulus/parachains/pallets/collective-content/src/lib.rs +++ b/cumulus/parachains/pallets/collective-content/src/lib.rs @@ -46,7 +46,6 @@ pub use weights::WeightInfo; use frame_support::{traits::schedule::DispatchTime, BoundedVec}; use sp_core::ConstU32; -use sp_std::prelude::*; /// IPFS compatible CID. // Worst case 2 bytes base and codec, 2 bytes hash type and size, 64 bytes hash digest. diff --git a/cumulus/parachains/pallets/collective-content/src/tests.rs b/cumulus/parachains/pallets/collective-content/src/tests.rs index 4910b30b89af84430a60e2eab011ed2c5c6a3d03..7fee5eea101dbc94e2180b104cdfb2d8a1d040cd 100644 --- a/cumulus/parachains/pallets/collective-content/src/tests.rs +++ b/cumulus/parachains/pallets/collective-content/src/tests.rs @@ -16,7 +16,8 @@ //! Tests. use super::{mock::*, *}; -use frame_support::{assert_noop, assert_ok, error::BadOrigin, pallet_prelude::Pays}; +use frame_support::{assert_noop, assert_ok, pallet_prelude::Pays}; +use sp_runtime::traits::BadOrigin; /// returns CID hash of 68 bytes of given `i`. fn create_cid(i: u8) -> OpaqueCid { diff --git a/cumulus/parachains/pallets/parachain-info/Cargo.toml b/cumulus/parachains/pallets/parachain-info/Cargo.toml index 7369c3a2c157624b7af48f860c73ba61716a1038..e0bed23c4f8c0931d1b5b13c36a696378f62fd83 100644 --- a/cumulus/parachains/pallets/parachain-info/Cargo.toml +++ b/cumulus/parachains/pallets/parachain-info/Cargo.toml @@ -17,7 +17,6 @@ frame-support = { workspace = true } frame-system = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } cumulus-primitives-core = { workspace = true } @@ -30,7 +29,6 @@ std = [ "frame-system/std", "scale-info/std", "sp-runtime/std", - "sp-std/std", ] try-runtime = [ "frame-support/try-runtime", diff --git a/cumulus/parachains/pallets/parachain-info/src/lib.rs b/cumulus/parachains/pallets/parachain-info/src/lib.rs index a4ef448a6b6b9b934e9e49a4a4797a590ad55d6b..0aaa7adaa51c0198fa1025337a31ff790df2113b 100644 --- a/cumulus/parachains/pallets/parachain-info/src/lib.rs +++ b/cumulus/parachains/pallets/parachain-info/src/lib.rs @@ -41,7 +41,7 @@ pub mod pallet { #[pallet::genesis_config] pub struct GenesisConfig { #[serde(skip)] - pub _config: sp_std::marker::PhantomData, + pub _config: core::marker::PhantomData, pub parachain_id: ParaId, } diff --git a/cumulus/parachains/pallets/ping/Cargo.toml b/cumulus/parachains/pallets/ping/Cargo.toml index f74328207b84387f969bcf94d81d6bef705f877a..51fc384a4f1408ba7ad9c05f9d172146290d4cd5 100644 --- a/cumulus/parachains/pallets/ping/Cargo.toml +++ b/cumulus/parachains/pallets/ping/Cargo.toml @@ -13,7 +13,6 @@ workspace = true codec = { features = ["derive"], workspace = true } scale-info = { features = ["derive"], workspace = true } -sp-std = { workspace = true } sp-runtime = { workspace = true } frame-support = { workspace = true } frame-system = { workspace = true } @@ -33,7 +32,6 @@ std = [ "frame-system/std", "scale-info/std", "sp-runtime/std", - "sp-std/std", "xcm/std", ] diff --git a/cumulus/parachains/pallets/ping/src/lib.rs b/cumulus/parachains/pallets/ping/src/lib.rs index a738c05e0366bc44da562f59f7e9a638a8251d9c..729494cbd251d6ff5ea3271a040c28bb786ea849 100644 --- a/cumulus/parachains/pallets/ping/src/lib.rs +++ b/cumulus/parachains/pallets/ping/src/lib.rs @@ -18,12 +18,14 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + +use alloc::{vec, vec::Vec}; use cumulus_pallet_xcm::{ensure_sibling_para, Origin as CumulusOrigin}; use cumulus_primitives_core::ParaId; use frame_support::{parameter_types, BoundedVec}; use frame_system::Config as SystemConfig; use sp_runtime::traits::Saturating; -use sp_std::prelude::*; use xcm::latest::prelude::*; pub use pallet::*; diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/Cargo.toml b/cumulus/parachains/runtimes/assets/asset-hub-rococo/Cargo.toml index 9ef0aa0072c96a3077c2a9d1c8b3793521938ff5..98df41090a4072f45177326b70f617bf967d735b 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/Cargo.toml +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/Cargo.toml @@ -53,7 +53,6 @@ sp-genesis-builder = { workspace = true } sp-offchain = { workspace = true } sp-runtime = { workspace = true } sp-session = { workspace = true } -sp-std = { workspace = true } sp-storage = { workspace = true } sp-transaction-pool = { workspace = true } sp-version = { workspace = true } @@ -241,7 +240,6 @@ std = [ "sp-offchain/std", "sp-runtime/std", "sp-session/std", - "sp-std/std", "sp-storage/std", "sp-transaction-pool/std", "sp-version/std", diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs index e8772c0b4830363723b96424d5507c461715354e..f09647854cd0132751889ef2b33bca1c5ec16e74 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs @@ -27,6 +27,9 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); mod weights; pub mod xcm_config; +extern crate alloc; + +use alloc::{vec, vec::Vec}; use assets_common::{ foreign_creators::ForeignCreators, local_and_foreign_assets::{LocalFromLeft, TargetFromLeft}, @@ -45,7 +48,6 @@ use sp_runtime::{ }; use testnet_parachains_constants::rococo::snowbridge::EthereumNetwork; -use sp_std::prelude::*; #[cfg(feature = "std")] use sp_version::NativeVersion; use sp_version::RuntimeVersion; @@ -1161,7 +1163,7 @@ impl_runtime_apis! { Runtime::metadata_at_version(version) } - fn metadata_versions() -> sp_std::vec::Vec { + fn metadata_versions() -> alloc::vec::Vec { Runtime::metadata_versions() } } @@ -1445,7 +1447,7 @@ impl_runtime_apis! { use frame_system_benchmarking::Pallet as SystemBench; impl frame_system_benchmarking::Config for Runtime { - fn setup_set_code_requirements(code: &sp_std::vec::Vec) -> Result<(), BenchmarkError> { + fn setup_set_code_requirements(code: &alloc::vec::Vec) -> Result<(), BenchmarkError> { ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32); Ok(()) } @@ -1515,7 +1517,7 @@ impl_runtime_apis! { } fn set_up_complex_asset_transfer( - ) -> Option<(XcmAssets, u32, Location, Box)> { + ) -> Option<(XcmAssets, u32, Location, alloc::boxed::Box)> { // Transfer to Relay some local AH asset (local-reserve-transfer) while paying // fees using teleported native token. // (We don't care that Relay doesn't accept incoming unknown AH local asset) @@ -1550,7 +1552,7 @@ impl_runtime_apis! { let fee_index = if assets.get(0).unwrap().eq(&fee_asset) { 0 } else { 1 }; // verify transferred successfully - let verify = Box::new(move || { + let verify = alloc::boxed::Box::new(move || { // verify native balance after transfer, decreased by transferred fee amount // (plus transport fees) assert!(Balances::free_balance(&who) <= balance - fee_amount); @@ -1584,7 +1586,7 @@ impl_runtime_apis! { let bridged_asset_hub = xcm_config::bridging::to_westend::AssetHubWestend::get(); let _ = PolkadotXcm::force_xcm_version( RuntimeOrigin::root(), - Box::new(bridged_asset_hub.clone()), + alloc::boxed::Box::new(bridged_asset_hub.clone()), XCM_VERSION, ).map_err(|e| { log::error!( diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/cumulus_pallet_parachain_system.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/cumulus_pallet_parachain_system.rs index c1e5c6a74293995b6e3702f19b8b3750c34b192f..fc63a0814d0a4af4ac9e264db8757e5abe2da36d 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/cumulus_pallet_parachain_system.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/cumulus_pallet_parachain_system.rs @@ -47,7 +47,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weight functions for `cumulus_pallet_parachain_system`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/pallet_message_queue.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/pallet_message_queue.rs index 45531ccfa797c52ead00833f765347f1282816c7..cd72703104ad0fee8744b904e950def1872d2456 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/pallet_message_queue.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/pallet_message_queue.rs @@ -43,7 +43,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weight functions for `pallet_message_queue`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/pallet_xcm_bridge_hub_router.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/pallet_xcm_bridge_hub_router.rs index 775bc3bdb80f54a8db97d1c1fdbf5a837fdb95b1..0a86037391b42d71340d8d0665a9210d8b9a0281 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/pallet_xcm_bridge_hub_router.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/pallet_xcm_bridge_hub_router.rs @@ -16,10 +16,10 @@ //! Autogenerated weights for `pallet_xcm_bridge_hub_router` //! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 +//! DATE: 2024-07-03, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-itmxxexx-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-7wrmsoux-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-rococo-dev")`, DB CACHE: 1024 // Executed Command: @@ -49,32 +49,32 @@ use core::marker::PhantomData; pub struct WeightInfo(PhantomData); impl pallet_xcm_bridge_hub_router::WeightInfo for WeightInfo { /// Storage: `XcmpQueue::InboundXcmpSuspended` (r:1 w:0) - /// Proof: `XcmpQueue::InboundXcmpSuspended` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Proof: `XcmpQueue::InboundXcmpSuspended` (`max_values`: Some(1), `max_size`: Some(4002), added: 4497, mode: `MaxEncodedLen`) /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:0) - /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: Some(1282), added: 1777, mode: `MaxEncodedLen`) /// Storage: `ToWestendXcmRouter::Bridge` (r:1 w:1) /// Proof: `ToWestendXcmRouter::Bridge` (`max_values`: Some(1), `max_size`: Some(17), added: 512, mode: `MaxEncodedLen`) fn on_initialize_when_non_congested() -> Weight { // Proof Size summary in bytes: // Measured: `154` - // Estimated: `1639` - // Minimum execution time: 7_853_000 picoseconds. - Weight::from_parts(8_443_000, 0) - .saturating_add(Weight::from_parts(0, 1639)) + // Estimated: `5487` + // Minimum execution time: 8_078_000 picoseconds. + Weight::from_parts(8_455_000, 0) + .saturating_add(Weight::from_parts(0, 5487)) .saturating_add(T::DbWeight::get().reads(3)) .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `XcmpQueue::InboundXcmpSuspended` (r:1 w:0) - /// Proof: `XcmpQueue::InboundXcmpSuspended` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Proof: `XcmpQueue::InboundXcmpSuspended` (`max_values`: Some(1), `max_size`: Some(4002), added: 4497, mode: `MaxEncodedLen`) /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:0) - /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: Some(1282), added: 1777, mode: `MaxEncodedLen`) fn on_initialize_when_congested() -> Weight { // Proof Size summary in bytes: // Measured: `144` - // Estimated: `1629` - // Minimum execution time: 4_333_000 picoseconds. - Weight::from_parts(4_501_000, 0) - .saturating_add(Weight::from_parts(0, 1629)) + // Estimated: `5487` + // Minimum execution time: 4_291_000 picoseconds. + Weight::from_parts(4_548_000, 0) + .saturating_add(Weight::from_parts(0, 5487)) .saturating_add(T::DbWeight::get().reads(2)) } /// Storage: `ToWestendXcmRouter::Bridge` (r:1 w:1) @@ -83,14 +83,12 @@ impl pallet_xcm_bridge_hub_router::WeightInfo for Weigh // Proof Size summary in bytes: // Measured: `150` // Estimated: `1502` - // Minimum execution time: 10_167_000 picoseconds. - Weight::from_parts(10_667_000, 0) + // Minimum execution time: 9_959_000 picoseconds. + Weight::from_parts(10_372_000, 0) .saturating_add(Weight::from_parts(0, 1502)) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } - /// Storage: `PolkadotXcm::SupportedVersion` (r:2 w:0) - /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: UNKNOWN KEY `0x3302afcb67e838a3f960251b417b9a4f` (r:1 w:0) @@ -100,7 +98,9 @@ impl pallet_xcm_bridge_hub_router::WeightInfo for Weigh /// Storage: `ToWestendXcmRouter::Bridge` (r:1 w:1) /// Proof: `ToWestendXcmRouter::Bridge` (`max_values`: Some(1), `max_size`: Some(17), added: 512, mode: `MaxEncodedLen`) /// Storage: `XcmpQueue::DeliveryFeeFactor` (r:1 w:0) - /// Proof: `XcmpQueue::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Proof: `XcmpQueue::DeliveryFeeFactor` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:2 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) @@ -108,17 +108,17 @@ impl pallet_xcm_bridge_hub_router::WeightInfo for Weigh /// Storage: `ParachainSystem::RelevantMessagingState` (r:1 w:0) /// Proof: `ParachainSystem::RelevantMessagingState` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:1) - /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: Some(1282), added: 1777, mode: `MaxEncodedLen`) /// Storage: `XcmpQueue::InboundXcmpSuspended` (r:1 w:0) - /// Proof: `XcmpQueue::InboundXcmpSuspended` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Proof: `XcmpQueue::InboundXcmpSuspended` (`max_values`: Some(1), `max_size`: Some(4002), added: 4497, mode: `MaxEncodedLen`) /// Storage: `XcmpQueue::OutboundXcmpMessages` (r:0 w:1) - /// Proof: `XcmpQueue::OutboundXcmpMessages` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Proof: `XcmpQueue::OutboundXcmpMessages` (`max_values`: None, `max_size`: Some(105506), added: 107981, mode: `MaxEncodedLen`) fn send_message() -> Weight { // Proof Size summary in bytes: // Measured: `448` // Estimated: `6388` - // Minimum execution time: 60_584_000 picoseconds. - Weight::from_parts(62_467_000, 0) + // Minimum execution time: 45_888_000 picoseconds. + Weight::from_parts(47_022_000, 0) .saturating_add(Weight::from_parts(0, 6388)) .saturating_add(T::DbWeight::get().reads(12)) .saturating_add(T::DbWeight::get().writes(4)) diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/mod.rs index 8e675ad0cf8e627a1f547a181db1737767e84d7c..8c52ecd9f1b1fa66bc027be7b1d376ff6882517a 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/mod.rs @@ -18,10 +18,10 @@ mod pallet_xcm_benchmarks_fungible; mod pallet_xcm_benchmarks_generic; use crate::{xcm_config::MaxAssetsIntoHolding, Runtime}; +use alloc::vec::Vec; use frame_support::weights::Weight; use pallet_xcm_benchmarks_fungible::WeightInfo as XcmFungibleWeight; use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; -use sp_std::prelude::*; use xcm::{latest::prelude::*, DoubleEncoded}; trait WeighAssets { diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs index 7fab35842509deceba14e89e5bbf6bebe2240528..03d3785dccbd7f213eee3d8aa51cde7eb5980b48 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs @@ -43,7 +43,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weights for `pallet_xcm_benchmarks::fungible`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index 4454494badcbfe9b4f429312e24b63786b83ef75..bee6bcdf21cf3fed11ef63d593b5b0dfb1f0f10b 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -43,7 +43,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weights for `pallet_xcm_benchmarks::generic`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs index 03de2c971b7ff133223db0385919a90d0393fea3..a11dca4f6d7ccf8095c1a1095e436e131c508370 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/xcm_config.rs @@ -55,11 +55,11 @@ use xcm_builder::{ EnsureXcmOrigin, FrameTransactionalProcessor, FungibleAdapter, FungiblesAdapter, GlobalConsensusParachainConvertsFor, HashedDescription, IsConcrete, LocalMint, NetworkExportTableItem, NoChecking, NonFungiblesAdapter, ParentAsSuperuser, ParentIsPreset, - RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, + RelayChainAsNative, SendXcmFeeToAccount, SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, SovereignPaidRemoteExporter, SovereignSignedViaLocation, StartsWith, StartsWithExplicitGlobalConsensus, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, - XcmFeeManagerFromComponents, XcmFeeToAccount, + XcmFeeManagerFromComponents, }; use xcm_executor::XcmExecutor; @@ -413,7 +413,7 @@ impl xcm_executor::Config for XcmConfig { type AssetExchanger = (); type FeeManager = XcmFeeManagerFromComponents< WaivedLocations, - XcmFeeToAccount, + SendXcmFeeToAccount, >; type MessageExporter = (); type UniversalAliases = @@ -511,8 +511,8 @@ impl pallet_assets::BenchmarkHelper for XcmBenchmarkHelper { /// All configuration related to bridging pub mod bridging { use super::*; + use alloc::collections::btree_set::BTreeSet; use assets_common::matching; - use sp_std::collections::btree_set::BTreeSet; // common/shared parameters parameter_types! { @@ -541,13 +541,13 @@ pub mod bridging { /// (`AssetId` has to be aligned with `BridgeTable`) pub XcmBridgeHubRouterFeeAssetId: AssetId = TokenLocation::get().into(); - pub BridgeTable: sp_std::vec::Vec = - sp_std::vec::Vec::new().into_iter() + pub BridgeTable: alloc::vec::Vec = + alloc::vec::Vec::new().into_iter() .chain(to_westend::BridgeTable::get()) .collect(); - pub EthereumBridgeTable: sp_std::vec::Vec = - sp_std::vec::Vec::new().into_iter() + pub EthereumBridgeTable: alloc::vec::Vec = + alloc::vec::Vec::new().into_iter() .chain(to_ethereum::BridgeTable::get()) .collect(); } @@ -578,10 +578,10 @@ pub mod bridging { /// Set up exporters configuration. /// `Option` represents static "base fee" which is used for total delivery fee calculation. - pub BridgeTable: sp_std::vec::Vec = sp_std::vec![ + pub BridgeTable: alloc::vec::Vec = alloc::vec![ NetworkExportTableItem::new( WestendNetwork::get(), - Some(sp_std::vec![ + Some(alloc::vec![ AssetHubWestend::get().interior.split_global().expect("invalid configuration for AssetHubWestend").1, ]), SiblingBridgeHub::get(), @@ -595,7 +595,7 @@ pub mod bridging { /// Universal aliases pub UniversalAliases: BTreeSet<(Location, Junction)> = BTreeSet::from_iter( - sp_std::vec![ + alloc::vec![ (SiblingBridgeHubWithBridgeHubWestendInstance::get(), GlobalConsensus(WestendNetwork::get())) ] ); @@ -643,10 +643,10 @@ pub mod bridging { /// Set up exporters configuration. /// `Option` represents static "base fee" which is used for total delivery fee calculation. - pub BridgeTable: sp_std::vec::Vec = sp_std::vec![ + pub BridgeTable: alloc::vec::Vec = alloc::vec![ NetworkExportTableItem::new( EthereumNetwork::get(), - Some(sp_std::vec![Junctions::Here]), + Some(alloc::vec![Junctions::Here]), SiblingBridgeHub::get(), Some(( XcmBridgeHubRouterFeeAssetId::get(), @@ -657,7 +657,7 @@ pub mod bridging { /// Universal aliases pub UniversalAliases: BTreeSet<(Location, Junction)> = BTreeSet::from_iter( - sp_std::vec![ + alloc::vec![ (SiblingBridgeHubWithEthereumInboundQueueInstance::get(), GlobalConsensus(EthereumNetwork::get())), ] ); diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/tests/tests.rs b/cumulus/parachains/runtimes/assets/asset-hub-rococo/tests/tests.rs index f670c5f424efeac0e00ddf472f1948e06d93bd68..ee1461b7f9c85664e25dca1d02b4f248812d4219 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/tests/tests.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/tests/tests.rs @@ -34,6 +34,7 @@ use asset_test_utils::{ ExtBuilder, SlotDurations, }; use codec::{Decode, Encode}; +use core::ops::Mul; use cumulus_primitives_utility::ChargeWeightInFungibles; use frame_support::{ assert_noop, assert_ok, @@ -48,7 +49,6 @@ use frame_support::{ use parachains_common::{AccountId, AssetIdForTrustBackedAssets, AuraId, Balance}; use sp_consensus_aura::SlotDuration; use sp_runtime::traits::MaybeEquivalence; -use sp_std::ops::Mul; use std::convert::Into; use testnet_parachains_constants::rococo::{consensus::*, currency::UNITS, fee::WeightToFee}; use xcm::latest::prelude::{Assets as XcmAssets, *}; @@ -1277,7 +1277,7 @@ mod asset_hub_rococo_tests { collator_session_keys(), bridging_to_asset_hub_westend, || { - sp_std::vec![ + vec![ UnpaidExecution { weight_limit: Unlimited, check_origin: None }, Transact { origin_kind: OriginKind::Xcm, @@ -1287,16 +1287,16 @@ mod asset_hub_rococo_tests { bp_asset_hub_rococo::XcmBridgeHubRouterCall::report_bridge_status { bridge_id: Default::default(), is_congested: true, - } + }, ) .encode() .into(), - } + }, ] .into() }, || { - sp_std::vec![ + vec![ UnpaidExecution { weight_limit: Unlimited, check_origin: None }, Transact { origin_kind: OriginKind::Xcm, @@ -1306,11 +1306,11 @@ mod asset_hub_rococo_tests { bp_asset_hub_rococo::XcmBridgeHubRouterCall::report_bridge_status { bridge_id: Default::default(), is_congested: false, - } + }, ) .encode() .into(), - } + }, ] .into() }, diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/Cargo.toml b/cumulus/parachains/runtimes/assets/asset-hub-westend/Cargo.toml index 7e618d950b19a86a46903d3b8351c1c1be542cb9..6b1bf769ace3511cc91cb1b557d4a7d5a754fd92 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/Cargo.toml +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/Cargo.toml @@ -53,7 +53,6 @@ sp-inherents = { workspace = true } sp-offchain = { workspace = true } sp-runtime = { workspace = true } sp-session = { workspace = true } -sp-std = { workspace = true } sp-storage = { workspace = true } sp-transaction-pool = { workspace = true } sp-version = { workspace = true } @@ -240,7 +239,6 @@ std = [ "sp-offchain/std", "sp-runtime/std", "sp-session/std", - "sp-std/std", "sp-storage/std", "sp-transaction-pool/std", "sp-version/std", diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs index 55c8a9f0b265daa8e9a4d3d70712d26bd8b9fc9c..178b886fc3e84b741eb6721fec1b4e493626795b 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs @@ -27,6 +27,9 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); mod weights; pub mod xcm_config; +extern crate alloc; + +use alloc::{vec, vec::Vec}; use assets_common::{ local_and_foreign_assets::{LocalFromLeft, TargetFromLeft}, AssetIdForTrustBackedAssetsConvert, @@ -68,7 +71,6 @@ use sp_runtime::{ transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, Perbill, Permill, RuntimeDebug, }; -use sp_std::prelude::*; #[cfg(feature = "std")] use sp_version::NativeVersion; use sp_version::RuntimeVersion; @@ -1206,7 +1208,7 @@ impl_runtime_apis! { Runtime::metadata_at_version(version) } - fn metadata_versions() -> sp_std::vec::Vec { + fn metadata_versions() -> alloc::vec::Vec { Runtime::metadata_versions() } } @@ -1536,7 +1538,7 @@ impl_runtime_apis! { use frame_system_benchmarking::Pallet as SystemBench; impl frame_system_benchmarking::Config for Runtime { - fn setup_set_code_requirements(code: &sp_std::vec::Vec) -> Result<(), BenchmarkError> { + fn setup_set_code_requirements(code: &alloc::vec::Vec) -> Result<(), BenchmarkError> { ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32); Ok(()) } @@ -1601,7 +1603,7 @@ impl_runtime_apis! { } fn set_up_complex_asset_transfer( - ) -> Option<(XcmAssets, u32, Location, Box)> { + ) -> Option<(XcmAssets, u32, Location, alloc::boxed::Box)> { // Transfer to Relay some local AH asset (local-reserve-transfer) while paying // fees using teleported native token. // (We don't care that Relay doesn't accept incoming unknown AH local asset) @@ -1636,7 +1638,7 @@ impl_runtime_apis! { let fee_index = if assets.get(0).unwrap().eq(&fee_asset) { 0 } else { 1 }; // verify transferred successfully - let verify = Box::new(move || { + let verify = alloc::boxed::Box::new(move || { // verify native balance after transfer, decreased by transferred fee amount // (plus transport fees) assert!(Balances::free_balance(&who) <= balance - fee_amount); @@ -1675,7 +1677,7 @@ impl_runtime_apis! { let bridged_asset_hub = xcm_config::bridging::to_rococo::AssetHubRococo::get(); let _ = PolkadotXcm::force_xcm_version( RuntimeOrigin::root(), - Box::new(bridged_asset_hub.clone()), + alloc::boxed::Box::new(bridged_asset_hub.clone()), XCM_VERSION, ).map_err(|e| { log::error!( diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/cumulus_pallet_parachain_system.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/cumulus_pallet_parachain_system.rs index c1e5c6a74293995b6e3702f19b8b3750c34b192f..fc63a0814d0a4af4ac9e264db8757e5abe2da36d 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/cumulus_pallet_parachain_system.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/cumulus_pallet_parachain_system.rs @@ -47,7 +47,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weight functions for `cumulus_pallet_parachain_system`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/pallet_message_queue.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/pallet_message_queue.rs index 45531ccfa797c52ead00833f765347f1282816c7..cd72703104ad0fee8744b904e950def1872d2456 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/pallet_message_queue.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/pallet_message_queue.rs @@ -43,7 +43,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weight functions for `pallet_message_queue`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/pallet_xcm_bridge_hub_router.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/pallet_xcm_bridge_hub_router.rs index 84d717b0283c764cac14cce63ca34f81c9f58e8c..21d15c75af553da60ecf0648186a26255bb72890 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/pallet_xcm_bridge_hub_router.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/pallet_xcm_bridge_hub_router.rs @@ -16,10 +16,10 @@ //! Autogenerated weights for `pallet_xcm_bridge_hub_router` //! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 +//! DATE: 2024-07-03, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-itmxxexx-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-7wrmsoux-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("asset-hub-westend-dev")`, DB CACHE: 1024 // Executed Command: @@ -49,48 +49,46 @@ use core::marker::PhantomData; pub struct WeightInfo(PhantomData); impl pallet_xcm_bridge_hub_router::WeightInfo for WeightInfo { /// Storage: `XcmpQueue::InboundXcmpSuspended` (r:1 w:0) - /// Proof: `XcmpQueue::InboundXcmpSuspended` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Proof: `XcmpQueue::InboundXcmpSuspended` (`max_values`: Some(1), `max_size`: Some(4002), added: 4497, mode: `MaxEncodedLen`) /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:0) - /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: Some(1282), added: 1777, mode: `MaxEncodedLen`) /// Storage: `ToRococoXcmRouter::Bridge` (r:1 w:1) /// Proof: `ToRococoXcmRouter::Bridge` (`max_values`: Some(1), `max_size`: Some(17), added: 512, mode: `MaxEncodedLen`) fn on_initialize_when_non_congested() -> Weight { // Proof Size summary in bytes: - // Measured: `193` - // Estimated: `1678` - // Minimum execution time: 8_095_000 picoseconds. - Weight::from_parts(8_393_000, 0) - .saturating_add(Weight::from_parts(0, 1678)) + // Measured: `226` + // Estimated: `5487` + // Minimum execution time: 8_363_000 picoseconds. + Weight::from_parts(8_620_000, 0) + .saturating_add(Weight::from_parts(0, 5487)) .saturating_add(T::DbWeight::get().reads(3)) .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `XcmpQueue::InboundXcmpSuspended` (r:1 w:0) - /// Proof: `XcmpQueue::InboundXcmpSuspended` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Proof: `XcmpQueue::InboundXcmpSuspended` (`max_values`: Some(1), `max_size`: Some(4002), added: 4497, mode: `MaxEncodedLen`) /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:0) - /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: Some(1282), added: 1777, mode: `MaxEncodedLen`) fn on_initialize_when_congested() -> Weight { // Proof Size summary in bytes: // Measured: `111` - // Estimated: `1596` - // Minimum execution time: 3_417_000 picoseconds. - Weight::from_parts(3_583_000, 0) - .saturating_add(Weight::from_parts(0, 1596)) + // Estimated: `5487` + // Minimum execution time: 3_436_000 picoseconds. + Weight::from_parts(3_586_000, 0) + .saturating_add(Weight::from_parts(0, 5487)) .saturating_add(T::DbWeight::get().reads(2)) } /// Storage: `ToRococoXcmRouter::Bridge` (r:1 w:1) /// Proof: `ToRococoXcmRouter::Bridge` (`max_values`: Some(1), `max_size`: Some(17), added: 512, mode: `MaxEncodedLen`) fn report_bridge_status() -> Weight { // Proof Size summary in bytes: - // Measured: `117` + // Measured: `150` // Estimated: `1502` - // Minimum execution time: 10_280_000 picoseconds. - Weight::from_parts(10_703_000, 0) + // Minimum execution time: 9_706_000 picoseconds. + Weight::from_parts(10_139_000, 0) .saturating_add(Weight::from_parts(0, 1502)) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } - /// Storage: `PolkadotXcm::SupportedVersion` (r:2 w:0) - /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) /// Storage: UNKNOWN KEY `0x3302afcb67e838a3f960251b417b9a4f` (r:1 w:0) @@ -100,7 +98,9 @@ impl pallet_xcm_bridge_hub_router::WeightInfo for Weigh /// Storage: `ToRococoXcmRouter::Bridge` (r:1 w:1) /// Proof: `ToRococoXcmRouter::Bridge` (`max_values`: Some(1), `max_size`: Some(17), added: 512, mode: `MaxEncodedLen`) /// Storage: `XcmpQueue::DeliveryFeeFactor` (r:1 w:0) - /// Proof: `XcmpQueue::DeliveryFeeFactor` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Proof: `XcmpQueue::DeliveryFeeFactor` (`max_values`: None, `max_size`: Some(28), added: 2503, mode: `MaxEncodedLen`) + /// Storage: `PolkadotXcm::SupportedVersion` (r:2 w:0) + /// Proof: `PolkadotXcm::SupportedVersion` (`max_values`: None, `max_size`: None, mode: `Measured`) /// Storage: `PolkadotXcm::VersionDiscoveryQueue` (r:1 w:1) /// Proof: `PolkadotXcm::VersionDiscoveryQueue` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `PolkadotXcm::SafeXcmVersion` (r:1 w:0) @@ -108,18 +108,18 @@ impl pallet_xcm_bridge_hub_router::WeightInfo for Weigh /// Storage: `ParachainSystem::RelevantMessagingState` (r:1 w:0) /// Proof: `ParachainSystem::RelevantMessagingState` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:1) - /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: Some(1282), added: 1777, mode: `MaxEncodedLen`) /// Storage: `XcmpQueue::InboundXcmpSuspended` (r:1 w:0) - /// Proof: `XcmpQueue::InboundXcmpSuspended` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Proof: `XcmpQueue::InboundXcmpSuspended` (`max_values`: Some(1), `max_size`: Some(4002), added: 4497, mode: `MaxEncodedLen`) /// Storage: `XcmpQueue::OutboundXcmpMessages` (r:0 w:1) - /// Proof: `XcmpQueue::OutboundXcmpMessages` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Proof: `XcmpQueue::OutboundXcmpMessages` (`max_values`: None, `max_size`: Some(105506), added: 107981, mode: `MaxEncodedLen`) fn send_message() -> Weight { // Proof Size summary in bytes: - // Measured: `487` - // Estimated: `6427` - // Minimum execution time: 63_624_000 picoseconds. - Weight::from_parts(66_071_000, 0) - .saturating_add(Weight::from_parts(0, 6427)) + // Measured: `520` + // Estimated: `6460` + // Minimum execution time: 46_250_000 picoseconds. + Weight::from_parts(47_801_000, 0) + .saturating_add(Weight::from_parts(0, 6460)) .saturating_add(T::DbWeight::get().reads(12)) .saturating_add(T::DbWeight::get().writes(4)) } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/mod.rs index 8c77774da2dd747f4c3321ae9e2dfb3984cedb0f..d39052c5c03b84f8c02f8257bd9f5a739f4f8624 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/mod.rs @@ -17,10 +17,10 @@ mod pallet_xcm_benchmarks_fungible; mod pallet_xcm_benchmarks_generic; use crate::{xcm_config::MaxAssetsIntoHolding, Runtime}; +use alloc::vec::Vec; use frame_support::weights::Weight; use pallet_xcm_benchmarks_fungible::WeightInfo as XcmFungibleWeight; use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; -use sp_std::prelude::*; use xcm::{latest::prelude::*, DoubleEncoded}; trait WeighAssets { diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs index eaf07aac52cefa88f524e6f3a2180ab9faf2b088..fe8d186139256fbaac3989e0c56fb3acc494d63e 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs @@ -42,7 +42,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weights for `pallet_xcm_benchmarks::fungible`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index fc196abea0f5e61d746760e2b2bf5a7d8d0a476b..127bc173c103741839ac2466b0d6ae7d5942ea7f 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -42,7 +42,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weights for `pallet_xcm_benchmarks::generic`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs index fc2e68c599fd1415df04c6b89510503091ef6cb5..5ecfce18b6dacf5fd1b1b0c012d98c4cd4c70fb7 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs @@ -51,11 +51,10 @@ use xcm_builder::{ EnsureXcmOrigin, FrameTransactionalProcessor, FungibleAdapter, FungiblesAdapter, GlobalConsensusParachainConvertsFor, HashedDescription, IsConcrete, LocalMint, NetworkExportTableItem, NoChecking, NonFungiblesAdapter, ParentAsSuperuser, ParentIsPreset, - RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, + RelayChainAsNative, SendXcmFeeToAccount, SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, StartsWith, StartsWithExplicitGlobalConsensus, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, XcmFeeManagerFromComponents, - XcmFeeToAccount, }; use xcm_executor::XcmExecutor; @@ -429,7 +428,7 @@ impl xcm_executor::Config for XcmConfig { type AssetExchanger = (); type FeeManager = XcmFeeManagerFromComponents< WaivedLocations, - XcmFeeToAccount, + SendXcmFeeToAccount, >; type MessageExporter = (); type UniversalAliases = (bridging::to_rococo::UniversalAliases,); @@ -519,8 +518,8 @@ impl pallet_assets::BenchmarkHelper for XcmBenchmarkHelper { /// All configuration related to bridging pub mod bridging { use super::*; + use alloc::collections::btree_set::BTreeSet; use assets_common::matching; - use sp_std::collections::btree_set::BTreeSet; parameter_types! { /// Base price of every byte of the Westend -> Rococo message. Can be adjusted via @@ -548,8 +547,8 @@ pub mod bridging { /// (`AssetId` has to be aligned with `BridgeTable`) pub XcmBridgeHubRouterFeeAssetId: AssetId = WestendLocation::get().into(); - pub BridgeTable: sp_std::vec::Vec = - sp_std::vec::Vec::new().into_iter() + pub BridgeTable: alloc::vec::Vec = + alloc::vec::Vec::new().into_iter() .chain(to_rococo::BridgeTable::get()) .collect(); } @@ -580,10 +579,10 @@ pub mod bridging { /// Set up exporters configuration. /// `Option` represents static "base fee" which is used for total delivery fee calculation. - pub BridgeTable: sp_std::vec::Vec = sp_std::vec![ + pub BridgeTable: alloc::vec::Vec = alloc::vec![ NetworkExportTableItem::new( RococoNetwork::get(), - Some(sp_std::vec![ + Some(alloc::vec![ AssetHubRococo::get().interior.split_global().expect("invalid configuration for AssetHubRococo").1, ]), SiblingBridgeHub::get(), @@ -597,7 +596,7 @@ pub mod bridging { /// Universal aliases pub UniversalAliases: BTreeSet<(Location, Junction)> = BTreeSet::from_iter( - sp_std::vec![ + alloc::vec![ (SiblingBridgeHubWithBridgeHubRococoInstance::get(), GlobalConsensus(RococoNetwork::get())) ] ); diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/tests/tests.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/tests/tests.rs index b5957dd5df92ff1180909535cb6e604deadd8829..48e6c11d268c7c2e915c3ce4c0213ede2c883911 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/tests/tests.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/tests/tests.rs @@ -1258,7 +1258,7 @@ fn report_bridge_status_from_xcm_bridge_router_for_rococo_works() { collator_session_keys(), bridging_to_asset_hub_rococo, || { - sp_std::vec![ + vec![ UnpaidExecution { weight_limit: Unlimited, check_origin: None }, Transact { origin_kind: OriginKind::Xcm, @@ -1268,16 +1268,16 @@ fn report_bridge_status_from_xcm_bridge_router_for_rococo_works() { bp_asset_hub_westend::XcmBridgeHubRouterCall::report_bridge_status { bridge_id: Default::default(), is_congested: true, - } + }, ) .encode() .into(), - } + }, ] .into() }, || { - sp_std::vec![ + vec![ UnpaidExecution { weight_limit: Unlimited, check_origin: None }, Transact { origin_kind: OriginKind::Xcm, @@ -1287,11 +1287,11 @@ fn report_bridge_status_from_xcm_bridge_router_for_rococo_works() { bp_asset_hub_westend::XcmBridgeHubRouterCall::report_bridge_status { bridge_id: Default::default(), is_congested: false, - } + }, ) .encode() .into(), - } + }, ] .into() }, diff --git a/cumulus/parachains/runtimes/assets/common/Cargo.toml b/cumulus/parachains/runtimes/assets/common/Cargo.toml index 94612506f510e3677db444c61c05db46f84cdc0e..c6740269339d808f14d9dd2879f2ddd74b4e842b 100644 --- a/cumulus/parachains/runtimes/assets/common/Cargo.toml +++ b/cumulus/parachains/runtimes/assets/common/Cargo.toml @@ -18,7 +18,6 @@ impl-trait-for-tuples = { workspace = true } # Substrate frame-support = { workspace = true } sp-api = { workspace = true } -sp-std = { workspace = true } sp-runtime = { workspace = true } pallet-asset-conversion = { workspace = true } @@ -48,7 +47,6 @@ std = [ "scale-info/std", "sp-api/std", "sp-runtime/std", - "sp-std/std", "xcm-builder/std", "xcm-executor/std", "xcm/std", diff --git a/cumulus/parachains/runtimes/assets/common/src/benchmarks.rs b/cumulus/parachains/runtimes/assets/common/src/benchmarks.rs index 44bda1eb3709c74d808e696d5d3728a3354b747a..d59fddc4e8f0289fd8ab4aebe7465551c83c136a 100644 --- a/cumulus/parachains/runtimes/assets/common/src/benchmarks.rs +++ b/cumulus/parachains/runtimes/assets/common/src/benchmarks.rs @@ -13,9 +13,9 @@ // See the License for the specific language governing permissions and // limitations under the License. +use core::marker::PhantomData; use cumulus_primitives_core::ParaId; use sp_runtime::traits::Get; -use sp_std::marker::PhantomData; use xcm::latest::prelude::*; /// Creates asset pairs for liquidity pools with `Target` always being the first asset. diff --git a/cumulus/parachains/runtimes/assets/common/src/foreign_creators.rs b/cumulus/parachains/runtimes/assets/common/src/foreign_creators.rs index a9fd79bf939f575ac60007cd6920ac6db3ded773..95edb31da06e5a0ff1f9d40f3d385f6bd2c21e35 100644 --- a/cumulus/parachains/runtimes/assets/common/src/foreign_creators.rs +++ b/cumulus/parachains/runtimes/assets/common/src/foreign_creators.rs @@ -23,7 +23,7 @@ use xcm_executor::traits::ConvertLocation; /// `EnsureOriginWithArg` impl for `CreateOrigin` that allows only XCM origins that are locations /// containing the class location. pub struct ForeignCreators( - sp_std::marker::PhantomData<(IsForeign, AccountOf, AccountId, L)>, + core::marker::PhantomData<(IsForeign, AccountOf, AccountId, L)>, ); impl< IsForeign: ContainsPair, @@ -41,7 +41,7 @@ where fn try_origin( origin: RuntimeOrigin, asset_location: &L, - ) -> sp_std::result::Result { + ) -> core::result::Result { let origin_location = EnsureXcm::::try_origin(origin.clone())?; if !IsForeign::contains(asset_location, &origin_location) { return Err(origin) diff --git a/cumulus/parachains/runtimes/assets/common/src/fungible_conversion.rs b/cumulus/parachains/runtimes/assets/common/src/fungible_conversion.rs index e21203485a764c350b3d9890d7dcdaa89110babf..27ee2d6b5653c91bd922045005201439870c324a 100644 --- a/cumulus/parachains/runtimes/assets/common/src/fungible_conversion.rs +++ b/cumulus/parachains/runtimes/assets/common/src/fungible_conversion.rs @@ -16,9 +16,10 @@ //! Runtime API definition for assets. use crate::runtime_api::FungiblesAccessError; +use alloc::vec::Vec; +use core::borrow::Borrow; use frame_support::traits::Contains; use sp_runtime::traits::MaybeEquivalence; -use sp_std::{borrow::Borrow, vec::Vec}; use xcm::latest::{Asset, Location}; use xcm_builder::{ConvertedConcreteId, MatchedConvertedConcreteId}; use xcm_executor::traits::MatchesFungibles; diff --git a/cumulus/parachains/runtimes/assets/common/src/lib.rs b/cumulus/parachains/runtimes/assets/common/src/lib.rs index 431b5766147aeb8279ed2b1298691ceede856e5e..4bb593f98929e4dfcaf2879e759f863138f49282 100644 --- a/cumulus/parachains/runtimes/assets/common/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/common/src/lib.rs @@ -23,6 +23,8 @@ pub mod local_and_foreign_assets; pub mod matching; pub mod runtime_api; +extern crate alloc; + use crate::matching::{LocalLocationPattern, ParentLocation}; use frame_support::traits::{Equals, EverythingBut}; use parachains_common::{AssetIdForTrustBackedAssets, CollectionId, ItemId}; diff --git a/cumulus/parachains/runtimes/assets/common/src/local_and_foreign_assets.rs b/cumulus/parachains/runtimes/assets/common/src/local_and_foreign_assets.rs index 58f5d2d57a7669b73876897f90e0da3e20730cbb..8a89089c7187726d30cc485b9280853a9da277e3 100644 --- a/cumulus/parachains/runtimes/assets/common/src/local_and_foreign_assets.rs +++ b/cumulus/parachains/runtimes/assets/common/src/local_and_foreign_assets.rs @@ -13,13 +13,13 @@ // See the License for the specific language governing permissions and // limitations under the License. +use core::marker::PhantomData; use frame_support::traits::Get; use sp_runtime::{ traits::{Convert, MaybeEquivalence}, Either, Either::{Left, Right}, }; -use sp_std::marker::PhantomData; use xcm::latest::Location; /// Converts a given [`Location`] to [`Either::Left`] when equal to `Target`, or diff --git a/cumulus/parachains/runtimes/assets/common/src/matching.rs b/cumulus/parachains/runtimes/assets/common/src/matching.rs index f356cb541315fa814c3df5d7ad69342c132661d3..9bb35d0c5328b8de455f6f3c75f4d2965d5fe44f 100644 --- a/cumulus/parachains/runtimes/assets/common/src/matching.rs +++ b/cumulus/parachains/runtimes/assets/common/src/matching.rs @@ -28,7 +28,7 @@ frame_support::parameter_types! { } /// Accepts an asset if it is from the origin. -pub struct IsForeignConcreteAsset(sp_std::marker::PhantomData); +pub struct IsForeignConcreteAsset(core::marker::PhantomData); impl> ContainsPair for IsForeignConcreteAsset { @@ -41,7 +41,7 @@ impl> ContainsPair /// Checks if `a` is from sibling location `b`. Checks that `Location-a` starts with /// `Location-b`, and that the `ParaId` of `b` is not equal to `a`. pub struct FromSiblingParachain( - sp_std::marker::PhantomData<(SelfParaId, L)>, + core::marker::PhantomData<(SelfParaId, L)>, ); impl, L: TryFrom + TryInto + Clone> ContainsPair for FromSiblingParachain @@ -65,7 +65,7 @@ impl, L: TryFrom + TryInto + Clone> /// Checks if `a` is from the expected global consensus network. Checks that `Location-a` /// starts with `Location-b`, and that network is a foreign consensus system. pub struct FromNetwork( - sp_std::marker::PhantomData<(UniversalLocation, ExpectedNetworkId, L)>, + core::marker::PhantomData<(UniversalLocation, ExpectedNetworkId, L)>, ); impl< UniversalLocation: Get, @@ -100,7 +100,7 @@ impl< /// Accept an asset if it is native to `AssetsAllowedNetworks` and it is coming from /// `OriginLocation`. pub struct RemoteAssetFromLocation( - sp_std::marker::PhantomData<(AssetsAllowedNetworks, OriginLocation)>, + core::marker::PhantomData<(AssetsAllowedNetworks, OriginLocation)>, ); impl, OriginLocation: Get> ContainsPair for RemoteAssetFromLocation diff --git a/cumulus/parachains/runtimes/assets/common/src/runtime_api.rs b/cumulus/parachains/runtimes/assets/common/src/runtime_api.rs index 19977cbedab07b638f71f32470d3768cabeba322..799b2f45b4dfbff288383821598954f30612f806 100644 --- a/cumulus/parachains/runtimes/assets/common/src/runtime_api.rs +++ b/cumulus/parachains/runtimes/assets/common/src/runtime_api.rs @@ -18,7 +18,7 @@ use codec::{Codec, Decode, Encode}; use sp_runtime::RuntimeDebug; #[cfg(feature = "std")] -use {sp_std::vec::Vec, xcm::latest::Asset}; +use {alloc::vec::Vec, xcm::latest::Asset}; /// The possible errors that can happen querying the storage of assets. #[derive(Eq, PartialEq, Encode, Decode, RuntimeDebug, scale_info::TypeInfo)] diff --git a/cumulus/parachains/runtimes/assets/test-utils/Cargo.toml b/cumulus/parachains/runtimes/assets/test-utils/Cargo.toml index a7aad361e84e1b4c8555f57be2dafacab760c15d..529d6460fc4e46b6a7d04ae77c01f7135f6eed9d 100644 --- a/cumulus/parachains/runtimes/assets/test-utils/Cargo.toml +++ b/cumulus/parachains/runtimes/assets/test-utils/Cargo.toml @@ -21,7 +21,6 @@ pallet-timestamp = { workspace = true } pallet-session = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } # Cumulus cumulus-pallet-parachain-system = { workspace = true } @@ -68,7 +67,6 @@ std = [ "parachains-runtimes-test-utils/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", "xcm-builder/std", "xcm-executor/std", "xcm/std", diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/Cargo.toml b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/Cargo.toml index 1ac31efaf912d7a115a704d37bb3d3e76a2db854..98737298468210671a6140fb119f504bd8f7f9e4 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/Cargo.toml +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/Cargo.toml @@ -96,7 +96,7 @@ bp-parachains = { workspace = true } bp-polkadot-bulletin = { workspace = true } bp-polkadot-core = { workspace = true } bp-relayers = { workspace = true } -bp-runtime = { workspace = true } +bp-runtime = { features = ["test-helpers"], workspace = true } bp-rococo = { workspace = true } bp-westend = { workspace = true } pallet-bridge-grandpa = { workspace = true } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_common_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_common_config.rs index 5551b05e202547c99501b279e8839611efcc7f66..779cc537ee96dcc2fadc38452dfcd01c4c320789 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_common_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_common_config.rs @@ -21,14 +21,9 @@ //! For example, the messaging pallet needs to know the sending and receiving chains, but the //! GRANDPA tracking pallet only needs to be aware of one chain. -use super::{ - weights, AccountId, Balance, Balances, BlockNumber, Runtime, RuntimeEvent, RuntimeOrigin, -}; +use super::{weights, AccountId, Balance, Balances, BlockNumber, Runtime, RuntimeEvent}; use bp_parachains::SingleParaStoredHeaderDataBuilder; -use bp_runtime::UnderlyingChainProvider; -use bridge_runtime_common::messages::ThisChainWithMessages; use frame_support::{parameter_types, traits::ConstU32}; -use sp_runtime::RuntimeDebug; parameter_types! { pub const RelayChainHeadersToKeep: u32 = 1024; @@ -103,15 +98,3 @@ impl pallet_bridge_grandpa::Config for Runt // weights are also the same for both bridges. type WeightInfo = weights::pallet_bridge_grandpa::WeightInfo; } - -/// BridgeHubRococo chain from message lane point of view. -#[derive(RuntimeDebug, Clone, Copy)] -pub struct BridgeHubRococo; - -impl UnderlyingChainProvider for BridgeHubRococo { - type Chain = bp_bridge_hub_rococo::BridgeHubRococo; -} - -impl ThisChainWithMessages for BridgeHubRococo { - type RuntimeOrigin = RuntimeOrigin; -} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_bulletin_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_bulletin_config.rs index 94b936889b77c4460f9921956d6f7abef1ecb52c..d97e6a1d88e1b698c2a047adb11ede43827f18f1 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_bulletin_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_bulletin_config.rs @@ -20,23 +20,20 @@ //! are reusing Polkadot Bulletin chain primitives everywhere here. use crate::{ - bridge_common_config::BridgeHubRococo, weights, xcm_config::UniversalLocation, AccountId, - BridgeRococoBulletinGrandpa, BridgeRococoBulletinMessages, PolkadotXcm, Runtime, RuntimeEvent, - XcmOverRococoBulletin, XcmRouter, + weights, xcm_config::UniversalLocation, BridgeRococoBulletinGrandpa, + BridgeRococoBulletinMessages, PolkadotXcm, Runtime, RuntimeEvent, XcmOverRococoBulletin, + XcmRouter, +}; +use bp_messages::{ + source_chain::FromBridgedChainMessagesDeliveryProof, + target_chain::FromBridgedChainMessagesProof, LaneId, }; -use bp_messages::LaneId; use bp_runtime::Chain; use bridge_runtime_common::{ extensions::refund_relayer_extension::{ ActualFeeRefund, RefundBridgedMessages, RefundSignedExtensionAdapter, RefundableMessagesLane, }, - messages, - messages::{ - source::{FromBridgedChainMessagesDeliveryProof, TargetHeaderChainAdapter}, - target::{FromBridgedChainMessagesProof, SourceHeaderChainAdapter}, - MessageBridge, UnderlyingChainProvider, - }, messages_xcm_extension::{ SenderAndLane, XcmAsPlainPayload, XcmBlobHauler, XcmBlobHaulerAdapter, XcmBlobMessageDispatch, XcmVersionOfDestAndRemoteBridge, @@ -44,7 +41,6 @@ use bridge_runtime_common::{ }; use frame_support::{parameter_types, traits::PalletInfoAccess}; -use sp_runtime::RuntimeDebug; use xcm::{ latest::prelude::*, prelude::{InteriorLocation, NetworkId}, @@ -52,15 +48,6 @@ use xcm::{ use xcm_builder::BridgeBlobDispatcher; parameter_types! { - /// Maximal number of entries in the unrewarded relayers vector at the Rococo Bridge Hub. It matches the - /// maximal number of unrewarded relayers that the single confirmation transaction at Rococo Bulletin Chain - /// may process. - pub const MaxUnrewardedRelayerEntriesAtInboundLane: bp_messages::MessageNonce = - bp_polkadot_bulletin::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX; - /// Maximal number of unconfirmed messages at the Rococo Bridge Hub. It matches the maximal number of - /// unconfirmed messages that the single confirmation transaction at Rococo Bulletin Chain may process. - pub const MaxUnconfirmedMessagesAtInboundLane: bp_messages::MessageNonce = - bp_polkadot_bulletin::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX; /// Bridge specific chain (network) identifier of the Rococo Bulletin Chain. pub const RococoBulletinChainId: bp_runtime::ChainId = bp_polkadot_bulletin::PolkadotBulletin::ID; /// Interior location (relative to this runtime) of the with-RococoBulletin messages pallet. @@ -100,7 +87,7 @@ parameter_types! { XCM_LANE_FOR_ROCOCO_PEOPLE_TO_ROCOCO_BULLETIN, ); /// All active routes and their destinations. - pub ActiveLanes: sp_std::vec::Vec<(SenderAndLane, (NetworkId, InteriorLocation))> = sp_std::vec![ + pub ActiveLanes: alloc::vec::Vec<(SenderAndLane, (NetworkId, InteriorLocation))> = alloc::vec![ ( FromRococoPeopleToRococoBulletinRoute::get(), (RococoBulletinGlobalConsensusNetwork::get(), Here) @@ -142,31 +129,6 @@ impl XcmBlobHauler for ToRococoBulletinXcmBlobHauler { type OnMessagesDeliveredFromRococoBulletin = XcmBlobHaulerAdapter; -/// Messaging Bridge configuration for BridgeHubRococo -> Rococo Bulletin. -pub struct WithRococoBulletinMessageBridge; -impl MessageBridge for WithRococoBulletinMessageBridge { - // Bulletin chain assumes it is bridged with Polkadot Bridge Hub - const BRIDGED_MESSAGES_PALLET_NAME: &'static str = - bp_bridge_hub_polkadot::WITH_BRIDGE_HUB_POLKADOT_MESSAGES_PALLET_NAME; - type ThisChain = BridgeHubRococo; - type BridgedChain = RococoBulletin; - type BridgedHeaderChain = BridgeRococoBulletinGrandpa; -} - -/// Maximal outbound payload size of BridgeHubRococo -> RococoBulletin messages. -pub type ToRococoBulletinMaximalOutboundPayloadSize = - messages::source::FromThisChainMaximalOutboundPayloadSize; - -/// RococoBulletin chain from message lane point of view. -#[derive(RuntimeDebug, Clone, Copy)] -pub struct RococoBulletin; - -impl UnderlyingChainProvider for RococoBulletin { - type Chain = bp_polkadot_bulletin::PolkadotBulletin; -} - -impl messages::BridgedChainWithMessages for RococoBulletin {} - /// Signed extension that refunds relayers that are delivering messages from the Rococo Bulletin /// chain. pub type OnBridgeHubRococoRefundRococoBulletinMessages = RefundSignedExtensionAdapter< @@ -189,22 +151,20 @@ impl pallet_bridge_messages::Config for Runt type RuntimeEvent = RuntimeEvent; type WeightInfo = weights::pallet_bridge_messages_rococo_to_rococo_bulletin::WeightInfo; - type BridgedChainId = RococoBulletinChainId; + + type ThisChain = bp_bridge_hub_rococo::BridgeHubRococo; + type BridgedChain = bp_polkadot_bulletin::PolkadotBulletin; + type BridgedHeaderChain = BridgeRococoBulletinGrandpa; + type ActiveOutboundLanes = ActiveOutboundLanesToRococoBulletin; - type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane; - type MaxUnconfirmedMessagesAtInboundLane = MaxUnconfirmedMessagesAtInboundLane; - type MaximalOutboundPayloadSize = ToRococoBulletinMaximalOutboundPayloadSize; type OutboundPayload = XcmAsPlainPayload; type InboundPayload = XcmAsPlainPayload; - type InboundRelayer = AccountId; type DeliveryPayments = (); - type TargetHeaderChain = TargetHeaderChainAdapter; type DeliveryConfirmationPayments = (); - type SourceHeaderChain = SourceHeaderChainAdapter; type MessageDispatch = XcmBlobMessageDispatch; type OnMessagesDelivered = OnMessagesDeliveredFromRococoBulletin; @@ -267,8 +227,7 @@ mod tests { runtime: Runtime, with_bridged_chain_grandpa_instance: BridgeGrandpaRococoBulletinInstance, with_bridged_chain_messages_instance: WithRococoBulletinMessagesInstance, - bridge: WithRococoBulletinMessageBridge, - this_chain: bp_rococo::Rococo, + this_chain: bp_bridge_hub_rococo::BridgeHubRococo, bridged_chain: bp_polkadot_bulletin::PolkadotBulletin, ); diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_westend_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_westend_config.rs index 1681ac7f4687493c82c0a3233439b2a9d47a1ad0..fe854e20c244545a770edcdb6c6c57a49c93b124 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_westend_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/bridge_to_westend_config.rs @@ -17,27 +17,21 @@ //! Bridge definitions used on BridgeHubRococo for bridging to BridgeHubWestend. use crate::{ - bridge_common_config::{ - BridgeHubRococo, BridgeParachainWestendInstance, DeliveryRewardInBalance, - }, + bridge_common_config::{BridgeParachainWestendInstance, DeliveryRewardInBalance}, weights, xcm_config::UniversalLocation, - AccountId, BridgeWestendMessages, PolkadotXcm, Runtime, RuntimeEvent, XcmOverBridgeHubWestend, - XcmRouter, + BridgeWestendMessages, PolkadotXcm, Runtime, RuntimeEvent, XcmOverBridgeHubWestend, XcmRouter, +}; +use bp_messages::{ + source_chain::FromBridgedChainMessagesDeliveryProof, + target_chain::FromBridgedChainMessagesProof, LaneId, }; -use bp_messages::LaneId; use bp_runtime::Chain; use bridge_runtime_common::{ extensions::refund_relayer_extension::{ ActualFeeRefund, RefundBridgedMessages, RefundSignedExtensionAdapter, RefundableMessagesLane, }, - messages, - messages::{ - source::{FromBridgedChainMessagesDeliveryProof, TargetHeaderChainAdapter}, - target::{FromBridgedChainMessagesProof, SourceHeaderChainAdapter}, - MessageBridge, UnderlyingChainProvider, - }, messages_xcm_extension::{ SenderAndLane, XcmAsPlainPayload, XcmBlobHauler, XcmBlobHaulerAdapter, XcmBlobMessageDispatch, XcmVersionOfDestAndRemoteBridge, @@ -46,7 +40,6 @@ use bridge_runtime_common::{ use codec::Encode; use frame_support::{parameter_types, traits::PalletInfoAccess}; -use sp_runtime::RuntimeDebug; use xcm::{ latest::prelude::*, prelude::{InteriorLocation, NetworkId}, @@ -54,11 +47,7 @@ use xcm::{ use xcm_builder::BridgeBlobDispatcher; parameter_types! { - pub const MaxUnrewardedRelayerEntriesAtInboundLane: bp_messages::MessageNonce = - bp_bridge_hub_rococo::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX; - pub const MaxUnconfirmedMessagesAtInboundLane: bp_messages::MessageNonce = - bp_bridge_hub_rococo::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX; - pub const BridgeHubWestendChainId: bp_runtime::ChainId = BridgeHubWestend::ID; + pub const BridgeHubWestendChainId: bp_runtime::ChainId = bp_bridge_hub_westend::BridgeHubWestend::ID; pub BridgeRococoToWestendMessagesPalletInstance: InteriorLocation = [PalletInstance(::index() as u8)].into(); pub WestendGlobalConsensusNetwork: NetworkId = NetworkId::Westend; pub WestendGlobalConsensusNetworkLocation: Location = Location::new( @@ -82,7 +71,7 @@ parameter_types! { ParentThen([Parachain(AssetHubRococoParaId::get().into())].into()).into(), XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WESTEND, ); - pub ActiveLanes: sp_std::vec::Vec<(SenderAndLane, (NetworkId, InteriorLocation))> = sp_std::vec![ + pub ActiveLanes: alloc::vec::Vec<(SenderAndLane, (NetworkId, InteriorLocation))> = alloc::vec![ ( FromAssetHubRococoToAssetHubWestendRoute::get(), (WestendGlobalConsensusNetwork::get(), [Parachain(AssetHubWestendParaId::get().into())].into()) @@ -102,8 +91,8 @@ parameter_types! { } pub const XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WESTEND: LaneId = LaneId([0, 0, 0, 2]); -fn build_congestion_message(is_congested: bool) -> sp_std::vec::Vec> { - sp_std::vec![ +fn build_congestion_message(is_congested: bool) -> alloc::vec::Vec> { + alloc::vec![ UnpaidExecution { weight_limit: Unlimited, check_origin: None }, Transact { origin_kind: OriginKind::Xcm, @@ -148,34 +137,6 @@ impl XcmBlobHauler for ToBridgeHubWestendXcmBlobHauler { type OnMessagesDeliveredFromWestend = XcmBlobHaulerAdapter; -/// Messaging Bridge configuration for BridgeHubRococo -> BridgeHubWestend -pub struct WithBridgeHubWestendMessageBridge; -impl MessageBridge for WithBridgeHubWestendMessageBridge { - const BRIDGED_MESSAGES_PALLET_NAME: &'static str = - bp_bridge_hub_rococo::WITH_BRIDGE_HUB_ROCOCO_MESSAGES_PALLET_NAME; - type ThisChain = BridgeHubRococo; - type BridgedChain = BridgeHubWestend; - type BridgedHeaderChain = pallet_bridge_parachains::ParachainHeaders< - Runtime, - BridgeParachainWestendInstance, - bp_bridge_hub_westend::BridgeHubWestend, - >; -} - -/// Maximal outbound payload size of BridgeHubRococo -> BridgeHubWestend messages. -pub type ToBridgeHubWestendMaximalOutboundPayloadSize = - messages::source::FromThisChainMaximalOutboundPayloadSize; - -/// BridgeHubWestend chain from message lane point of view. -#[derive(RuntimeDebug, Clone, Copy)] -pub struct BridgeHubWestend; - -impl UnderlyingChainProvider for BridgeHubWestend { - type Chain = bp_bridge_hub_westend::BridgeHubWestend; -} - -impl messages::BridgedChainWithMessages for BridgeHubWestend {} - /// Signed extension that refunds relayers that are delivering messages from the Westend parachain. pub type OnBridgeHubRococoRefundBridgeHubWestendMessages = RefundSignedExtensionAdapter< RefundBridgedMessages< @@ -196,26 +157,28 @@ pub type WithBridgeHubWestendMessagesInstance = pallet_bridge_messages::Instance impl pallet_bridge_messages::Config for Runtime { type RuntimeEvent = RuntimeEvent; type WeightInfo = weights::pallet_bridge_messages_rococo_to_westend::WeightInfo; - type BridgedChainId = BridgeHubWestendChainId; + + type ThisChain = bp_bridge_hub_rococo::BridgeHubRococo; + type BridgedChain = bp_bridge_hub_westend::BridgeHubWestend; + type BridgedHeaderChain = pallet_bridge_parachains::ParachainHeaders< + Runtime, + BridgeParachainWestendInstance, + bp_bridge_hub_westend::BridgeHubWestend, + >; + type ActiveOutboundLanes = ActiveOutboundLanesToBridgeHubWestend; - type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane; - type MaxUnconfirmedMessagesAtInboundLane = MaxUnconfirmedMessagesAtInboundLane; - type MaximalOutboundPayloadSize = ToBridgeHubWestendMaximalOutboundPayloadSize; type OutboundPayload = XcmAsPlainPayload; type InboundPayload = XcmAsPlainPayload; - type InboundRelayer = AccountId; type DeliveryPayments = (); - type TargetHeaderChain = TargetHeaderChainAdapter; type DeliveryConfirmationPayments = pallet_bridge_relayers::DeliveryConfirmationPaymentsAdapter< Runtime, WithBridgeHubWestendMessagesInstance, DeliveryRewardInBalance, >; - type SourceHeaderChain = SourceHeaderChainAdapter; type MessageDispatch = XcmBlobMessageDispatch< FromWestendMessageBlobDispatcher, Self::WeightInfo, @@ -248,9 +211,8 @@ mod tests { assert_complete_bridge_types, extensions::refund_relayer_extension::RefundableParachain, integrity::{ - assert_complete_bridge_constants, check_message_lane_weights, - AssertBridgeMessagesPalletConstants, AssertBridgePalletNames, AssertChainConstants, - AssertCompleteBridgeConstants, + assert_complete_with_parachain_bridge_constants, check_message_lane_weights, + AssertChainConstants, AssertCompleteBridgeConstants, }, }; use parachains_common::Balance; @@ -292,36 +254,20 @@ mod tests { runtime: Runtime, with_bridged_chain_grandpa_instance: BridgeGrandpaWestendInstance, with_bridged_chain_messages_instance: WithBridgeHubWestendMessagesInstance, - bridge: WithBridgeHubWestendMessageBridge, - this_chain: bp_rococo::Rococo, - bridged_chain: bp_westend::Westend, + this_chain: bp_bridge_hub_rococo::BridgeHubRococo, + bridged_chain: bp_bridge_hub_westend::BridgeHubWestend, ); - assert_complete_bridge_constants::< + assert_complete_with_parachain_bridge_constants::< Runtime, BridgeGrandpaWestendInstance, WithBridgeHubWestendMessagesInstance, - WithBridgeHubWestendMessageBridge, + bp_westend::Westend, >(AssertCompleteBridgeConstants { this_chain_constants: AssertChainConstants { block_length: bp_bridge_hub_rococo::BlockLength::get(), block_weights: bp_bridge_hub_rococo::BlockWeightsForAsyncBacking::get(), }, - messages_pallet_constants: AssertBridgeMessagesPalletConstants { - max_unrewarded_relayers_in_bridged_confirmation_tx: - bp_bridge_hub_westend::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX, - max_unconfirmed_messages_in_bridged_confirmation_tx: - bp_bridge_hub_westend::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX, - bridged_chain_id: BridgeHubWestend::ID, - }, - pallet_names: AssertBridgePalletNames { - with_this_chain_messages_pallet_name: - bp_bridge_hub_rococo::WITH_BRIDGE_HUB_ROCOCO_MESSAGES_PALLET_NAME, - with_bridged_chain_grandpa_pallet_name: - bp_westend::WITH_WESTEND_GRANDPA_PALLET_NAME, - with_bridged_chain_messages_pallet_name: - bp_bridge_hub_westend::WITH_BRIDGE_HUB_WESTEND_MESSAGES_PALLET_NAME, - }, }); bridge_runtime_common::extensions::priority_calculator::per_relay_header::ensure_priority_boost_is_sane::< @@ -332,7 +278,7 @@ mod tests { bridge_runtime_common::extensions::priority_calculator::per_parachain_header::ensure_priority_boost_is_sane::< Runtime, - RefundableParachain, + RefundableParachain, PriorityBoostPerParachainHeader, >(FEE_BOOST_PER_PARACHAIN_HEADER); diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/lib.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/lib.rs index 57ed5ec258d2c0a1df7f824c465ff53953d25835..512c1199f43920f0832d0edf91a4205f37d7c493 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/lib.rs @@ -35,6 +35,9 @@ pub mod bridge_to_westend_config; mod weights; pub mod xcm_config; +extern crate alloc; + +use alloc::{vec, vec::Vec}; use bridge_runtime_common::extensions::{ check_obsolete_extension::{ CheckAndBoostBridgeGrandpaTransactions, CheckAndBoostBridgeParachainsTransactions, @@ -58,7 +61,6 @@ use sp_runtime::{ ApplyExtrinsicResult, FixedU128, }; -use sp_std::prelude::*; #[cfg(feature = "std")] use sp_version::NativeVersion; use sp_version::RuntimeVersion; @@ -110,6 +112,8 @@ use parachains_common::{ AVERAGE_ON_INITIALIZE_RATIO, NORMAL_DISPATCH_RATIO, }; +#[cfg(feature = "runtime-benchmarks")] +use alloc::boxed::Box; #[cfg(feature = "runtime-benchmarks")] use benchmark_helpers::DoNothingRouter; @@ -862,7 +866,7 @@ impl_runtime_apis! { Runtime::metadata_at_version(version) } - fn metadata_versions() -> sp_std::vec::Vec { + fn metadata_versions() -> alloc::vec::Vec { Runtime::metadata_versions() } } @@ -1197,7 +1201,7 @@ impl_runtime_apis! { use frame_system_benchmarking::Pallet as SystemBench; impl frame_system_benchmarking::Config for Runtime { - fn setup_set_code_requirements(code: &sp_std::vec::Vec) -> Result<(), BenchmarkError> { + fn setup_set_code_requirements(code: &alloc::vec::Vec) -> Result<(), BenchmarkError> { ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32); Ok(()) } @@ -1432,7 +1436,7 @@ impl_runtime_apis! { prepare_message_proof_from_parachain::< Runtime, bridge_common_config::BridgeGrandpaWestendInstance, - bridge_to_westend_config::WithBridgeHubWestendMessageBridge, + bridge_to_westend_config::WithBridgeHubWestendMessagesInstance, >(params, generate_xcm_builder_bridge_message_sample([GlobalConsensus(Rococo), Parachain(42)].into())) } @@ -1442,7 +1446,7 @@ impl_runtime_apis! { prepare_message_delivery_proof_from_parachain::< Runtime, bridge_common_config::BridgeGrandpaWestendInstance, - bridge_to_westend_config::WithBridgeHubWestendMessageBridge, + bridge_to_westend_config::WithBridgeHubWestendMessagesInstance, >(params) } @@ -1467,7 +1471,7 @@ impl_runtime_apis! { prepare_message_proof_from_grandpa_chain::< Runtime, bridge_common_config::BridgeGrandpaRococoBulletinInstance, - bridge_to_bulletin_config::WithRococoBulletinMessageBridge, + bridge_to_bulletin_config::WithRococoBulletinMessagesInstance, >(params, generate_xcm_builder_bridge_message_sample([GlobalConsensus(Rococo), Parachain(42)].into())) } @@ -1477,7 +1481,7 @@ impl_runtime_apis! { prepare_message_delivery_proof_from_grandpa_chain::< Runtime, bridge_common_config::BridgeGrandpaRococoBulletinInstance, - bridge_to_bulletin_config::WithRococoBulletinMessageBridge, + bridge_to_bulletin_config::WithRococoBulletinMessagesInstance, >(params) } @@ -1503,7 +1507,7 @@ impl_runtime_apis! { fn prepare_parachain_heads_proof( parachains: &[bp_polkadot_core::parachains::ParaId], parachain_head_size: u32, - proof_size: bp_runtime::StorageProofSize, + proof_params: bp_runtime::UnverifiedStorageProofParams, ) -> ( pallet_bridge_parachains::RelayBlockNumber, pallet_bridge_parachains::RelayBlockHash, @@ -1513,7 +1517,7 @@ impl_runtime_apis! { prepare_parachain_heads_proof::( parachains, parachain_head_size, - proof_size, + proof_params, ) } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/cumulus_pallet_parachain_system.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/cumulus_pallet_parachain_system.rs index dc480c391636a92aad6e303a515524b5ce7ff2b1..8fcd7b10d931b03ec4cd9cc063e0bacf8878ed16 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/cumulus_pallet_parachain_system.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/cumulus_pallet_parachain_system.rs @@ -47,7 +47,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weight functions for `cumulus_pallet_parachain_system`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_grandpa.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_grandpa.rs index bbd27bbb1d7d95731f6274edc468a50beca449bf..4ce57b2e50161a812ddf17a9bbd20d5fc58682a7 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_grandpa.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_grandpa.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_bridge_grandpa` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-06-26, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-07-11, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-7wrmsoux-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-yaoqqom-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-rococo-dev")`, DB CACHE: 1024 // Executed Command: @@ -68,13 +68,13 @@ impl pallet_bridge_grandpa::WeightInfo for WeightInfo pallet_bridge_grandpa::WeightInfo for WeightInfo pallet_bridge_messages::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `654` // Estimated: `52645` - // Minimum execution time: 37_405_000 picoseconds. - Weight::from_parts(38_397_000, 0) + // Minimum execution time: 37_206_000 picoseconds. + Weight::from_parts(38_545_000, 0) .saturating_add(Weight::from_parts(0, 52645)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(1)) @@ -74,13 +74,17 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< /// Proof: `BridgePolkadotBulletinMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - fn receive_two_messages_proof() -> Weight { + /// The range of component `n` is `[1, 4076]`. + /// The range of component `n` is `[1, 4076]`. + fn receive_n_messages_proof(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `654` // Estimated: `52645` - // Minimum execution time: 48_076_000 picoseconds. - Weight::from_parts(49_374_000, 0) + // Minimum execution time: 37_075_000 picoseconds. + Weight::from_parts(37_757_000, 0) .saturating_add(Weight::from_parts(0, 52645)) + // Standard Error: 5_776 + .saturating_add(Weight::from_parts(11_586_768, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -96,8 +100,8 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `654` // Estimated: `52645` - // Minimum execution time: 42_529_000 picoseconds. - Weight::from_parts(44_536_000, 0) + // Minimum execution time: 42_087_000 picoseconds. + Weight::from_parts(42_970_000, 0) .saturating_add(Weight::from_parts(0, 52645)) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(1)) @@ -108,30 +112,20 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< /// Proof: `BridgePolkadotBulletinGrandpa::ImportedHeaders` (`max_values`: Some(1024), `max_size`: Some(68), added: 1553, mode: `MaxEncodedLen`) /// Storage: `BridgePolkadotBulletinMessages::InboundLanes` (r:1 w:1) /// Proof: `BridgePolkadotBulletinMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) - fn receive_single_message_proof_1_kb() -> Weight { - // Proof Size summary in bytes: - // Measured: `622` - // Estimated: `52645` - // Minimum execution time: 36_101_000 picoseconds. - Weight::from_parts(37_356_000, 0) - .saturating_add(Weight::from_parts(0, 52645)) - .saturating_add(T::DbWeight::get().reads(3)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `BridgePolkadotBulletinMessages::PalletOperatingMode` (r:1 w:0) - /// Proof: `BridgePolkadotBulletinMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) - /// Storage: `BridgePolkadotBulletinGrandpa::ImportedHeaders` (r:1 w:0) - /// Proof: `BridgePolkadotBulletinGrandpa::ImportedHeaders` (`max_values`: Some(1024), `max_size`: Some(68), added: 1553, mode: `MaxEncodedLen`) - /// Storage: `BridgePolkadotBulletinMessages::InboundLanes` (r:1 w:1) - /// Proof: `BridgePolkadotBulletinMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) - fn receive_single_message_proof_16_kb() -> Weight { + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// The range of component `n` is `[1, 16384]`. + /// The range of component `n` is `[1, 16384]`. + fn receive_single_n_bytes_message_proof(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `622` + // Measured: `654` // Estimated: `52645` - // Minimum execution time: 70_370_000 picoseconds. - Weight::from_parts(72_054_000, 0) + // Minimum execution time: 35_055_000 picoseconds. + Weight::from_parts(36_987_740, 0) .saturating_add(Weight::from_parts(0, 52645)) - .saturating_add(T::DbWeight::get().reads(3)) + // Standard Error: 4 + .saturating_add(Weight::from_parts(2_316, 0).saturating_mul(n.into())) + .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `BridgePolkadotBulletinMessages::PalletOperatingMode` (r:1 w:0) @@ -144,8 +138,8 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `621` // Estimated: `2543` - // Minimum execution time: 25_144_000 picoseconds. - Weight::from_parts(25_876_000, 0) + // Minimum execution time: 24_326_000 picoseconds. + Weight::from_parts(25_169_000, 0) .saturating_add(Weight::from_parts(0, 2543)) .saturating_add(T::DbWeight::get().reads(3)) .saturating_add(T::DbWeight::get().writes(1)) @@ -160,8 +154,8 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `621` // Estimated: `2543` - // Minimum execution time: 25_085_000 picoseconds. - Weight::from_parts(25_872_000, 0) + // Minimum execution time: 24_484_000 picoseconds. + Weight::from_parts(25_130_000, 0) .saturating_add(Weight::from_parts(0, 2543)) .saturating_add(T::DbWeight::get().reads(3)) .saturating_add(T::DbWeight::get().writes(1)) @@ -176,8 +170,8 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `621` // Estimated: `2543` - // Minimum execution time: 25_181_000 picoseconds. - Weight::from_parts(25_920_000, 0) + // Minimum execution time: 24_450_000 picoseconds. + Weight::from_parts(25_164_000, 0) .saturating_add(Weight::from_parts(0, 2543)) .saturating_add(T::DbWeight::get().reads(3)) .saturating_add(T::DbWeight::get().writes(1)) @@ -204,17 +198,17 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: Some(1282), added: 1777, mode: `MaxEncodedLen`) /// Storage: `XcmpQueue::OutboundXcmpMessages` (r:0 w:1) /// Proof: `XcmpQueue::OutboundXcmpMessages` (`max_values`: None, `max_size`: Some(105506), added: 107981, mode: `MaxEncodedLen`) - /// The range of component `i` is `[128, 2048]`. - /// The range of component `i` is `[128, 2048]`. - fn receive_single_message_proof_with_dispatch(i: u32, ) -> Weight { + /// The range of component `n` is `[1, 16384]`. + /// The range of component `n` is `[1, 16384]`. + fn receive_single_n_bytes_message_proof_with_dispatch(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `813` // Estimated: `52645` - // Minimum execution time: 57_941_000 picoseconds. - Weight::from_parts(59_000_115, 0) + // Minimum execution time: 54_317_000 picoseconds. + Weight::from_parts(59_171_547, 0) .saturating_add(Weight::from_parts(0, 52645)) - // Standard Error: 46 - .saturating_add(Weight::from_parts(8_660, 0).saturating_mul(i.into())) + // Standard Error: 7 + .saturating_add(Weight::from_parts(7_566, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(10)) .saturating_add(T::DbWeight::get().writes(4)) } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_messages_rococo_to_westend.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_messages_rococo_to_westend.rs index e096c40d284e357a56df807a28bf6e05fbfedffc..9c05dae979daa0107e7754cc7107f80c3f753b7e 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_messages_rococo_to_westend.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_messages_rococo_to_westend.rs @@ -17,7 +17,7 @@ //! Autogenerated weights for `pallet_bridge_messages` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-06-26, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-07-03, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `runner-7wrmsoux-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-rococo-dev")`, DB CACHE: 1024 @@ -62,8 +62,8 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `658` // Estimated: `52645` - // Minimum execution time: 41_848_000 picoseconds. - Weight::from_parts(43_363_000, 0) + // Minimum execution time: 41_396_000 picoseconds. + Weight::from_parts(43_141_000, 0) .saturating_add(Weight::from_parts(0, 52645)) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(1)) @@ -78,13 +78,17 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< /// Proof: `BridgeWestendMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - fn receive_two_messages_proof() -> Weight { + /// The range of component `n` is `[1, 4076]`. + /// The range of component `n` is `[1, 4076]`. + fn receive_n_messages_proof(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `658` // Estimated: `52645` - // Minimum execution time: 52_674_000 picoseconds. - Weight::from_parts(55_080_000, 0) + // Minimum execution time: 41_095_000 picoseconds. + Weight::from_parts(42_030_000, 0) .saturating_add(Weight::from_parts(0, 52645)) + // Standard Error: 5_702 + .saturating_add(Weight::from_parts(11_627_951, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -102,8 +106,8 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `658` // Estimated: `52645` - // Minimum execution time: 46_892_000 picoseconds. - Weight::from_parts(49_441_000, 0) + // Minimum execution time: 45_912_000 picoseconds. + Weight::from_parts(47_564_000, 0) .saturating_add(Weight::from_parts(0, 52645)) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(1)) @@ -116,32 +120,20 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< /// Proof: `BridgeWestendParachains::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) /// Storage: `BridgeWestendMessages::InboundLanes` (r:1 w:1) /// Proof: `BridgeWestendMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) - fn receive_single_message_proof_1_kb() -> Weight { - // Proof Size summary in bytes: - // Measured: `626` - // Estimated: `52645` - // Minimum execution time: 41_262_000 picoseconds. - Weight::from_parts(42_734_000, 0) - .saturating_add(Weight::from_parts(0, 52645)) - .saturating_add(T::DbWeight::get().reads(4)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `BridgeWestendMessages::PalletOperatingMode` (r:1 w:0) - /// Proof: `BridgeWestendMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) - /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:0) - /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: Some(1282), added: 1777, mode: `MaxEncodedLen`) - /// Storage: `BridgeWestendParachains::ImportedParaHeads` (r:1 w:0) - /// Proof: `BridgeWestendParachains::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) - /// Storage: `BridgeWestendMessages::InboundLanes` (r:1 w:1) - /// Proof: `BridgeWestendMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) - fn receive_single_message_proof_16_kb() -> Weight { + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// The range of component `n` is `[1, 16384]`. + /// The range of component `n` is `[1, 16384]`. + fn receive_single_n_bytes_message_proof(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `626` + // Measured: `658` // Estimated: `52645` - // Minimum execution time: 75_654_000 picoseconds. - Weight::from_parts(76_866_000, 0) + // Minimum execution time: 39_175_000 picoseconds. + Weight::from_parts(41_674_095, 0) .saturating_add(Weight::from_parts(0, 52645)) - .saturating_add(T::DbWeight::get().reads(4)) + // Standard Error: 4 + .saturating_add(Weight::from_parts(2_305, 0).saturating_mul(n.into())) + .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `BridgeWestendMessages::PalletOperatingMode` (r:1 w:0) @@ -158,8 +150,8 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `501` // Estimated: `3966` - // Minimum execution time: 32_911_000 picoseconds. - Weight::from_parts(33_644_000, 0) + // Minimum execution time: 32_033_000 picoseconds. + Weight::from_parts(33_131_000, 0) .saturating_add(Weight::from_parts(0, 3966)) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(2)) @@ -178,8 +170,8 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `501` // Estimated: `3966` - // Minimum execution time: 32_830_000 picoseconds. - Weight::from_parts(33_675_000, 0) + // Minimum execution time: 32_153_000 picoseconds. + Weight::from_parts(33_126_000, 0) .saturating_add(Weight::from_parts(0, 3966)) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(2)) @@ -198,8 +190,8 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `501` // Estimated: `6086` - // Minimum execution time: 37_024_000 picoseconds. - Weight::from_parts(38_112_000, 0) + // Minimum execution time: 36_387_000 picoseconds. + Weight::from_parts(37_396_000, 0) .saturating_add(Weight::from_parts(0, 6086)) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(3)) @@ -226,17 +218,17 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< /// Proof: `ParachainSystem::RelevantMessagingState` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `XcmpQueue::OutboundXcmpMessages` (r:0 w:1) /// Proof: `XcmpQueue::OutboundXcmpMessages` (`max_values`: None, `max_size`: Some(105506), added: 107981, mode: `MaxEncodedLen`) - /// The range of component `i` is `[128, 2048]`. - /// The range of component `i` is `[128, 2048]`. - fn receive_single_message_proof_with_dispatch(i: u32, ) -> Weight { + /// The range of component `n` is `[1, 16384]`. + /// The range of component `n` is `[1, 16384]`. + fn receive_single_n_bytes_message_proof_with_dispatch(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `789` // Estimated: `52645` - // Minimum execution time: 60_653_000 picoseconds. - Weight::from_parts(62_358_212, 0) + // Minimum execution time: 56_562_000 picoseconds. + Weight::from_parts(61_452_871, 0) .saturating_add(Weight::from_parts(0, 52645)) - // Standard Error: 57 - .saturating_add(Weight::from_parts(8_660, 0).saturating_mul(i.into())) + // Standard Error: 9 + .saturating_add(Weight::from_parts(7_587, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(10)) .saturating_add(T::DbWeight::get().writes(4)) } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_parachains.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_parachains.rs index af216cd997c8160a06a60ecd979fda5a9003a095..8eb291ea14523b15d6c44b8ee72d637fcbe11166 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_parachains.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_parachains.rs @@ -17,7 +17,7 @@ //! Autogenerated weights for `pallet_bridge_parachains` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-06-26, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-07-03, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `runner-7wrmsoux-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-rococo-dev")`, DB CACHE: 1024 @@ -61,13 +61,15 @@ impl pallet_bridge_parachains::WeightInfo for WeightInf /// Storage: `BridgeWestendParachains::ImportedParaHeads` (r:0 w:1) /// Proof: `BridgeWestendParachains::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) /// The range of component `p` is `[1, 2]`. - fn submit_parachain_heads_with_n_parachains(_p: u32, ) -> Weight { + fn submit_parachain_heads_with_n_parachains(p: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `558` // Estimated: `2543` - // Minimum execution time: 35_711_000 picoseconds. - Weight::from_parts(37_344_514, 0) + // Minimum execution time: 34_889_000 picoseconds. + Weight::from_parts(36_100_759, 0) .saturating_add(Weight::from_parts(0, 2543)) + // Standard Error: 102_466 + .saturating_add(Weight::from_parts(178_820, 0).saturating_mul(p.into())) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -87,8 +89,8 @@ impl pallet_bridge_parachains::WeightInfo for WeightInf // Proof Size summary in bytes: // Measured: `558` // Estimated: `2543` - // Minimum execution time: 37_717_000 picoseconds. - Weight::from_parts(38_374_000, 0) + // Minimum execution time: 36_501_000 picoseconds. + Weight::from_parts(37_266_000, 0) .saturating_add(Weight::from_parts(0, 2543)) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(4)) @@ -109,8 +111,8 @@ impl pallet_bridge_parachains::WeightInfo for WeightInf // Proof Size summary in bytes: // Measured: `558` // Estimated: `2543` - // Minimum execution time: 70_203_000 picoseconds. - Weight::from_parts(70_994_000, 0) + // Minimum execution time: 66_059_000 picoseconds. + Weight::from_parts(67_139_000, 0) .saturating_add(Weight::from_parts(0, 2543)) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(4)) diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_relayers.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_relayers.rs index a66a7fb08aaf1ae33b2336364bc836253305bda1..f8bb983e80aa776ae7fe8c9a756935096956e7dd 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_relayers.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_bridge_relayers.rs @@ -17,7 +17,7 @@ //! Autogenerated weights for `pallet_bridge_relayers` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-06-26, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-07-03, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `runner-7wrmsoux-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-rococo-dev")`, DB CACHE: 1024 @@ -56,8 +56,8 @@ impl pallet_bridge_relayers::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `278` // Estimated: `3593` - // Minimum execution time: 43_669_000 picoseconds. - Weight::from_parts(44_907_000, 0) + // Minimum execution time: 44_224_000 picoseconds. + Weight::from_parts(44_905_000, 0) .saturating_add(Weight::from_parts(0, 3593)) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(2)) @@ -72,8 +72,8 @@ impl pallet_bridge_relayers::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `131` // Estimated: `4714` - // Minimum execution time: 24_024_000 picoseconds. - Weight::from_parts(24_582_000, 0) + // Minimum execution time: 23_902_000 picoseconds. + Weight::from_parts(24_702_000, 0) .saturating_add(Weight::from_parts(0, 4714)) .saturating_add(T::DbWeight::get().reads(3)) .saturating_add(T::DbWeight::get().writes(2)) @@ -86,8 +86,8 @@ impl pallet_bridge_relayers::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `231` // Estimated: `4714` - // Minimum execution time: 24_522_000 picoseconds. - Weight::from_parts(25_362_000, 0) + // Minimum execution time: 24_469_000 picoseconds. + Weight::from_parts(25_176_000, 0) .saturating_add(Weight::from_parts(0, 4714)) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(2)) @@ -102,8 +102,8 @@ impl pallet_bridge_relayers::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `334` // Estimated: `4714` - // Minimum execution time: 26_963_000 picoseconds. - Weight::from_parts(27_686_000, 0) + // Minimum execution time: 27_518_000 picoseconds. + Weight::from_parts(28_068_000, 0) .saturating_add(Weight::from_parts(0, 4714)) .saturating_add(T::DbWeight::get().reads(3)) .saturating_add(T::DbWeight::get().writes(3)) @@ -114,8 +114,8 @@ impl pallet_bridge_relayers::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `76` // Estimated: `3538` - // Minimum execution time: 5_401_000 picoseconds. - Weight::from_parts(5_563_000, 0) + // Minimum execution time: 5_484_000 picoseconds. + Weight::from_parts(5_718_000, 0) .saturating_add(Weight::from_parts(0, 3538)) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_message_queue.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_message_queue.rs index 2fcd573ceb277116bda67180da8e0701593ab453..b6fee47d1435162a3e24dd204b896eb849a7e146 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_message_queue.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/pallet_message_queue.rs @@ -43,7 +43,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weight functions for `pallet_message_queue`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/mod.rs index 4f5bae0fe597b88b1c23fa4ab806cec98bf7d746..b40cbfeeb8f2770bbc15e77d2a0a657b209a45ef 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/mod.rs @@ -17,11 +17,11 @@ mod pallet_xcm_benchmarks_fungible; mod pallet_xcm_benchmarks_generic; use crate::{xcm_config::MaxAssetsIntoHolding, Runtime}; +use alloc::vec::Vec; use codec::Encode; use frame_support::weights::Weight; use pallet_xcm_benchmarks_fungible::WeightInfo as XcmFungibleWeight; use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; -use sp_std::prelude::*; use xcm::{latest::prelude::*, DoubleEncoded}; trait WeighAssets { diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs index d7e8c41ff8ac41acfeb60f30774e8282939b6c1c..057dc4313510f79aa1daa1216141538ceb357012 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs @@ -43,7 +43,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weights for `pallet_xcm_benchmarks::fungible`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index abd84f8e89b07799758c36b002c30db742305927..9c58072d402c91a13f63795bf5b4184f80ab2c0b 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -16,10 +16,10 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::generic` //! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 +//! DATE: 2024-07-03, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-itmxxexx-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-7wrmsoux-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: Compiled, CHAIN: Some("bridge-hub-rococo-dev"), DB CACHE: 1024 // Executed Command: @@ -43,7 +43,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weights for `pallet_xcm_benchmarks::generic`. pub struct WeightInfo(PhantomData); @@ -68,8 +68,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `171` // Estimated: `6196` - // Minimum execution time: 61_813_000 picoseconds. - Weight::from_parts(62_996_000, 6196) + // Minimum execution time: 60_119_000 picoseconds. + Weight::from_parts(61_871_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -77,8 +77,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_044_000 picoseconds. - Weight::from_parts(2_112_000, 0) + // Minimum execution time: 998_000 picoseconds. + Weight::from_parts(1_038_000, 0) } // Storage: `PolkadotXcm::Queries` (r:1 w:0) // Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -86,58 +86,58 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `32` // Estimated: `3497` - // Minimum execution time: 7_472_000 picoseconds. - Weight::from_parts(7_723_000, 3497) + // Minimum execution time: 6_327_000 picoseconds. + Weight::from_parts(6_520_000, 3497) .saturating_add(T::DbWeight::get().reads(1)) } pub fn transact() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 8_414_000 picoseconds. - Weight::from_parts(8_765_000, 0) + // Minimum execution time: 6_783_000 picoseconds. + Weight::from_parts(7_117_000, 0) } pub fn refund_surplus() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_192_000 picoseconds. - Weight::from_parts(2_243_000, 0) + // Minimum execution time: 1_589_000 picoseconds. + Weight::from_parts(1_655_000, 0) } pub fn set_error_handler() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_866_000 picoseconds. - Weight::from_parts(1_931_000, 0) + // Minimum execution time: 1_013_000 picoseconds. + Weight::from_parts(1_045_000, 0) } pub fn set_appendix() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_847_000 picoseconds. - Weight::from_parts(1_921_000, 0) + // Minimum execution time: 1_005_000 picoseconds. + Weight::from_parts(1_044_000, 0) } pub fn clear_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_797_000 picoseconds. - Weight::from_parts(1_880_000, 0) + // Minimum execution time: 964_000 picoseconds. + Weight::from_parts(1_011_000, 0) } pub fn descend_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_458_000 picoseconds. - Weight::from_parts(2_523_000, 0) + // Minimum execution time: 1_005_000 picoseconds. + Weight::from_parts(1_027_000, 0) } pub fn clear_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_833_000 picoseconds. - Weight::from_parts(1_906_000, 0) + // Minimum execution time: 980_000 picoseconds. + Weight::from_parts(1_009_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -159,8 +159,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `171` // Estimated: `6196` - // Minimum execution time: 54_659_000 picoseconds. - Weight::from_parts(56_025_000, 6196) + // Minimum execution time: 56_726_000 picoseconds. + Weight::from_parts(59_300_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -170,8 +170,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `90` // Estimated: `3555` - // Minimum execution time: 10_953_000 picoseconds. - Weight::from_parts(11_220_000, 3555) + // Minimum execution time: 8_962_000 picoseconds. + Weight::from_parts(9_519_000, 3555) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -179,8 +179,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_834_000 picoseconds. - Weight::from_parts(1_892_000, 0) + // Minimum execution time: 999_000 picoseconds. + Weight::from_parts(1_035_000, 0) } // Storage: `PolkadotXcm::VersionNotifyTargets` (r:1 w:1) // Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -200,8 +200,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `38` // Estimated: `3503` - // Minimum execution time: 22_238_000 picoseconds. - Weight::from_parts(22_690_000, 3503) + // Minimum execution time: 20_313_000 picoseconds. + Weight::from_parts(21_000_000, 3503) .saturating_add(T::DbWeight::get().reads(7)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -211,44 +211,44 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_798_000 picoseconds. - Weight::from_parts(3_936_000, 0) + // Minimum execution time: 2_820_000 picoseconds. + Weight::from_parts(2_949_000, 0) .saturating_add(T::DbWeight::get().writes(1)) } pub fn burn_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_985_000 picoseconds. - Weight::from_parts(3_099_000, 0) + // Minimum execution time: 1_293_000 picoseconds. + Weight::from_parts(1_354_000, 0) } pub fn expect_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_955_000 picoseconds. - Weight::from_parts(2_050_000, 0) + // Minimum execution time: 1_076_000 picoseconds. + Weight::from_parts(1_114_000, 0) } pub fn expect_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_939_000 picoseconds. - Weight::from_parts(1_990_000, 0) + // Minimum execution time: 1_014_000 picoseconds. + Weight::from_parts(1_055_000, 0) } pub fn expect_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_841_000 picoseconds. - Weight::from_parts(1_900_000, 0) + // Minimum execution time: 979_000 picoseconds. + Weight::from_parts(1_019_000, 0) } pub fn expect_transact_status() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_081_000 picoseconds. - Weight::from_parts(2_145_000, 0) + // Minimum execution time: 1_161_000 picoseconds. + Weight::from_parts(1_208_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -270,8 +270,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `171` // Estimated: `6196` - // Minimum execution time: 59_600_000 picoseconds. - Weight::from_parts(61_572_000, 6196) + // Minimum execution time: 62_250_000 picoseconds. + Weight::from_parts(64_477_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -279,8 +279,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 4_390_000 picoseconds. - Weight::from_parts(4_517_000, 0) + // Minimum execution time: 4_286_000 picoseconds. + Weight::from_parts(4_476_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -302,8 +302,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `171` // Estimated: `6196` - // Minimum execution time: 53_864_000 picoseconds. - Weight::from_parts(55_527_000, 6196) + // Minimum execution time: 58_253_000 picoseconds. + Weight::from_parts(59_360_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -311,22 +311,22 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_879_000 picoseconds. - Weight::from_parts(1_947_000, 0) + // Minimum execution time: 1_026_000 picoseconds. + Weight::from_parts(1_065_000, 0) } pub fn set_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_827_000 picoseconds. - Weight::from_parts(1_900_000, 0) + // Minimum execution time: 993_000 picoseconds. + Weight::from_parts(1_015_000, 0) } pub fn clear_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_824_000 picoseconds. - Weight::from_parts(1_898_000, 0) + // Minimum execution time: 966_000 picoseconds. + Weight::from_parts(999_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -339,16 +339,16 @@ impl WeightInfo { // Storage: `BridgeWestendMessages::OutboundLanesCongestedSignals` (r:1 w:0) // Proof: `BridgeWestendMessages::OutboundLanesCongestedSignals` (`max_values`: Some(1), `max_size`: Some(21), added: 516, mode: `MaxEncodedLen`) // Storage: `BridgeWestendMessages::OutboundMessages` (r:0 w:1) - // Proof: `BridgeWestendMessages::OutboundMessages` (`max_values`: None, `max_size`: Some(2621472), added: 2623947, mode: `MaxEncodedLen`) + // Proof: `BridgeWestendMessages::OutboundMessages` (`max_values`: None, `max_size`: Some(65568), added: 68043, mode: `MaxEncodedLen`) /// The range of component `x` is `[1, 1000]`. pub fn export_message(x: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `190` // Estimated: `6130` - // Minimum execution time: 41_598_000 picoseconds. - Weight::from_parts(42_219_173, 6130) - // Standard Error: 426 - .saturating_add(Weight::from_parts(452_460, 0).saturating_mul(x.into())) + // Minimum execution time: 37_014_000 picoseconds. + Weight::from_parts(38_096_655, 6130) + // Standard Error: 61 + .saturating_add(Weight::from_parts(45_146, 0).saturating_mul(x.into())) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -356,14 +356,14 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_812_000 picoseconds. - Weight::from_parts(1_898_000, 0) + // Minimum execution time: 996_000 picoseconds. + Weight::from_parts(1_025_000, 0) } pub fn unpaid_execution() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_915_000 picoseconds. - Weight::from_parts(1_976_000, 0) + // Minimum execution time: 1_001_000 picoseconds. + Weight::from_parts(1_044_000, 0) } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs index a0d2e91dffd2e9240ad9364e18ef52a7b3cab3b1..2f11b4694e3bb0c0a625eebdb6a84ae64c87e1db 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs @@ -22,6 +22,7 @@ use super::{ use bp_messages::LaneId; use bp_relayers::{PayRewardFromAccount, RewardsAccountOwner, RewardsAccountParams}; use bp_runtime::ChainId; +use core::marker::PhantomData; use frame_support::{ parameter_types, traits::{tokens::imbalance::ResolveTo, ConstU32, Contains, Equals, Everything, Nothing}, @@ -41,7 +42,6 @@ use polkadot_runtime_common::xcm_sender::ExponentialPrice; use snowbridge_runtime_common::XcmExportFeeToSibling; use sp_core::Get; use sp_runtime::traits::AccountIdConversion; -use sp_std::marker::PhantomData; use testnet_parachains_constants::rococo::snowbridge::EthereumNetwork; use xcm::latest::prelude::*; use xcm_builder::{ @@ -49,10 +49,10 @@ use xcm_builder::{ AllowHrmpNotificationsFromRelayChain, AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, DenyReserveTransferToRelayChain, DenyThenTry, EnsureXcmOrigin, FrameTransactionalProcessor, FungibleAdapter, HandleFee, IsConcrete, ParentAsSuperuser, - ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, - SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, - TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, - XcmFeeToAccount, + ParentIsPreset, RelayChainAsNative, SendXcmFeeToAccount, SiblingParachainAsNative, + SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, + SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, + WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, }; use xcm_executor::{ traits::{FeeManager, FeeReason, FeeReason::Export, TransactAsset}, @@ -223,7 +223,7 @@ impl xcm_executor::Config for XcmConfig { Self::AssetTransactor, crate::EthereumOutboundQueue, >, - XcmFeeToAccount, + SendXcmFeeToAccount, ), >; type MessageExporter = ( @@ -354,24 +354,27 @@ impl< match asset.fun { Fungible(total_fee) => { let source_fee = total_fee / 2; - deposit_or_burn_fee::( + deposit_or_burn_fee::( Asset { id: asset.id.clone(), fun: Fungible(source_fee) }.into(), maybe_context, - source_para_account.clone(), + AccountId32 { network: None, id: source_para_account.clone().into() } + .into(), ); let dest_fee = total_fee - source_fee; - deposit_or_burn_fee::( + deposit_or_burn_fee::( Asset { id: asset.id, fun: Fungible(dest_fee) }.into(), maybe_context, - dest_para_account.clone(), + AccountId32 { network: None, id: dest_para_account.clone().into() } + .into(), ); }, NonFungible(_) => { - deposit_or_burn_fee::( + deposit_or_burn_fee::( asset.into(), maybe_context, - source_para_account.clone(), + AccountId32 { network: None, id: source_para_account.clone().into() } + .into(), ); }, } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/tests.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/tests.rs index b309232825db3aa964b2fa1a1d8d739f06ec3153..1d3d9e55f7eeb99bb46c23aba0bf9940515c69d4 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/tests.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/tests/tests.rs @@ -148,8 +148,7 @@ mod bridge_hub_westend_tests { use bridge_hub_test_utils::test_cases::from_parachain; use bridge_to_westend_config::{ BridgeHubWestendChainId, BridgeHubWestendLocation, WestendGlobalConsensusNetwork, - WithBridgeHubWestendMessageBridge, WithBridgeHubWestendMessagesInstance, - XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WESTEND, + WithBridgeHubWestendMessagesInstance, XCM_LANE_FOR_ASSET_HUB_ROCOCO_TO_ASSET_HUB_WESTEND, }; // Para id of sibling chain used in tests. @@ -162,7 +161,6 @@ mod bridge_hub_westend_tests { BridgeGrandpaWestendInstance, BridgeParachainWestendInstance, WithBridgeHubWestendMessagesInstance, - WithBridgeHubWestendMessageBridge, >; #[test] @@ -457,8 +455,8 @@ mod bridge_hub_bulletin_tests { use bridge_hub_test_utils::test_cases::from_grandpa_chain; use bridge_to_bulletin_config::{ RococoBulletinChainId, RococoBulletinGlobalConsensusNetwork, - RococoBulletinGlobalConsensusNetworkLocation, WithRococoBulletinMessageBridge, - WithRococoBulletinMessagesInstance, XCM_LANE_FOR_ROCOCO_PEOPLE_TO_ROCOCO_BULLETIN, + RococoBulletinGlobalConsensusNetworkLocation, WithRococoBulletinMessagesInstance, + XCM_LANE_FOR_ROCOCO_PEOPLE_TO_ROCOCO_BULLETIN, }; // Para id of sibling chain used in tests. @@ -470,7 +468,6 @@ mod bridge_hub_bulletin_tests { AllPalletsWithoutSystem, BridgeGrandpaRococoBulletinInstance, WithRococoBulletinMessagesInstance, - WithRococoBulletinMessageBridge, >; #[test] @@ -594,44 +591,4 @@ mod bridge_hub_bulletin_tests { construct_and_apply_extrinsic, ) } - - #[test] - pub fn can_calculate_fee_for_standalone_message_delivery_transaction() { - bridge_hub_test_utils::check_sane_fees_values( - "bp_bridge_hub_rococo::BridgeHubRococoBaseDeliveryFeeInRocs", - bp_bridge_hub_rococo::BridgeHubRococoBaseDeliveryFeeInRocs::get(), - || { - from_grandpa_chain::can_calculate_fee_for_standalone_message_delivery_transaction::< - RuntimeTestsAdapter, - >(collator_session_keys(), construct_and_estimate_extrinsic_fee) - }, - Perbill::from_percent(33), - None, /* we don't want lowering according to the Bulletin setup, because - * `from_grandpa_chain` is cheaper then `from_parachain_chain` */ - &format!( - "Estimate fee for `single message delivery` for runtime: {:?}", - ::Version::get() - ), - ) - } - - #[test] - pub fn can_calculate_fee_for_standalone_message_confirmation_transaction() { - bridge_hub_test_utils::check_sane_fees_values( - "bp_bridge_hub_rococo::BridgeHubRococoBaseConfirmationFeeInRocs", - bp_bridge_hub_rococo::BridgeHubRococoBaseConfirmationFeeInRocs::get(), - || { - from_grandpa_chain::can_calculate_fee_for_standalone_message_confirmation_transaction::< - RuntimeTestsAdapter, - >(collator_session_keys(), construct_and_estimate_extrinsic_fee) - }, - Perbill::from_percent(33), - None, /* we don't want lowering according to the Bulletin setup, because - * `from_grandpa_chain` is cheaper then `from_parachain_chain` */ - &format!( - "Estimate fee for `single message confirmation` for runtime: {:?}", - ::Version::get() - ), - ) - } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/Cargo.toml b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/Cargo.toml index c18d5036e06ad5772b24d4d53b8618bf054ef66a..e2671d3d606d1e993a38de2eeacf8a9675bb3b82 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/Cargo.toml +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/Cargo.toml @@ -89,7 +89,7 @@ bp-messages = { workspace = true } bp-parachains = { workspace = true } bp-polkadot-core = { workspace = true } bp-relayers = { workspace = true } -bp-runtime = { workspace = true } +bp-runtime = { features = ["test-helpers"], workspace = true } bp-rococo = { workspace = true } bp-westend = { workspace = true } pallet-bridge-grandpa = { workspace = true } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/bridge_to_rococo_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/bridge_to_rococo_config.rs index 425b53da30fc8a176fcddfe145fab66a41b60f8a..42d5ef3eebdb3030d49507fb8cc6d976cb041672 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/bridge_to_rococo_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/bridge_to_rococo_config.rs @@ -18,10 +18,12 @@ use crate::{ bridge_common_config::DeliveryRewardInBalance, weights, xcm_config::UniversalLocation, - AccountId, BridgeRococoMessages, PolkadotXcm, Runtime, RuntimeEvent, RuntimeOrigin, - XcmOverBridgeHubRococo, XcmRouter, + BridgeRococoMessages, PolkadotXcm, Runtime, RuntimeEvent, XcmOverBridgeHubRococo, XcmRouter, +}; +use bp_messages::{ + source_chain::FromBridgedChainMessagesDeliveryProof, + target_chain::FromBridgedChainMessagesProof, LaneId, }; -use bp_messages::LaneId; use bp_parachains::SingleParaStoredHeaderDataBuilder; use bp_runtime::Chain; use bridge_runtime_common::{ @@ -29,12 +31,6 @@ use bridge_runtime_common::{ ActualFeeRefund, RefundBridgedMessages, RefundSignedExtensionAdapter, RefundableMessagesLane, }, - messages, - messages::{ - source::{FromBridgedChainMessagesDeliveryProof, TargetHeaderChainAdapter}, - target::{FromBridgedChainMessagesProof, SourceHeaderChainAdapter}, - MessageBridge, ThisChainWithMessages, UnderlyingChainProvider, - }, messages_xcm_extension::{ SenderAndLane, XcmAsPlainPayload, XcmBlobHauler, XcmBlobHaulerAdapter, XcmBlobMessageDispatch, XcmVersionOfDestAndRemoteBridge, @@ -45,7 +41,6 @@ use frame_support::{ parameter_types, traits::{ConstU32, PalletInfoAccess}, }; -use sp_runtime::RuntimeDebug; use xcm::{ latest::prelude::*, prelude::{InteriorLocation, NetworkId}, @@ -59,11 +54,7 @@ parameter_types! { pub const RococoBridgeParachainPalletName: &'static str = "Paras"; pub const MaxRococoParaHeadDataSize: u32 = bp_rococo::MAX_NESTED_PARACHAIN_HEAD_DATA_SIZE; - pub const MaxUnrewardedRelayerEntriesAtInboundLane: bp_messages::MessageNonce = - bp_bridge_hub_westend::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX; - pub const MaxUnconfirmedMessagesAtInboundLane: bp_messages::MessageNonce = - bp_bridge_hub_westend::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX; - pub const BridgeHubRococoChainId: bp_runtime::ChainId = BridgeHubRococo::ID; + pub const BridgeHubRococoChainId: bp_runtime::ChainId = bp_bridge_hub_rococo::BridgeHubRococo::ID; pub BridgeWestendToRococoMessagesPalletInstance: InteriorLocation = [PalletInstance(::index() as u8)].into(); pub RococoGlobalConsensusNetwork: NetworkId = NetworkId::Rococo; pub RococoGlobalConsensusNetworkLocation: Location = Location::new( @@ -87,7 +78,7 @@ parameter_types! { ParentThen([Parachain(AssetHubWestendParaId::get().into())].into()).into(), XCM_LANE_FOR_ASSET_HUB_WESTEND_TO_ASSET_HUB_ROCOCO, ); - pub ActiveLanes: sp_std::vec::Vec<(SenderAndLane, (NetworkId, InteriorLocation))> = sp_std::vec![ + pub ActiveLanes: alloc::vec::Vec<(SenderAndLane, (NetworkId, InteriorLocation))> = alloc::vec![ ( FromAssetHubWestendToAssetHubRococoRoute::get(), (RococoGlobalConsensusNetwork::get(), [Parachain(AssetHubRococoParaId::get().into())].into()) @@ -107,8 +98,8 @@ parameter_types! { } pub const XCM_LANE_FOR_ASSET_HUB_WESTEND_TO_ASSET_HUB_ROCOCO: LaneId = LaneId([0, 0, 0, 2]); -fn build_congestion_message(is_congested: bool) -> sp_std::vec::Vec> { - sp_std::vec![ +fn build_congestion_message(is_congested: bool) -> alloc::vec::Vec> { + alloc::vec![ UnpaidExecution { weight_limit: Unlimited, check_origin: None }, Transact { origin_kind: OriginKind::Xcm, @@ -153,46 +144,6 @@ impl XcmBlobHauler for ToBridgeHubRococoXcmBlobHauler { /// On messages delivered callback. type OnMessagesDelivered = XcmBlobHaulerAdapter; -/// Messaging Bridge configuration for BridgeHubWestend -> BridgeHubRococo -pub struct WithBridgeHubRococoMessageBridge; -impl MessageBridge for WithBridgeHubRococoMessageBridge { - const BRIDGED_MESSAGES_PALLET_NAME: &'static str = - bp_bridge_hub_westend::WITH_BRIDGE_HUB_WESTEND_MESSAGES_PALLET_NAME; - type ThisChain = BridgeHubWestend; - type BridgedChain = BridgeHubRococo; - type BridgedHeaderChain = pallet_bridge_parachains::ParachainHeaders< - Runtime, - BridgeParachainRococoInstance, - bp_bridge_hub_rococo::BridgeHubRococo, - >; -} - -/// Maximal outbound payload size of BridgeHubWestend -> BridgeHubRococo messages. -type ToBridgeHubRococoMaximalOutboundPayloadSize = - messages::source::FromThisChainMaximalOutboundPayloadSize; - -/// BridgeHubRococo chain from message lane point of view. -#[derive(RuntimeDebug, Clone, Copy)] -pub struct BridgeHubRococo; - -impl UnderlyingChainProvider for BridgeHubRococo { - type Chain = bp_bridge_hub_rococo::BridgeHubRococo; -} - -impl messages::BridgedChainWithMessages for BridgeHubRococo {} - -/// BridgeHubWestend chain from message lane point of view. -#[derive(RuntimeDebug, Clone, Copy)] -pub struct BridgeHubWestend; - -impl UnderlyingChainProvider for BridgeHubWestend { - type Chain = bp_bridge_hub_westend::BridgeHubWestend; -} - -impl ThisChainWithMessages for BridgeHubWestend { - type RuntimeOrigin = RuntimeOrigin; -} - /// Signed extension that refunds relayers that are delivering messages from the Rococo parachain. pub type OnBridgeHubWestendRefundBridgeHubRococoMessages = RefundSignedExtensionAdapter< RefundBridgedMessages< @@ -237,26 +188,28 @@ pub type WithBridgeHubRococoMessagesInstance = pallet_bridge_messages::Instance1 impl pallet_bridge_messages::Config for Runtime { type RuntimeEvent = RuntimeEvent; type WeightInfo = weights::pallet_bridge_messages::WeightInfo; - type BridgedChainId = BridgeHubRococoChainId; + + type ThisChain = bp_bridge_hub_westend::BridgeHubWestend; + type BridgedChain = bp_bridge_hub_rococo::BridgeHubRococo; + type BridgedHeaderChain = pallet_bridge_parachains::ParachainHeaders< + Runtime, + BridgeParachainRococoInstance, + bp_bridge_hub_rococo::BridgeHubRococo, + >; + type ActiveOutboundLanes = ActiveOutboundLanesToBridgeHubRococo; - type MaxUnrewardedRelayerEntriesAtInboundLane = MaxUnrewardedRelayerEntriesAtInboundLane; - type MaxUnconfirmedMessagesAtInboundLane = MaxUnconfirmedMessagesAtInboundLane; - type MaximalOutboundPayloadSize = ToBridgeHubRococoMaximalOutboundPayloadSize; type OutboundPayload = XcmAsPlainPayload; type InboundPayload = XcmAsPlainPayload; - type InboundRelayer = AccountId; type DeliveryPayments = (); - type TargetHeaderChain = TargetHeaderChainAdapter; type DeliveryConfirmationPayments = pallet_bridge_relayers::DeliveryConfirmationPaymentsAdapter< Runtime, WithBridgeHubRococoMessagesInstance, DeliveryRewardInBalance, >; - type SourceHeaderChain = SourceHeaderChainAdapter; type MessageDispatch = XcmBlobMessageDispatch< FromRococoMessageBlobDispatcher, Self::WeightInfo, @@ -287,9 +240,8 @@ mod tests { assert_complete_bridge_types, extensions::refund_relayer_extension::RefundableParachain, integrity::{ - assert_complete_bridge_constants, check_message_lane_weights, - AssertBridgeMessagesPalletConstants, AssertBridgePalletNames, AssertChainConstants, - AssertCompleteBridgeConstants, + assert_complete_with_parachain_bridge_constants, check_message_lane_weights, + AssertChainConstants, AssertCompleteBridgeConstants, }, }; use parachains_common::Balance; @@ -331,35 +283,20 @@ mod tests { runtime: Runtime, with_bridged_chain_grandpa_instance: BridgeGrandpaRococoInstance, with_bridged_chain_messages_instance: WithBridgeHubRococoMessagesInstance, - bridge: WithBridgeHubRococoMessageBridge, - this_chain: bp_westend::Westend, - bridged_chain: bp_rococo::Rococo, + this_chain: bp_bridge_hub_westend::BridgeHubWestend, + bridged_chain: bp_bridge_hub_rococo::BridgeHubRococo, ); - assert_complete_bridge_constants::< + assert_complete_with_parachain_bridge_constants::< Runtime, BridgeGrandpaRococoInstance, WithBridgeHubRococoMessagesInstance, - WithBridgeHubRococoMessageBridge, + bp_rococo::Rococo, >(AssertCompleteBridgeConstants { this_chain_constants: AssertChainConstants { block_length: bp_bridge_hub_westend::BlockLength::get(), block_weights: bp_bridge_hub_westend::BlockWeightsForAsyncBacking::get(), }, - messages_pallet_constants: AssertBridgeMessagesPalletConstants { - max_unrewarded_relayers_in_bridged_confirmation_tx: - bp_bridge_hub_rococo::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX, - max_unconfirmed_messages_in_bridged_confirmation_tx: - bp_bridge_hub_rococo::MAX_UNCONFIRMED_MESSAGES_IN_CONFIRMATION_TX, - bridged_chain_id: BridgeHubRococo::ID, - }, - pallet_names: AssertBridgePalletNames { - with_this_chain_messages_pallet_name: - bp_bridge_hub_westend::WITH_BRIDGE_HUB_WESTEND_MESSAGES_PALLET_NAME, - with_bridged_chain_grandpa_pallet_name: bp_rococo::WITH_ROCOCO_GRANDPA_PALLET_NAME, - with_bridged_chain_messages_pallet_name: - bp_bridge_hub_rococo::WITH_BRIDGE_HUB_ROCOCO_MESSAGES_PALLET_NAME, - }, }); bridge_runtime_common::extensions::priority_calculator::per_relay_header::ensure_priority_boost_is_sane::< @@ -370,7 +307,7 @@ mod tests { bridge_runtime_common::extensions::priority_calculator::per_parachain_header::ensure_priority_boost_is_sane::< Runtime, - RefundableParachain, + RefundableParachain, PriorityBoostPerParachainHeader, >(FEE_BOOST_PER_PARACHAIN_HEADER); diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/lib.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/lib.rs index 05d6cdfd691e6220f7d539ec800eaff45dd19287..5d4c35d6610a0fb7a9b15e886750135c36533f5a 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/lib.rs @@ -32,6 +32,9 @@ pub mod bridge_to_rococo_config; mod weights; pub mod xcm_config; +extern crate alloc; + +use alloc::{vec, vec::Vec}; use bridge_runtime_common::extensions::{ check_obsolete_extension::{ CheckAndBoostBridgeGrandpaTransactions, CheckAndBoostBridgeParachainsTransactions, @@ -49,7 +52,6 @@ use sp_runtime::{ ApplyExtrinsicResult, }; -use sp_std::prelude::*; #[cfg(feature = "std")] use sp_version::NativeVersion; use sp_version::RuntimeVersion; @@ -612,7 +614,7 @@ impl_runtime_apis! { Runtime::metadata_at_version(version) } - fn metadata_versions() -> sp_std::vec::Vec { + fn metadata_versions() -> alloc::vec::Vec { Runtime::metadata_versions() } } @@ -886,7 +888,7 @@ impl_runtime_apis! { use frame_system_benchmarking::Pallet as SystemBench; impl frame_system_benchmarking::Config for Runtime { - fn setup_set_code_requirements(code: &sp_std::vec::Vec) -> Result<(), BenchmarkError> { + fn setup_set_code_requirements(code: &alloc::vec::Vec) -> Result<(), BenchmarkError> { ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32); Ok(()) } @@ -928,7 +930,7 @@ impl_runtime_apis! { } fn set_up_complex_asset_transfer( - ) -> Option<(Assets, u32, Location, Box)> { + ) -> Option<(Assets, u32, Location, alloc::boxed::Box)> { // BH only supports teleports to system parachain. // Relay/native token can be teleported between BH and Relay. let native_location = Parent.into(); @@ -1051,7 +1053,7 @@ impl_runtime_apis! { // save XCM version for remote bridge hub let _ = PolkadotXcm::force_xcm_version( RuntimeOrigin::root(), - Box::new(bridge_to_rococo_config::BridgeHubRococoLocation::get()), + alloc::boxed::Box::new(bridge_to_rococo_config::BridgeHubRococoLocation::get()), XCM_VERSION, ).map_err(|e| { log::error!( @@ -1118,7 +1120,7 @@ impl_runtime_apis! { prepare_message_proof_from_parachain::< Runtime, bridge_to_rococo_config::BridgeGrandpaRococoInstance, - bridge_to_rococo_config::WithBridgeHubRococoMessageBridge, + bridge_to_rococo_config::WithBridgeHubRococoMessagesInstance, >(params, generate_xcm_builder_bridge_message_sample([GlobalConsensus(Westend), Parachain(42)].into())) } @@ -1128,7 +1130,7 @@ impl_runtime_apis! { prepare_message_delivery_proof_from_parachain::< Runtime, bridge_to_rococo_config::BridgeGrandpaRococoInstance, - bridge_to_rococo_config::WithBridgeHubRococoMessageBridge, + bridge_to_rococo_config::WithBridgeHubRococoMessagesInstance, >(params) } @@ -1154,7 +1156,7 @@ impl_runtime_apis! { fn prepare_parachain_heads_proof( parachains: &[bp_polkadot_core::parachains::ParaId], parachain_head_size: u32, - proof_size: bp_runtime::StorageProofSize, + proof_params: bp_runtime::UnverifiedStorageProofParams, ) -> ( pallet_bridge_parachains::RelayBlockNumber, pallet_bridge_parachains::RelayBlockHash, @@ -1164,7 +1166,7 @@ impl_runtime_apis! { prepare_parachain_heads_proof::( parachains, parachain_head_size, - proof_size, + proof_params, ) } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/cumulus_pallet_parachain_system.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/cumulus_pallet_parachain_system.rs index dc480c391636a92aad6e303a515524b5ce7ff2b1..8fcd7b10d931b03ec4cd9cc063e0bacf8878ed16 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/cumulus_pallet_parachain_system.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/cumulus_pallet_parachain_system.rs @@ -47,7 +47,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weight functions for `cumulus_pallet_parachain_system`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_grandpa.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_grandpa.rs index a9ccb00b1a1c84376878781bb0a8f9acb2580b9e..fa7efc260489bead50ba63969571e018248ddefe 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_grandpa.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_grandpa.rs @@ -17,9 +17,9 @@ //! Autogenerated weights for `pallet_bridge_grandpa` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-06-26, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-07-11, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-7wrmsoux-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-yaoqqom-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-westend-dev")`, DB CACHE: 1024 // Executed Command: @@ -68,13 +68,13 @@ impl pallet_bridge_grandpa::WeightInfo for WeightInfo pallet_bridge_grandpa::WeightInfo for WeightInfo pallet_bridge_messages::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `522` // Estimated: `52645` - // Minimum execution time: 41_095_000 picoseconds. - Weight::from_parts(42_438_000, 0) + // Minimum execution time: 40_748_000 picoseconds. + Weight::from_parts(41_836_000, 0) .saturating_add(Weight::from_parts(0, 52645)) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(1)) @@ -78,13 +78,16 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< /// Proof: `BridgeRococoMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - fn receive_two_messages_proof() -> Weight { + /// The range of component `n` is `[1, 4076]`. + fn receive_n_messages_proof(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `522` // Estimated: `52645` - // Minimum execution time: 51_974_000 picoseconds. - Weight::from_parts(53_444_000, 0) + // Minimum execution time: 40_923_000 picoseconds. + Weight::from_parts(41_287_000, 0) .saturating_add(Weight::from_parts(0, 52645)) + // Standard Error: 9_774 + .saturating_add(Weight::from_parts(11_469_207, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -102,8 +105,8 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `522` // Estimated: `52645` - // Minimum execution time: 45_949_000 picoseconds. - Weight::from_parts(47_912_000, 0) + // Minimum execution time: 45_946_000 picoseconds. + Weight::from_parts(47_547_000, 0) .saturating_add(Weight::from_parts(0, 52645)) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(1)) @@ -116,32 +119,19 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< /// Proof: `BridgeRococoParachains::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) /// Storage: `BridgeRococoMessages::InboundLanes` (r:1 w:1) /// Proof: `BridgeRococoMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) - fn receive_single_message_proof_1_kb() -> Weight { - // Proof Size summary in bytes: - // Measured: `453` - // Estimated: `52645` - // Minimum execution time: 39_349_000 picoseconds. - Weight::from_parts(40_723_000, 0) - .saturating_add(Weight::from_parts(0, 52645)) - .saturating_add(T::DbWeight::get().reads(4)) - .saturating_add(T::DbWeight::get().writes(1)) - } - /// Storage: `BridgeRococoMessages::PalletOperatingMode` (r:1 w:0) - /// Proof: `BridgeRococoMessages::PalletOperatingMode` (`max_values`: Some(1), `max_size`: Some(2), added: 497, mode: `MaxEncodedLen`) - /// Storage: `XcmpQueue::OutboundXcmpStatus` (r:1 w:0) - /// Proof: `XcmpQueue::OutboundXcmpStatus` (`max_values`: Some(1), `max_size`: Some(1282), added: 1777, mode: `MaxEncodedLen`) - /// Storage: `BridgeRococoParachains::ImportedParaHeads` (r:1 w:0) - /// Proof: `BridgeRococoParachains::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) - /// Storage: `BridgeRococoMessages::InboundLanes` (r:1 w:1) - /// Proof: `BridgeRococoMessages::InboundLanes` (`max_values`: None, `max_size`: Some(49180), added: 51655, mode: `MaxEncodedLen`) - fn receive_single_message_proof_16_kb() -> Weight { + /// Storage: `ParachainInfo::ParachainId` (r:1 w:0) + /// Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) + /// The range of component `n` is `[1, 16384]`. + fn receive_single_n_bytes_message_proof(n: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `453` + // Measured: `522` // Estimated: `52645` - // Minimum execution time: 70_566_000 picoseconds. - Weight::from_parts(73_240_000, 0) + // Minimum execution time: 39_668_000 picoseconds. + Weight::from_parts(41_908_980, 0) .saturating_add(Weight::from_parts(0, 52645)) - .saturating_add(T::DbWeight::get().reads(4)) + // Standard Error: 11 + .saturating_add(Weight::from_parts(2_209, 0).saturating_mul(n.into())) + .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(1)) } /// Storage: `BridgeRococoMessages::PalletOperatingMode` (r:1 w:0) @@ -158,8 +148,8 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `357` // Estimated: `3822` - // Minimum execution time: 31_381_000 picoseconds. - Weight::from_parts(31_980_000, 0) + // Minimum execution time: 30_544_000 picoseconds. + Weight::from_parts(31_171_000, 0) .saturating_add(Weight::from_parts(0, 3822)) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(2)) @@ -178,8 +168,8 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `357` // Estimated: `3822` - // Minimum execution time: 31_479_000 picoseconds. - Weight::from_parts(32_220_000, 0) + // Minimum execution time: 30_593_000 picoseconds. + Weight::from_parts(31_261_000, 0) .saturating_add(Weight::from_parts(0, 3822)) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(2)) @@ -198,8 +188,8 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `357` // Estimated: `6086` - // Minimum execution time: 35_724_000 picoseconds. - Weight::from_parts(36_460_000, 0) + // Minimum execution time: 34_682_000 picoseconds. + Weight::from_parts(35_277_000, 0) .saturating_add(Weight::from_parts(0, 6086)) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(3)) @@ -226,16 +216,16 @@ impl pallet_bridge_messages::WeightInfo for WeightInfo< /// Proof: `ParachainSystem::RelevantMessagingState` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) /// Storage: `XcmpQueue::OutboundXcmpMessages` (r:0 w:1) /// Proof: `XcmpQueue::OutboundXcmpMessages` (`max_values`: None, `max_size`: Some(105506), added: 107981, mode: `MaxEncodedLen`) - /// The range of component `i` is `[128, 2048]`. - fn receive_single_message_proof_with_dispatch(i: u32, ) -> Weight { + /// The range of component `n` is `[1, 16384]`. + fn receive_single_n_bytes_message_proof_with_dispatch(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `653` // Estimated: `52645` - // Minimum execution time: 60_476_000 picoseconds. - Weight::from_parts(61_832_928, 0) + // Minimum execution time: 56_465_000 picoseconds. + Weight::from_parts(61_575_775, 0) .saturating_add(Weight::from_parts(0, 52645)) - // Standard Error: 73 - .saturating_add(Weight::from_parts(7_951, 0).saturating_mul(i.into())) + // Standard Error: 15 + .saturating_add(Weight::from_parts(7_197, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(10)) .saturating_add(T::DbWeight::get().writes(4)) } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_parachains.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_parachains.rs index 82764a48b48092dd1b263db33110d45897ee2cef..b4748f1417059e91e482c650f5046ef09b76a7af 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_parachains.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_parachains.rs @@ -17,7 +17,7 @@ //! Autogenerated weights for `pallet_bridge_parachains` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-06-26, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-07-03, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `runner-7wrmsoux-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-westend-dev")`, DB CACHE: 1024 @@ -61,15 +61,13 @@ impl pallet_bridge_parachains::WeightInfo for WeightInf /// Storage: `BridgeRococoParachains::ImportedParaHeads` (r:0 w:1) /// Proof: `BridgeRococoParachains::ImportedParaHeads` (`max_values`: Some(64), `max_size`: Some(196), added: 1186, mode: `MaxEncodedLen`) /// The range of component `p` is `[1, 2]`. - fn submit_parachain_heads_with_n_parachains(p: u32, ) -> Weight { + fn submit_parachain_heads_with_n_parachains(_p: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `315` // Estimated: `2543` - // Minimum execution time: 34_408_000 picoseconds. - Weight::from_parts(35_467_881, 0) + // Minimum execution time: 34_177_000 picoseconds. + Weight::from_parts(35_662_308, 0) .saturating_add(Weight::from_parts(0, 2543)) - // Standard Error: 100_493 - .saturating_add(Weight::from_parts(63_859, 0).saturating_mul(p.into())) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -89,8 +87,8 @@ impl pallet_bridge_parachains::WeightInfo for WeightInf // Proof Size summary in bytes: // Measured: `315` // Estimated: `2543` - // Minimum execution time: 36_125_000 picoseconds. - Weight::from_parts(36_703_000, 0) + // Minimum execution time: 35_975_000 picoseconds. + Weight::from_parts(36_510_000, 0) .saturating_add(Weight::from_parts(0, 2543)) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(4)) @@ -111,8 +109,8 @@ impl pallet_bridge_parachains::WeightInfo for WeightInf // Proof Size summary in bytes: // Measured: `315` // Estimated: `2543` - // Minimum execution time: 64_697_000 picoseconds. - Weight::from_parts(68_015_000, 0) + // Minimum execution time: 62_837_000 picoseconds. + Weight::from_parts(63_562_000, 0) .saturating_add(Weight::from_parts(0, 2543)) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(4)) diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_relayers.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_relayers.rs index 7e3f3f3d7230afbc71188e529956011d9181f463..60d81dc3082a86ea3cea3951d4ed59cf9be8ed56 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_relayers.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_bridge_relayers.rs @@ -17,7 +17,7 @@ //! Autogenerated weights for `pallet_bridge_relayers` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-06-26, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-07-03, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `runner-7wrmsoux-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("bridge-hub-westend-dev")`, DB CACHE: 1024 @@ -56,8 +56,8 @@ impl pallet_bridge_relayers::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `207` // Estimated: `3593` - // Minimum execution time: 43_291_000 picoseconds. - Weight::from_parts(44_118_000, 0) + // Minimum execution time: 43_132_000 picoseconds. + Weight::from_parts(43_923_000, 0) .saturating_add(Weight::from_parts(0, 3593)) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(2)) @@ -72,8 +72,8 @@ impl pallet_bridge_relayers::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `61` // Estimated: `4714` - // Minimum execution time: 23_286_000 picoseconds. - Weight::from_parts(23_823_000, 0) + // Minimum execution time: 22_765_000 picoseconds. + Weight::from_parts(23_576_000, 0) .saturating_add(Weight::from_parts(0, 4714)) .saturating_add(T::DbWeight::get().reads(3)) .saturating_add(T::DbWeight::get().writes(2)) @@ -86,8 +86,8 @@ impl pallet_bridge_relayers::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `160` // Estimated: `4714` - // Minimum execution time: 24_145_000 picoseconds. - Weight::from_parts(24_541_000, 0) + // Minimum execution time: 24_013_000 picoseconds. + Weight::from_parts(24_460_000, 0) .saturating_add(Weight::from_parts(0, 4714)) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(2)) @@ -102,8 +102,8 @@ impl pallet_bridge_relayers::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `263` // Estimated: `4714` - // Minimum execution time: 26_707_000 picoseconds. - Weight::from_parts(27_266_000, 0) + // Minimum execution time: 26_946_000 picoseconds. + Weight::from_parts(27_485_000, 0) .saturating_add(Weight::from_parts(0, 4714)) .saturating_add(T::DbWeight::get().reads(3)) .saturating_add(T::DbWeight::get().writes(3)) @@ -114,8 +114,8 @@ impl pallet_bridge_relayers::WeightInfo for WeightInfo< // Proof Size summary in bytes: // Measured: `6` // Estimated: `3538` - // Minimum execution time: 4_850_000 picoseconds. - Weight::from_parts(5_116_000, 0) + // Minimum execution time: 4_658_000 picoseconds. + Weight::from_parts(4_902_000, 0) .saturating_add(Weight::from_parts(0, 3538)) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_message_queue.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_message_queue.rs index 2fcd573ceb277116bda67180da8e0701593ab453..b6fee47d1435162a3e24dd204b896eb849a7e146 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_message_queue.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/pallet_message_queue.rs @@ -43,7 +43,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weight functions for `pallet_message_queue`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/mod.rs index e8950678b40fd7b4e7afca8c998bc20c619e65ef..3961cc6d5cdd63a67b5ea4cbc805448e01f98939 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/mod.rs @@ -18,11 +18,11 @@ mod pallet_xcm_benchmarks_fungible; mod pallet_xcm_benchmarks_generic; use crate::{xcm_config::MaxAssetsIntoHolding, Runtime}; +use alloc::vec::Vec; use codec::Encode; use frame_support::weights::Weight; use pallet_xcm_benchmarks_fungible::WeightInfo as XcmFungibleWeight; use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; -use sp_std::prelude::*; use xcm::{latest::prelude::*, DoubleEncoded}; trait WeighAssets { diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs index 295abd481d7dc6decd39032bf6b0972cdc7ccf20..4310b24564758c4a3d95d27f047dd8988a43395c 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs @@ -43,7 +43,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weights for `pallet_xcm_benchmarks::fungible`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index 9281a880c7e1266d65d29436ca88e51e896c0363..ba434ff29629ff89a92d6ea663e5fcf8184d102f 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -16,10 +16,10 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::generic` //! -//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-12-12, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 +//! DATE: 2024-07-03, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-itmxxexx-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-7wrmsoux-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: Compiled, CHAIN: Some("bridge-hub-westend-dev"), DB CACHE: 1024 // Executed Command: @@ -43,7 +43,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weights for `pallet_xcm_benchmarks::generic`. pub struct WeightInfo(PhantomData); @@ -68,8 +68,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `208` // Estimated: `6196` - // Minimum execution time: 61_577_000 picoseconds. - Weight::from_parts(63_216_000, 6196) + // Minimum execution time: 58_505_000 picoseconds. + Weight::from_parts(60_437_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -77,8 +77,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_019_000 picoseconds. - Weight::from_parts(2_146_000, 0) + // Minimum execution time: 510_000 picoseconds. + Weight::from_parts(569_000, 0) } // Storage: `PolkadotXcm::Queries` (r:1 w:0) // Proof: `PolkadotXcm::Queries` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -86,58 +86,58 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `32` // Estimated: `3497` - // Minimum execution time: 7_473_000 picoseconds. - Weight::from_parts(7_784_000, 3497) + // Minimum execution time: 5_597_000 picoseconds. + Weight::from_parts(5_884_000, 3497) .saturating_add(T::DbWeight::get().reads(1)) } pub fn transact() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 8_385_000 picoseconds. - Weight::from_parts(8_768_000, 0) + // Minimum execution time: 5_320_000 picoseconds. + Weight::from_parts(5_594_000, 0) } pub fn refund_surplus() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_181_000 picoseconds. - Weight::from_parts(2_304_000, 0) + // Minimum execution time: 1_164_000 picoseconds. + Weight::from_parts(1_227_000, 0) } pub fn set_error_handler() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_858_000 picoseconds. - Weight::from_parts(1_919_000, 0) + // Minimum execution time: 528_000 picoseconds. + Weight::from_parts(586_000, 0) } pub fn set_appendix() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_855_000 picoseconds. - Weight::from_parts(1_979_000, 0) + // Minimum execution time: 509_000 picoseconds. + Weight::from_parts(571_000, 0) } pub fn clear_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_823_000 picoseconds. - Weight::from_parts(1_890_000, 0) + // Minimum execution time: 511_000 picoseconds. + Weight::from_parts(546_000, 0) } pub fn descend_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_407_000 picoseconds. - Weight::from_parts(2_507_000, 0) + // Minimum execution time: 560_000 picoseconds. + Weight::from_parts(600_000, 0) } pub fn clear_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_838_000 picoseconds. - Weight::from_parts(1_894_000, 0) + // Minimum execution time: 514_000 picoseconds. + Weight::from_parts(558_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -159,8 +159,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `208` // Estimated: `6196` - // Minimum execution time: 54_847_000 picoseconds. - Weight::from_parts(55_742_000, 6196) + // Minimum execution time: 55_871_000 picoseconds. + Weight::from_parts(57_172_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -170,8 +170,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `90` // Estimated: `3555` - // Minimum execution time: 10_614_000 picoseconds. - Weight::from_parts(11_344_000, 3555) + // Minimum execution time: 8_487_000 picoseconds. + Weight::from_parts(8_800_000, 3555) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -179,8 +179,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_826_000 picoseconds. - Weight::from_parts(1_899_000, 0) + // Minimum execution time: 528_000 picoseconds. + Weight::from_parts(569_000, 0) } // Storage: `PolkadotXcm::VersionNotifyTargets` (r:1 w:1) // Proof: `PolkadotXcm::VersionNotifyTargets` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -200,8 +200,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `38` // Estimated: `3503` - // Minimum execution time: 22_312_000 picoseconds. - Weight::from_parts(22_607_000, 3503) + // Minimum execution time: 19_803_000 picoseconds. + Weight::from_parts(20_368_000, 3503) .saturating_add(T::DbWeight::get().reads(7)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -211,44 +211,44 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_728_000 picoseconds. - Weight::from_parts(3_914_000, 0) + // Minimum execution time: 2_185_000 picoseconds. + Weight::from_parts(2_332_000, 0) .saturating_add(T::DbWeight::get().writes(1)) } pub fn burn_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 3_054_000 picoseconds. - Weight::from_parts(3_140_000, 0) + // Minimum execution time: 822_000 picoseconds. + Weight::from_parts(928_000, 0) } pub fn expect_asset() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_996_000 picoseconds. - Weight::from_parts(2_148_000, 0) + // Minimum execution time: 603_000 picoseconds. + Weight::from_parts(643_000, 0) } pub fn expect_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_008_000 picoseconds. - Weight::from_parts(2_077_000, 0) + // Minimum execution time: 503_000 picoseconds. + Weight::from_parts(580_000, 0) } pub fn expect_error() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_837_000 picoseconds. - Weight::from_parts(1_913_000, 0) + // Minimum execution time: 534_000 picoseconds. + Weight::from_parts(577_000, 0) } pub fn expect_transact_status() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 2_052_000 picoseconds. - Weight::from_parts(2_120_000, 0) + // Minimum execution time: 694_000 picoseconds. + Weight::from_parts(745_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -270,8 +270,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `208` // Estimated: `6196` - // Minimum execution time: 58_725_000 picoseconds. - Weight::from_parts(60_271_000, 6196) + // Minimum execution time: 61_083_000 picoseconds. + Weight::from_parts(62_214_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -279,8 +279,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 4_570_000 picoseconds. - Weight::from_parts(4_707_000, 0) + // Minimum execution time: 3_261_000 picoseconds. + Weight::from_parts(3_483_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -302,8 +302,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `208` // Estimated: `6196` - // Minimum execution time: 54_903_000 picoseconds. - Weight::from_parts(55_711_000, 6196) + // Minimum execution time: 56_270_000 picoseconds. + Weight::from_parts(57_443_000, 6196) .saturating_add(T::DbWeight::get().reads(9)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -311,22 +311,22 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_872_000 picoseconds. - Weight::from_parts(1_938_000, 0) + // Minimum execution time: 565_000 picoseconds. + Weight::from_parts(628_000, 0) } pub fn set_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_836_000 picoseconds. - Weight::from_parts(1_903_000, 0) + // Minimum execution time: 496_000 picoseconds. + Weight::from_parts(563_000, 0) } pub fn clear_topic() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_847_000 picoseconds. - Weight::from_parts(1_900_000, 0) + // Minimum execution time: 518_000 picoseconds. + Weight::from_parts(557_000, 0) } // Storage: `ParachainInfo::ParachainId` (r:1 w:0) // Proof: `ParachainInfo::ParachainId` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) @@ -339,16 +339,16 @@ impl WeightInfo { // Storage: `BridgeRococoMessages::OutboundLanesCongestedSignals` (r:1 w:0) // Proof: `BridgeRococoMessages::OutboundLanesCongestedSignals` (`max_values`: Some(1), `max_size`: Some(21), added: 516, mode: `MaxEncodedLen`) // Storage: `BridgeRococoMessages::OutboundMessages` (r:0 w:1) - // Proof: `BridgeRococoMessages::OutboundMessages` (`max_values`: None, `max_size`: Some(2621472), added: 2623947, mode: `MaxEncodedLen`) + // Proof: `BridgeRococoMessages::OutboundMessages` (`max_values`: None, `max_size`: Some(65568), added: 68043, mode: `MaxEncodedLen`) /// The range of component `x` is `[1, 1000]`. pub fn export_message(x: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `225` // Estimated: `6165` - // Minimum execution time: 41_750_000 picoseconds. - Weight::from_parts(43_496_915, 6165) - // Standard Error: 623 - .saturating_add(Weight::from_parts(457_907, 0).saturating_mul(x.into())) + // Minimum execution time: 36_288_000 picoseconds. + Weight::from_parts(37_707_751, 6165) + // Standard Error: 124 + .saturating_add(Weight::from_parts(51_290, 0).saturating_mul(x.into())) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -356,14 +356,14 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_826_000 picoseconds. - Weight::from_parts(1_911_000, 0) + // Minimum execution time: 485_000 picoseconds. + Weight::from_parts(540_000, 0) } pub fn unpaid_execution() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_967_000 picoseconds. - Weight::from_parts(2_096_000, 0) + // Minimum execution time: 542_000 picoseconds. + Weight::from_parts(586_000, 0) } } diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs index c2ca8e47f2a61cf6d66613daa205caddafe192b0..7f94b76a005bf933d7dead5309a2fc0bdec5a4e8 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/src/xcm_config.rs @@ -42,10 +42,10 @@ use xcm_builder::{ AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, DenyReserveTransferToRelayChain, DenyThenTry, EnsureXcmOrigin, FrameTransactionalProcessor, FungibleAdapter, IsConcrete, ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, - SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, - SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, - UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, - XcmFeeManagerFromComponents, XcmFeeToAccount, + SendXcmFeeToAccount, SiblingParachainAsNative, SiblingParachainConvertsVia, + SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, + TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, + XcmFeeManagerFromComponents, }; use xcm_executor::XcmExecutor; @@ -195,7 +195,7 @@ impl xcm_executor::Config for XcmConfig { type MaxAssetsIntoHolding = MaxAssetsIntoHolding; type FeeManager = XcmFeeManagerFromComponents< WaivedLocations, - XcmFeeToAccount, + SendXcmFeeToAccount, >; type MessageExporter = (crate::bridge_to_rococo_config::ToBridgeHubRococoHaulBlobExporter,); type UniversalAliases = Nothing; diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/tests/tests.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/tests/tests.rs index 836594140b2328081ff6c0de8cac40ea82dfb6f7..763271fd7af0e69ae8de2aa4fe507083f5d09d9e 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/tests/tests.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/tests/tests.rs @@ -28,8 +28,8 @@ use bridge_hub_westend_runtime::{ }; use bridge_to_rococo_config::{ BridgeGrandpaRococoInstance, BridgeHubRococoChainId, BridgeHubRococoLocation, - BridgeParachainRococoInstance, WithBridgeHubRococoMessageBridge, - WithBridgeHubRococoMessagesInstance, XCM_LANE_FOR_ASSET_HUB_WESTEND_TO_ASSET_HUB_ROCOCO, + BridgeParachainRococoInstance, WithBridgeHubRococoMessagesInstance, + XCM_LANE_FOR_ASSET_HUB_WESTEND_TO_ASSET_HUB_ROCOCO, }; use codec::{Decode, Encode}; use frame_support::{dispatch::GetDispatchInfo, parameter_types, traits::ConstU8}; @@ -53,7 +53,6 @@ type RuntimeTestsAdapter = from_parachain::WithRemoteParachainHelperAdapter< BridgeGrandpaRococoInstance, BridgeParachainRococoInstance, WithBridgeHubRococoMessagesInstance, - WithBridgeHubRococoMessageBridge, >; parameter_types! { diff --git a/cumulus/parachains/runtimes/bridge-hubs/common/Cargo.toml b/cumulus/parachains/runtimes/bridge-hubs/common/Cargo.toml index fd0eed1c05a1a65e9f5c41d1880f57b708e85119..3ae43075000ba2ccd34c9efe1edfc91681201944 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/common/Cargo.toml +++ b/cumulus/parachains/runtimes/bridge-hubs/common/Cargo.toml @@ -10,7 +10,6 @@ license = "Apache-2.0" codec = { features = ["derive"], workspace = true } scale-info = { features = ["derive"], workspace = true } frame-support = { workspace = true } -sp-std = { workspace = true } sp-core = { workspace = true } sp-runtime = { workspace = true } cumulus-primitives-core = { workspace = true } @@ -29,7 +28,6 @@ std = [ "snowbridge-core/std", "sp-core/std", "sp-runtime/std", - "sp-std/std", "xcm/std", ] diff --git a/cumulus/parachains/runtimes/bridge-hubs/common/src/message_queue.rs b/cumulus/parachains/runtimes/bridge-hubs/common/src/message_queue.rs index c1bba65b0abc3c6949f94e9e904a5649f1a9d285..5f91897262f4b8eed44a2da7ad945945dda67cc4 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/common/src/message_queue.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/common/src/message_queue.rs @@ -14,6 +14,7 @@ // limitations under the License. //! Runtime configuration for MessageQueue pallet use codec::{Decode, Encode, MaxEncodedLen}; +use core::marker::PhantomData; use cumulus_primitives_core::{AggregateMessageOrigin as CumulusAggregateMessageOrigin, ParaId}; use frame_support::{ traits::{ProcessMessage, ProcessMessageError, QueueFootprint, QueuePausedQuery}, @@ -22,7 +23,6 @@ use frame_support::{ use pallet_message_queue::OnQueueChanged; use scale_info::TypeInfo; use snowbridge_core::ChannelId; -use sp_std::{marker::PhantomData, prelude::*}; use xcm::v4::{Junction, Location}; /// The aggregate origin of an inbound message. diff --git a/cumulus/parachains/runtimes/bridge-hubs/test-utils/Cargo.toml b/cumulus/parachains/runtimes/bridge-hubs/test-utils/Cargo.toml index 90af4dd8f3ed80708cde59e66aed557042e3da39..44a8646142d6c38d265c0b9cd518b1b7ddd192e3 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/test-utils/Cargo.toml +++ b/cumulus/parachains/runtimes/bridge-hubs/test-utils/Cargo.toml @@ -21,7 +21,6 @@ sp-core = { workspace = true } sp-io = { workspace = true } sp-keyring = { workspace = true, default-features = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } sp-tracing = { workspace = true, default-features = true } pallet-balances = { workspace = true } pallet-utility = { workspace = true } @@ -48,7 +47,7 @@ bp-runtime = { workspace = true } bp-test-utils = { workspace = true } pallet-bridge-grandpa = { workspace = true } pallet-bridge-parachains = { workspace = true } -pallet-bridge-messages = { workspace = true } +pallet-bridge-messages = { features = ["test-helpers"], workspace = true } pallet-bridge-relayers = { workspace = true } bridge-runtime-common = { workspace = true } @@ -81,7 +80,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", "xcm-builder/std", "xcm-executor/std", "xcm/std", diff --git a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/lib.rs b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/lib.rs index 1874f38de2df17e85c1f49723271d090e962eb70..0b3463f0df974dcc9ce46c1d811b363d5011bbb4 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/lib.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/lib.rs @@ -19,6 +19,8 @@ pub mod test_cases; pub mod test_data; +extern crate alloc; + pub use bp_test_utils::test_header; pub use parachains_runtimes_test_utils::*; use sp_runtime::Perbill; diff --git a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/from_grandpa_chain.rs b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/from_grandpa_chain.rs index bfa2f0f50f94ca3ba2f663f9646be3165dd48220..d6dfa93731a7d3fe17203330e86486093ca5d7ed 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/from_grandpa_chain.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/from_grandpa_chain.rs @@ -22,22 +22,14 @@ use crate::{ test_data, }; +use alloc::{boxed::Box, vec}; use bp_header_chain::ChainWithGrandpa; -use bp_messages::{ - source_chain::TargetHeaderChain, target_chain::SourceHeaderChain, LaneId, - UnrewardedRelayersState, -}; +use bp_messages::{LaneId, UnrewardedRelayersState}; use bp_relayers::{RewardsAccountOwner, RewardsAccountParams}; -use bp_runtime::{HashOf, UnderlyingChainOf}; -use bridge_runtime_common::{ - messages::{ - source::FromBridgedChainMessagesDeliveryProof, target::FromBridgedChainMessagesProof, - BridgedChain as MessageBridgedChain, MessageBridge, ThisChain as MessageThisChain, - }, - messages_xcm_extension::XcmAsPlainPayload, -}; +use bridge_runtime_common::messages_xcm_extension::XcmAsPlainPayload; use frame_support::traits::{OnFinalize, OnInitialize}; use frame_system::pallet_prelude::BlockNumberFor; +use pallet_bridge_messages::{BridgedChainOf, ThisChainOf}; use parachains_runtimes_test_utils::{ AccountIdOf, BasicParachainRuntime, CollatorSessionKeys, RuntimeCallOf, SlotDurations, }; @@ -53,13 +45,10 @@ pub trait WithRemoteGrandpaChainHelper { /// This chain runtime. type Runtime: BasicParachainRuntime + cumulus_pallet_xcmp_queue::Config - + BridgeGrandpaConfig< - Self::GPI, - BridgedChain = UnderlyingChainOf>, - > + BridgeMessagesConfig< + + BridgeGrandpaConfig> + + BridgeMessagesConfig< Self::MPI, InboundPayload = XcmAsPlainPayload, - InboundRelayer = bp_runtime::AccountIdOf>, OutboundPayload = XcmAsPlainPayload, > + pallet_bridge_relayers::Config; /// All pallets of this chain, excluding system pallet. @@ -69,38 +58,33 @@ pub trait WithRemoteGrandpaChainHelper { type GPI: 'static; /// Instance of the `pallet-bridge-messages`, used to bridge with remote GRANDPA chain. type MPI: 'static; - /// Messages bridge definition. - type MB: MessageBridge; } /// Adapter struct that implements [`WithRemoteGrandpaChainHelper`]. -pub struct WithRemoteGrandpaChainHelperAdapter( - sp_std::marker::PhantomData<(Runtime, AllPalletsWithoutSystem, GPI, MPI, MB)>, +pub struct WithRemoteGrandpaChainHelperAdapter( + core::marker::PhantomData<(Runtime, AllPalletsWithoutSystem, GPI, MPI)>, ); -impl WithRemoteGrandpaChainHelper - for WithRemoteGrandpaChainHelperAdapter +impl WithRemoteGrandpaChainHelper + for WithRemoteGrandpaChainHelperAdapter where Runtime: BasicParachainRuntime + cumulus_pallet_xcmp_queue::Config - + BridgeGrandpaConfig>> + + BridgeGrandpaConfig> + BridgeMessagesConfig< MPI, InboundPayload = XcmAsPlainPayload, - InboundRelayer = bp_runtime::AccountIdOf>, OutboundPayload = XcmAsPlainPayload, > + pallet_bridge_relayers::Config, AllPalletsWithoutSystem: OnInitialize> + OnFinalize>, GPI: 'static, MPI: 'static, - MB: MessageBridge, { type Runtime = Runtime; type AllPalletsWithoutSystem = AllPalletsWithoutSystem; type GPI = GPI; type MPI = MPI; - type MB = MB; } /// Test-case makes sure that Runtime can dispatch XCM messages submitted by relayer, @@ -124,13 +108,7 @@ pub fn relayed_incoming_message_works( AccountIdOf: From, RuntimeCallOf: From> + From>, - UnderlyingChainOf>: ChainWithGrandpa, - >::SourceHeaderChain: - SourceHeaderChain< - MessagesProof = FromBridgedChainMessagesProof< - HashOf>, - >, - >, + BridgedChainOf: ChainWithGrandpa, { helpers::relayed_incoming_message_works::< RuntimeHelper::Runtime, @@ -161,7 +139,8 @@ pub fn relayed_incoming_message_works( // to be submitted by relayer to this chain. let (relay_chain_header, grandpa_justification, message_proof) = test_data::from_grandpa_chain::make_complex_relayer_delivery_proofs::< - RuntimeHelper::MB, + BridgedChainOf, + ThisChainOf, (), >( lane_id, @@ -186,7 +165,7 @@ pub fn relayed_incoming_message_works( ( BridgeMessagesCall::::receive_messages_proof { relayer_id_at_bridged_chain, - proof: message_proof, + proof: Box::new(message_proof), messages_count: 1, dispatch_weight: Weight::from_parts(1000000000, 0), }.into(), @@ -233,13 +212,7 @@ pub fn free_relay_extrinsic_works( AccountIdOf: From, RuntimeCallOf: From> + From>, - UnderlyingChainOf>: ChainWithGrandpa, - >::SourceHeaderChain: - SourceHeaderChain< - MessagesProof = FromBridgedChainMessagesProof< - HashOf>, - >, - >, + BridgedChainOf: ChainWithGrandpa, { // ensure that the runtime allows free header submissions let free_headers_interval = ( // to be submitted by relayer to this chain. let (relay_chain_header, grandpa_justification, message_proof) = test_data::from_grandpa_chain::make_complex_relayer_delivery_proofs::< - RuntimeHelper::MB, + BridgedChainOf, + ThisChainOf, (), >( lane_id, @@ -322,7 +296,7 @@ pub fn free_relay_extrinsic_works( ( BridgeMessagesCall::::receive_messages_proof { relayer_id_at_bridged_chain, - proof: message_proof, + proof: Box::new(message_proof), messages_count: 1, dispatch_weight: Weight::from_parts(1000000000, 0), }.into(), @@ -370,13 +344,7 @@ pub fn complex_relay_extrinsic_works( RuntimeCallOf: From> + From> + From>, - UnderlyingChainOf>: ChainWithGrandpa, - >::SourceHeaderChain: - SourceHeaderChain< - MessagesProof = FromBridgedChainMessagesProof< - HashOf>, - >, - >, + BridgedChainOf: ChainWithGrandpa, { helpers::relayed_incoming_message_works::< RuntimeHelper::Runtime, @@ -407,7 +375,8 @@ pub fn complex_relay_extrinsic_works( // to be submitted by relayer to this chain. let (relay_chain_header, grandpa_justification, message_proof) = test_data::from_grandpa_chain::make_complex_relayer_delivery_proofs::< - RuntimeHelper::MB, + BridgedChainOf, + ThisChainOf, (), >( lane_id, @@ -428,7 +397,7 @@ pub fn complex_relay_extrinsic_works( }.into(), BridgeMessagesCall::::receive_messages_proof { relayer_id_at_bridged_chain, - proof: message_proof, + proof: Box::new(message_proof), messages_count: 1, dispatch_weight: Weight::from_parts(1000000000, 0), }.into(), @@ -470,13 +439,7 @@ where pallet_utility::Config>, RuntimeCallOf: From> + From>, - UnderlyingChainOf>: ChainWithGrandpa, - >::SourceHeaderChain: - SourceHeaderChain< - MessagesProof = FromBridgedChainMessagesProof< - HashOf>, - >, - >, + BridgedChainOf: ChainWithGrandpa, { run_test::(collator_session_key, 1000, vec![], || { // generate bridged relay chain finality, parachain heads and message proofs, @@ -487,7 +450,8 @@ where // the message additionally let (relay_chain_header, grandpa_justification, message_proof) = test_data::from_grandpa_chain::make_complex_relayer_delivery_proofs::< - RuntimeHelper::MB, + BridgedChainOf, + ThisChainOf, (), >( LaneId::default(), @@ -526,19 +490,11 @@ where AccountIdOf: From, RuntimeHelper::Runtime: pallet_utility::Config>, - MessageThisChain: + ThisChainOf: bp_runtime::Chain>, RuntimeCallOf: From> + From>, - UnderlyingChainOf>: ChainWithGrandpa, - >::TargetHeaderChain: - TargetHeaderChain< - XcmAsPlainPayload, - AccountIdOf, - MessagesDeliveryProof = FromBridgedChainMessagesDeliveryProof< - HashOf>>, - >, - >, + BridgedChainOf: ChainWithGrandpa, { run_test::(collator_session_key, 1000, vec![], || { // generate bridged relay chain finality, parachain heads and message proofs, @@ -550,7 +506,8 @@ where }; let (relay_chain_header, grandpa_justification, message_delivery_proof) = test_data::from_grandpa_chain::make_complex_relayer_confirmation_proofs::< - RuntimeHelper::MB, + BridgedChainOf, + ThisChainOf, (), >( LaneId::default(), @@ -587,13 +544,7 @@ where RuntimeHelper: WithRemoteGrandpaChainHelper, RuntimeCallOf: From>, - UnderlyingChainOf>: ChainWithGrandpa, - >::SourceHeaderChain: - SourceHeaderChain< - MessagesProof = FromBridgedChainMessagesProof< - HashOf>, - >, - >, + BridgedChainOf: ChainWithGrandpa, { run_test::(collator_session_key, 1000, vec![], || { // generate bridged relay chain finality, parachain heads and message proofs, @@ -604,7 +555,8 @@ where // the message additionally let (_, _, message_proof) = test_data::from_grandpa_chain::make_complex_relayer_delivery_proofs::< - RuntimeHelper::MB, + BridgedChainOf, + ThisChainOf, (), >( LaneId::default(), @@ -639,19 +591,11 @@ pub fn can_calculate_fee_for_standalone_message_confirmation_transaction: From, - MessageThisChain: + ThisChainOf: bp_runtime::Chain>, RuntimeCallOf: From>, - UnderlyingChainOf>: ChainWithGrandpa, - >::TargetHeaderChain: - TargetHeaderChain< - XcmAsPlainPayload, - AccountIdOf, - MessagesDeliveryProof = FromBridgedChainMessagesDeliveryProof< - HashOf>>, - >, - >, + BridgedChainOf: ChainWithGrandpa, { run_test::(collator_session_key, 1000, vec![], || { // generate bridged relay chain finality, parachain heads and message proofs, @@ -663,7 +607,8 @@ where }; let (_, _, message_delivery_proof) = test_data::from_grandpa_chain::make_complex_relayer_confirmation_proofs::< - RuntimeHelper::MB, + BridgedChainOf, + ThisChainOf, (), >( LaneId::default(), diff --git a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/from_parachain.rs b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/from_parachain.rs index 12ab382d9e0f6518afb93f118199170acb5f8cc6..728b4e76b1055dd215d68a91ecb01704850d38a4 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/from_parachain.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/from_parachain.rs @@ -22,23 +22,16 @@ use crate::{ test_data, }; +use alloc::{boxed::Box, vec}; use bp_header_chain::ChainWithGrandpa; -use bp_messages::{ - source_chain::TargetHeaderChain, target_chain::SourceHeaderChain, LaneId, - UnrewardedRelayersState, -}; +use bp_messages::{LaneId, UnrewardedRelayersState}; use bp_polkadot_core::parachains::ParaHash; use bp_relayers::{RewardsAccountOwner, RewardsAccountParams}; -use bp_runtime::{HashOf, Parachain, UnderlyingChainOf}; -use bridge_runtime_common::{ - messages::{ - source::FromBridgedChainMessagesDeliveryProof, target::FromBridgedChainMessagesProof, - BridgedChain as MessageBridgedChain, MessageBridge, ThisChain as MessageThisChain, - }, - messages_xcm_extension::XcmAsPlainPayload, -}; +use bp_runtime::{Chain, Parachain}; +use bridge_runtime_common::messages_xcm_extension::XcmAsPlainPayload; use frame_support::traits::{OnFinalize, OnInitialize}; use frame_system::pallet_prelude::BlockNumberFor; +use pallet_bridge_messages::{BridgedChainOf, ThisChainOf}; use parachains_runtimes_test_utils::{ AccountIdOf, BasicParachainRuntime, CollatorSessionKeys, RuntimeCallOf, SlotDurations, }; @@ -59,7 +52,6 @@ pub trait WithRemoteParachainHelper { + BridgeMessagesConfig< Self::MPI, InboundPayload = XcmAsPlainPayload, - InboundRelayer = bp_runtime::AccountIdOf>, OutboundPayload = XcmAsPlainPayload, > + pallet_bridge_relayers::Config; /// All pallets of this chain, excluding system pallet. @@ -71,17 +63,15 @@ pub trait WithRemoteParachainHelper { type PPI: 'static; /// Instance of the `pallet-bridge-messages`, used to bridge with remote parachain. type MPI: 'static; - /// Messages bridge definition. - type MB: MessageBridge; } /// Adapter struct that implements `WithRemoteParachainHelper`. -pub struct WithRemoteParachainHelperAdapter( - sp_std::marker::PhantomData<(Runtime, AllPalletsWithoutSystem, GPI, PPI, MPI, MB)>, +pub struct WithRemoteParachainHelperAdapter( + core::marker::PhantomData<(Runtime, AllPalletsWithoutSystem, GPI, PPI, MPI)>, ); -impl WithRemoteParachainHelper - for WithRemoteParachainHelperAdapter +impl WithRemoteParachainHelper + for WithRemoteParachainHelperAdapter where Runtime: BasicParachainRuntime + cumulus_pallet_xcmp_queue::Config @@ -90,7 +80,6 @@ where + BridgeMessagesConfig< MPI, InboundPayload = XcmAsPlainPayload, - InboundRelayer = bp_runtime::AccountIdOf>, OutboundPayload = XcmAsPlainPayload, > + pallet_bridge_relayers::Config, AllPalletsWithoutSystem: @@ -98,14 +87,13 @@ where GPI: 'static, PPI: 'static, MPI: 'static, - MB: MessageBridge, + // MB: MessageBridge, { type Runtime = Runtime; type AllPalletsWithoutSystem = AllPalletsWithoutSystem; type GPI = GPI; type PPI = PPI; type MPI = MPI; - type MB = MB; } /// Test-case makes sure that Runtime can dispatch XCM messages submitted by relayer, @@ -131,16 +119,9 @@ pub fn relayed_incoming_message_works( RuntimeCallOf: From> + From> + From>, - UnderlyingChainOf>: - bp_runtime::Chain + Parachain, + BridgedChainOf: Chain + Parachain, >::BridgedChain: bp_runtime::Chain + ChainWithGrandpa, - >::SourceHeaderChain: - SourceHeaderChain< - MessagesProof = FromBridgedChainMessagesProof< - HashOf>, - >, - >, { helpers::relayed_incoming_message_works::< RuntimeHelper::Runtime, @@ -179,7 +160,8 @@ pub fn relayed_incoming_message_works( message_proof, ) = test_data::from_parachain::make_complex_relayer_delivery_proofs::< >::BridgedChain, - RuntimeHelper::MB, + BridgedChainOf, + ThisChainOf, (), >( lane_id, @@ -219,7 +201,7 @@ pub fn relayed_incoming_message_works( ( BridgeMessagesCall::::receive_messages_proof { relayer_id_at_bridged_chain, - proof: message_proof, + proof: Box::new(message_proof), messages_count: 1, dispatch_weight: Weight::from_parts(1000000000, 0), }.into(), @@ -268,16 +250,9 @@ pub fn free_relay_extrinsic_works( RuntimeCallOf: From> + From> + From>, - UnderlyingChainOf>: - bp_runtime::Chain + Parachain, + BridgedChainOf: Chain + Parachain, >::BridgedChain: bp_runtime::Chain + ChainWithGrandpa, - >::SourceHeaderChain: - SourceHeaderChain< - MessagesProof = FromBridgedChainMessagesProof< - HashOf>, - >, - >, { // ensure that the runtime allows free header submissions let free_headers_interval = ( message_proof, ) = test_data::from_parachain::make_complex_relayer_delivery_proofs::< >::BridgedChain, - RuntimeHelper::MB, + BridgedChainOf, + ThisChainOf, (), >( lane_id, @@ -390,7 +366,7 @@ pub fn free_relay_extrinsic_works( ( BridgeMessagesCall::::receive_messages_proof { relayer_id_at_bridged_chain, - proof: message_proof, + proof: Box::new(message_proof), messages_count: 1, dispatch_weight: Weight::from_parts(1000000000, 0), }.into(), @@ -440,16 +416,9 @@ pub fn complex_relay_extrinsic_works( + From> + From> + From>, - UnderlyingChainOf>: - bp_runtime::Chain + Parachain, + BridgedChainOf: Chain + Parachain, >::BridgedChain: bp_runtime::Chain + ChainWithGrandpa, - >::SourceHeaderChain: - SourceHeaderChain< - MessagesProof = FromBridgedChainMessagesProof< - HashOf>, - >, - >, { helpers::relayed_incoming_message_works::< RuntimeHelper::Runtime, @@ -488,7 +457,8 @@ pub fn complex_relay_extrinsic_works( message_proof, ) = test_data::from_parachain::make_complex_relayer_delivery_proofs::< >::BridgedChain, - RuntimeHelper::MB, + BridgedChainOf, + ThisChainOf, (), >( lane_id, @@ -518,7 +488,7 @@ pub fn complex_relay_extrinsic_works( }.into(), BridgeMessagesCall::::receive_messages_proof { relayer_id_at_bridged_chain, - proof: message_proof, + proof: Box::new(message_proof), messages_count: 1, dispatch_weight: Weight::from_parts(1000000000, 0), }.into(), @@ -565,16 +535,9 @@ where RuntimeCallOf: From> + From> + From>, - UnderlyingChainOf>: - bp_runtime::Chain + Parachain, + BridgedChainOf: Chain + Parachain, >::BridgedChain: bp_runtime::Chain + ChainWithGrandpa, - >::SourceHeaderChain: - SourceHeaderChain< - MessagesProof = FromBridgedChainMessagesProof< - HashOf>, - >, - >, { run_test::(collator_session_key, 1000, vec![], || { // generate bridged relay chain finality, parachain heads and message proofs, @@ -592,7 +555,8 @@ where message_proof, ) = test_data::from_parachain::make_complex_relayer_delivery_proofs::< >::BridgedChain, - RuntimeHelper::MB, + BridgedChainOf, + ThisChainOf, (), >( LaneId::default(), @@ -612,7 +576,6 @@ where RuntimeHelper::GPI, RuntimeHelper::PPI, RuntimeHelper::MPI, - _, >( relay_chain_header, grandpa_justification, @@ -637,23 +600,14 @@ where AccountIdOf: From, RuntimeHelper::Runtime: pallet_utility::Config>, - MessageThisChain: - bp_runtime::Chain>, + ThisChainOf: + Chain>, RuntimeCallOf: From> + From> + From>, - UnderlyingChainOf>: - bp_runtime::Chain + Parachain, + BridgedChainOf: Chain + Parachain, >::BridgedChain: bp_runtime::Chain + ChainWithGrandpa, - >::TargetHeaderChain: - TargetHeaderChain< - XcmAsPlainPayload, - AccountIdOf, - MessagesDeliveryProof = FromBridgedChainMessagesDeliveryProof< - HashOf>>, - >, - >, { run_test::(collator_session_key, 1000, vec![], || { // generate bridged relay chain finality, parachain heads and message proofs, @@ -672,7 +626,8 @@ where message_delivery_proof, ) = test_data::from_parachain::make_complex_relayer_confirmation_proofs::< >::BridgedChain, - RuntimeHelper::MB, + BridgedChainOf, + ThisChainOf, (), >( LaneId::default(), @@ -714,16 +669,9 @@ where RuntimeHelper: WithRemoteParachainHelper, RuntimeCallOf: From>, - UnderlyingChainOf>: - bp_runtime::Chain + Parachain, + BridgedChainOf: Chain + Parachain, >::BridgedChain: bp_runtime::Chain + ChainWithGrandpa, - >::SourceHeaderChain: - SourceHeaderChain< - MessagesProof = FromBridgedChainMessagesProof< - HashOf>, - >, - >, { run_test::(collator_session_key, 1000, vec![], || { // generate bridged relay chain finality, parachain heads and message proofs, @@ -741,7 +689,8 @@ where message_proof, ) = test_data::from_parachain::make_complex_relayer_delivery_proofs::< >::BridgedChain, - RuntimeHelper::MB, + BridgedChainOf, + ThisChainOf, (), >( LaneId::default(), @@ -757,7 +706,6 @@ where let call = test_data::from_parachain::make_standalone_relayer_delivery_call::< RuntimeHelper::Runtime, RuntimeHelper::MPI, - _, >( message_proof, helpers::relayer_id_at_bridged_chain::(), @@ -778,22 +726,13 @@ pub fn can_calculate_fee_for_standalone_message_confirmation_transaction: From, - MessageThisChain: - bp_runtime::Chain>, + ThisChainOf: + Chain>, RuntimeCallOf: From>, - UnderlyingChainOf>: - bp_runtime::Chain + Parachain, + BridgedChainOf: Chain + Parachain, >::BridgedChain: bp_runtime::Chain + ChainWithGrandpa, - >::TargetHeaderChain: - TargetHeaderChain< - XcmAsPlainPayload, - AccountIdOf, - MessagesDeliveryProof = FromBridgedChainMessagesDeliveryProof< - HashOf>>, - >, - >, { run_test::(collator_session_key, 1000, vec![], || { // generate bridged relay chain finality, parachain heads and message proofs, @@ -806,7 +745,8 @@ where let (_, _, _, _, _, message_delivery_proof) = test_data::from_parachain::make_complex_relayer_confirmation_proofs::< >::BridgedChain, - RuntimeHelper::MB, + BridgedChainOf, + ThisChainOf, (), >( LaneId::default(), diff --git a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/helpers.rs b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/helpers.rs index 0ce049cd1c4630c55c244afbc8a72213cb83d6b9..78b8a170f0d4b0bb6ed0aa71a5cac0dceeca96fe 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/helpers.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_cases/helpers.rs @@ -23,12 +23,14 @@ use bp_messages::{LaneId, MessageNonce}; use bp_polkadot_core::parachains::{ParaHash, ParaId}; use bp_relayers::RewardsAccountParams; use codec::Decode; +use core::marker::PhantomData; use frame_support::{ assert_ok, traits::{OnFinalize, OnInitialize, PalletInfoAccess}, }; use frame_system::pallet_prelude::BlockNumberFor; use pallet_bridge_grandpa::{BridgedBlockHash, BridgedHeader}; +use pallet_bridge_messages::BridgedChainOf; use parachains_common::AccountId; use parachains_runtimes_test_utils::{ mock_open_hrmp_channel, AccountIdOf, CollatorSessionKeys, RuntimeCallOf, SlotDurations, @@ -36,7 +38,6 @@ use parachains_runtimes_test_utils::{ use sp_core::Get; use sp_keyring::AccountKeyring::*; use sp_runtime::{traits::TrailingZeroInput, AccountId32}; -use sp_std::marker::PhantomData; use xcm::latest::prelude::*; /// Verify that the transaction has succeeded. @@ -240,10 +241,12 @@ pub(crate) fn initialize_bridge_grandpa_pallet( pub type CallsAndVerifiers = Vec<(RuntimeCallOf, Box)>; +pub type InboundRelayerId = bp_runtime::AccountIdOf>; + /// Returns relayer id at the bridged chain. pub fn relayer_id_at_bridged_chain, MPI>( -) -> Runtime::InboundRelayer { - Runtime::InboundRelayer::decode(&mut TrailingZeroInput::zeroes()).unwrap() +) -> InboundRelayerId { + Decode::decode(&mut TrailingZeroInput::zeroes()).unwrap() } /// Test-case makes sure that Runtime can dispatch XCM messages submitted by relayer, @@ -260,7 +263,7 @@ pub fn relayed_incoming_message_works( ) -> sp_runtime::DispatchOutcome, prepare_message_proof_import: impl FnOnce( Runtime::AccountId, - Runtime::InboundRelayer, + InboundRelayerId, InteriorLocation, MessageNonce, Xcm<()>, @@ -287,7 +290,7 @@ pub fn relayed_incoming_message_works( // value here is tricky - there are several transaction payment pallets and we don't // want to introduce additional bounds and traits here just for that, so let's just // select some presumably large value - sp_std::cmp::max::(Runtime::ExistentialDeposit::get(), 1u32.into()) * + core::cmp::max::(Runtime::ExistentialDeposit::get(), 1u32.into()) * 100_000_000u32.into(), )], || { diff --git a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_data/from_grandpa_chain.rs b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_data/from_grandpa_chain.rs index e5d5e7cac96ba14f6abfdae792908352f40d3e31..c61a31e5454ba75429929a0c7b879f6baaa72e15 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_data/from_grandpa_chain.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_data/from_grandpa_chain.rs @@ -19,30 +19,29 @@ use crate::test_data::prepare_inbound_xcm; use bp_messages::{ - source_chain::TargetHeaderChain, target_chain::SourceHeaderChain, LaneId, MessageNonce, + source_chain::FromBridgedChainMessagesDeliveryProof, + target_chain::FromBridgedChainMessagesProof, ChainWithMessages, LaneId, MessageNonce, UnrewardedRelayersState, }; -use bp_runtime::{AccountIdOf, BlockNumberOf, HeaderOf, StorageProofSize, UnderlyingChainOf}; +use bp_runtime::{AccountIdOf, BlockNumberOf, Chain, HeaderOf, UnverifiedStorageProofParams}; use bp_test_utils::make_default_justification; -use bridge_runtime_common::{ - messages::{ - source::FromBridgedChainMessagesDeliveryProof, target::FromBridgedChainMessagesProof, - BridgedChain as MessageBridgedChain, MessageBridge, ThisChain as MessageThisChain, - }, - messages_generation::{ - encode_all_messages, encode_lane_data, prepare_message_delivery_storage_proof, - prepare_messages_storage_proof, - }, - messages_xcm_extension::XcmAsPlainPayload, -}; +use bridge_runtime_common::messages_xcm_extension::XcmAsPlainPayload; use codec::Encode; use pallet_bridge_grandpa::{BridgedChain, BridgedHeader}; use sp_runtime::traits::Header as HeaderT; use xcm::latest::prelude::*; +use crate::test_cases::helpers::InboundRelayerId; use bp_header_chain::{justification::GrandpaJustification, ChainWithGrandpa}; use bp_messages::{DeliveredMessages, InboundLaneData, UnrewardedRelayer}; use bp_runtime::HashOf; +use pallet_bridge_messages::{ + messages_generation::{ + encode_all_messages, encode_lane_data, prepare_message_delivery_storage_proof, + prepare_messages_storage_proof, + }, + BridgedChainOf, +}; use sp_runtime::DigestItem; /// Prepare a batch call with bridged GRANDPA finality and message proof. @@ -50,22 +49,17 @@ pub fn make_complex_relayer_delivery_batch( bridged_header: BridgedHeader, bridged_justification: GrandpaJustification>, message_proof: FromBridgedChainMessagesProof>>, - relayer_id_at_bridged_chain: AccountIdOf>, + relayer_id_at_bridged_chain: InboundRelayerId, ) -> pallet_utility::Call where Runtime: pallet_bridge_grandpa::Config - + pallet_bridge_messages::Config< - MPI, - InboundPayload = XcmAsPlainPayload, - InboundRelayer = AccountIdOf>, - > + pallet_utility::Config, + + pallet_bridge_messages::Config + + pallet_utility::Config, GPI: 'static, MPI: 'static, - >::SourceHeaderChain: SourceHeaderChain< - MessagesProof = FromBridgedChainMessagesProof>>, - >, ::RuntimeCall: From> + From>, + BridgedChainOf: Chain>>, { let submit_grandpa = pallet_bridge_grandpa::Call::::submit_finality_proof { finality_target: Box::new(bridged_header), @@ -73,7 +67,7 @@ where }; let submit_message = pallet_bridge_messages::Call::::receive_messages_proof { relayer_id_at_bridged_chain, - proof: message_proof, + proof: Box::new(message_proof), messages_count: 1, dispatch_weight: Weight::from_parts(1000000000, 0), }; @@ -97,15 +91,9 @@ where + pallet_utility::Config, GPI: 'static, MPI: 'static, - >::TargetHeaderChain: TargetHeaderChain< - XcmAsPlainPayload, - Runtime::AccountId, - MessagesDeliveryProof = FromBridgedChainMessagesDeliveryProof< - HashOf>, - >, - >, ::RuntimeCall: From> + From>, + BridgedChainOf: Chain>>, { let submit_grandpa = pallet_bridge_grandpa::Call::::submit_finality_proof { finality_target: Box::new(bridged_header), @@ -124,24 +112,18 @@ where /// Prepare a call with message proof. pub fn make_standalone_relayer_delivery_call( message_proof: FromBridgedChainMessagesProof>>, - relayer_id_at_bridged_chain: AccountIdOf>, + relayer_id_at_bridged_chain: InboundRelayerId, ) -> Runtime::RuntimeCall where Runtime: pallet_bridge_grandpa::Config - + pallet_bridge_messages::Config< - MPI, - InboundPayload = XcmAsPlainPayload, - InboundRelayer = AccountIdOf>, - >, + + pallet_bridge_messages::Config, MPI: 'static, - >::SourceHeaderChain: SourceHeaderChain< - MessagesProof = FromBridgedChainMessagesProof>>, - >, Runtime::RuntimeCall: From>, + BridgedChainOf: Chain>>, { pallet_bridge_messages::Call::::receive_messages_proof { relayer_id_at_bridged_chain, - proof: message_proof, + proof: Box::new(message_proof), messages_count: 1, dispatch_weight: Weight::from_parts(1000000000, 0), } @@ -159,14 +141,8 @@ where Runtime: pallet_bridge_grandpa::Config + pallet_bridge_messages::Config, MPI: 'static, - >::TargetHeaderChain: TargetHeaderChain< - XcmAsPlainPayload, - Runtime::AccountId, - MessagesDeliveryProof = FromBridgedChainMessagesDeliveryProof< - HashOf>, - >, - >, Runtime::RuntimeCall: From>, + BridgedChainOf: Chain>>, { pallet_bridge_messages::Call::::receive_messages_delivery_proof { proof: message_delivery_proof, @@ -176,39 +152,47 @@ where } /// Prepare storage proofs of messages, stored at the (bridged) source GRANDPA chain. -pub fn make_complex_relayer_delivery_proofs( +pub fn make_complex_relayer_delivery_proofs< + BridgedChain, + ThisChainWithMessages, + InnerXcmRuntimeCall, +>( lane_id: LaneId, xcm_message: Xcm, message_nonce: MessageNonce, message_destination: Junctions, - header_number: BlockNumberOf>, + header_number: BlockNumberOf, is_minimal_call: bool, ) -> ( - HeaderOf>, - GrandpaJustification>>, - FromBridgedChainMessagesProof>>, + HeaderOf, + GrandpaJustification>, + FromBridgedChainMessagesProof>, ) where - MB: MessageBridge, - MessageBridgedChain: Send + Sync + 'static, - UnderlyingChainOf>: ChainWithGrandpa, + BridgedChain: ChainWithGrandpa, + ThisChainWithMessages: ChainWithMessages, { + // prepare message let message_payload = prepare_inbound_xcm(xcm_message, message_destination); - let message_size = StorageProofSize::Minimal(message_payload.len() as u32); - // prepare para storage proof containing message - let (state_root, storage_proof) = prepare_messages_storage_proof::( - lane_id, - message_nonce..=message_nonce, - None, - message_size, - message_payload, - encode_all_messages, - encode_lane_data, - ); + // prepare storage proof containing message + let (state_root, storage_proof) = + prepare_messages_storage_proof::( + lane_id, + message_nonce..=message_nonce, + None, + UnverifiedStorageProofParams::from_db_size(message_payload.len() as u32), + |_| message_payload.clone(), + encode_all_messages, + encode_lane_data, + false, + false, + ); - let (header, justification) = make_complex_bridged_grandpa_header_proof::< - MessageBridgedChain, - >(state_root, header_number, is_minimal_call); + let (header, justification) = make_complex_bridged_grandpa_header_proof::( + state_root, + header_number, + is_minimal_call, + ); let message_proof = FromBridgedChainMessagesProof { bridged_header_hash: header.hash(), @@ -222,44 +206,44 @@ where } /// Prepare storage proofs of message confirmations, stored at the (bridged) target GRANDPA chain. -pub fn make_complex_relayer_confirmation_proofs( +pub fn make_complex_relayer_confirmation_proofs< + BridgedChain, + ThisChainWithMessages, + InnerXcmRuntimeCall, +>( lane_id: LaneId, - header_number: BlockNumberOf>, - relayer_id_at_this_chain: AccountIdOf>, + header_number: BlockNumberOf, + relayer_id_at_this_chain: AccountIdOf, relayers_state: UnrewardedRelayersState, ) -> ( - HeaderOf>, - GrandpaJustification>>, - FromBridgedChainMessagesDeliveryProof>>, + HeaderOf, + GrandpaJustification>, + FromBridgedChainMessagesDeliveryProof>, ) where - MB: MessageBridge, - MessageBridgedChain: Send + Sync + 'static, - MessageThisChain: Send + Sync + 'static, - UnderlyingChainOf>: ChainWithGrandpa, + BridgedChain: ChainWithGrandpa, + ThisChainWithMessages: ChainWithMessages, { // prepare storage proof containing message delivery proof - let (state_root, storage_proof) = prepare_message_delivery_storage_proof::( - lane_id, - InboundLaneData { - relayers: vec![ - UnrewardedRelayer { - relayer: relayer_id_at_this_chain, - messages: DeliveredMessages::new(1) - }; - relayers_state.unrewarded_relayer_entries as usize - ] - .into(), - last_confirmed_nonce: 1, - }, - StorageProofSize::Minimal(0), - ); + let (state_root, storage_proof) = + prepare_message_delivery_storage_proof::( + lane_id, + InboundLaneData { + relayers: vec![ + UnrewardedRelayer { + relayer: relayer_id_at_this_chain, + messages: DeliveredMessages::new(1) + }; + relayers_state.unrewarded_relayer_entries as usize + ] + .into(), + last_confirmed_nonce: 1, + }, + UnverifiedStorageProofParams::default(), + ); - let (header, justification) = make_complex_bridged_grandpa_header_proof::( - state_root, - header_number, - false, - ); + let (header, justification) = + make_complex_bridged_grandpa_header_proof::(state_root, header_number, false); let message_delivery_proof = FromBridgedChainMessagesDeliveryProof { bridged_header_hash: header.hash(), diff --git a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_data/from_parachain.rs b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_data/from_parachain.rs index 5d3cba4e53b5ec7ec9cd2e6141e6e95aa8928970..897fe0d0b0f17729e8bbcd8c941d08ec868ac087 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_data/from_parachain.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_data/from_parachain.rs @@ -19,61 +19,58 @@ use super::{from_grandpa_chain::make_complex_bridged_grandpa_header_proof, prepare_inbound_xcm}; use bp_messages::{ - source_chain::TargetHeaderChain, target_chain::SourceHeaderChain, LaneId, + source_chain::FromBridgedChainMessagesDeliveryProof, + target_chain::FromBridgedChainMessagesProof, ChainWithMessages, LaneId, UnrewardedRelayersState, Weight, }; use bp_runtime::{ - AccountIdOf, BlockNumberOf, HeaderOf, Parachain, StorageProofSize, UnderlyingChainOf, + AccountIdOf, BlockNumberOf, Chain, HeaderOf, Parachain, UnverifiedStorageProofParams, }; use bp_test_utils::prepare_parachain_heads_proof; -use bridge_runtime_common::{ - messages::{ - source::FromBridgedChainMessagesDeliveryProof, target::FromBridgedChainMessagesProof, - BridgedChain as MessageBridgedChain, MessageBridge, ThisChain as MessageThisChain, - }, - messages_generation::{ - encode_all_messages, encode_lane_data, prepare_message_delivery_storage_proof, - prepare_messages_storage_proof, - }, - messages_xcm_extension::XcmAsPlainPayload, -}; +use bridge_runtime_common::messages_xcm_extension::XcmAsPlainPayload; use codec::Encode; use pallet_bridge_grandpa::BridgedHeader; use pallet_bridge_parachains::{RelayBlockHash, RelayBlockNumber}; use sp_runtime::traits::Header as HeaderT; use xcm::latest::prelude::*; +use crate::test_cases::helpers::InboundRelayerId; use bp_header_chain::{justification::GrandpaJustification, ChainWithGrandpa}; use bp_messages::{DeliveredMessages, InboundLaneData, MessageNonce, UnrewardedRelayer}; use bp_polkadot_core::parachains::{ParaHash, ParaHead, ParaHeadsProof, ParaId}; +use pallet_bridge_messages::{ + messages_generation::{ + encode_all_messages, encode_lane_data, prepare_message_delivery_storage_proof, + prepare_messages_storage_proof, + }, + BridgedChainOf, +}; use sp_runtime::SaturatedConversion; /// Prepare a batch call with relay finality proof, parachain head proof and message proof. -pub fn make_complex_relayer_delivery_batch( +pub fn make_complex_relayer_delivery_batch( relay_chain_header: BridgedHeader, grandpa_justification: GrandpaJustification>, parachain_heads: Vec<(ParaId, ParaHash)>, para_heads_proof: ParaHeadsProof, message_proof: FromBridgedChainMessagesProof, - relayer_id_at_bridged_chain: InboundRelayer, -) -> pallet_utility::Call where - Runtime:pallet_bridge_grandpa::Config + relayer_id_at_bridged_chain: InboundRelayerId, +) -> pallet_utility::Call +where + Runtime: pallet_bridge_grandpa::Config + pallet_bridge_parachains::Config - + pallet_bridge_messages::Config< - MPI, - InboundPayload = XcmAsPlainPayload, - InboundRelayer = InboundRelayer, - > + + pallet_bridge_messages::Config + pallet_utility::Config, GPI: 'static, PPI: 'static, MPI: 'static, - ParaHash: From<<>::BridgedChain as bp_runtime::Chain>::Hash>, - <>::BridgedChain as bp_runtime::Chain>::Hash: From, - <>::SourceHeaderChain as SourceHeaderChain>::MessagesProof: - From>, - ::RuntimeCall: - From> + ParaHash: From< + <>::BridgedChain as bp_runtime::Chain>::Hash, + >, + <>::BridgedChain as bp_runtime::Chain>::Hash: + From, + BridgedChainOf: Chain + Parachain, + ::RuntimeCall: From> + From> + From>, { @@ -93,7 +90,7 @@ pub fn make_complex_relayer_delivery_batch::receive_messages_proof { relayer_id_at_bridged_chain: relayer_id_at_bridged_chain.into(), - proof: message_proof.into(), + proof: Box::new(message_proof), messages_count: 1, dispatch_weight: Weight::from_parts(1000000000, 0), }; @@ -122,11 +119,7 @@ where MPI: 'static, >::BridgedChain: bp_runtime::Chain + ChainWithGrandpa, - >::TargetHeaderChain: TargetHeaderChain< - XcmAsPlainPayload, - Runtime::AccountId, - MessagesDeliveryProof = FromBridgedChainMessagesDeliveryProof, - >, + BridgedChainOf: Chain + Parachain, ::RuntimeCall: From> + From> + From>, @@ -160,23 +153,19 @@ where } /// Prepare a call with message proof. -pub fn make_standalone_relayer_delivery_call( +pub fn make_standalone_relayer_delivery_call( message_proof: FromBridgedChainMessagesProof, - relayer_id_at_bridged_chain: InboundRelayer, -) -> Runtime::RuntimeCall where - Runtime: pallet_bridge_messages::Config< - MPI, - InboundPayload = XcmAsPlainPayload, - InboundRelayer = InboundRelayer, - >, + relayer_id_at_bridged_chain: InboundRelayerId, +) -> Runtime::RuntimeCall +where + Runtime: pallet_bridge_messages::Config, MPI: 'static, - Runtime::RuntimeCall: From>, - <>::SourceHeaderChain as SourceHeaderChain>::MessagesProof: - From>, + Runtime::RuntimeCall: From>, + BridgedChainOf: Chain + Parachain, { pallet_bridge_messages::Call::::receive_messages_proof { relayer_id_at_bridged_chain: relayer_id_at_bridged_chain.into(), - proof: message_proof.into(), + proof: Box::new(message_proof), messages_count: 1, dispatch_weight: Weight::from_parts(1000000000, 0), } @@ -192,11 +181,7 @@ where Runtime: pallet_bridge_messages::Config, MPI: 'static, Runtime::RuntimeCall: From>, - >::TargetHeaderChain: TargetHeaderChain< - XcmAsPlainPayload, - Runtime::AccountId, - MessagesDeliveryProof = FromBridgedChainMessagesDeliveryProof, - >, + BridgedChainOf: Chain + Parachain, { pallet_bridge_messages::Call::::receive_messages_delivery_proof { proof: message_delivery_proof, @@ -206,7 +191,12 @@ where } /// Prepare storage proofs of messages, stored at the source chain. -pub fn make_complex_relayer_delivery_proofs( +pub fn make_complex_relayer_delivery_proofs< + BridgedRelayChain, + BridgedParachain, + ThisChainWithMessages, + InnerXcmRuntimeCall, +>( lane_id: LaneId, xcm_message: Xcm, message_nonce: MessageNonce, @@ -226,24 +216,27 @@ pub fn make_complex_relayer_delivery_proofs + ChainWithGrandpa, - MB: MessageBridge, - UnderlyingChainOf>: bp_runtime::Chain + Parachain, + BridgedParachain: bp_runtime::Chain + Parachain, + ThisChainWithMessages: ChainWithMessages, { + // prepare message let message_payload = prepare_inbound_xcm(xcm_message, message_destination); - let message_size = StorageProofSize::Minimal(message_payload.len() as u32); // prepare para storage proof containing message - let (para_state_root, para_storage_proof) = prepare_messages_storage_proof::( - lane_id, - message_nonce..=message_nonce, - None, - message_size, - message_payload, - encode_all_messages, - encode_lane_data, - ); + let (para_state_root, para_storage_proof) = + prepare_messages_storage_proof::( + lane_id, + message_nonce..=message_nonce, + None, + UnverifiedStorageProofParams::from_db_size(message_payload.len() as u32), + |_| message_payload.clone(), + encode_all_messages, + encode_lane_data, + false, + false, + ); let (relay_chain_header, justification, bridged_para_head, parachain_heads, para_heads_proof) = - make_complex_bridged_parachain_heads_proof::( + make_complex_bridged_parachain_heads_proof::( para_state_root, para_header_number, relay_header_number, @@ -270,12 +263,17 @@ where } /// Prepare storage proofs of message confirmations, stored at the target parachain. -pub fn make_complex_relayer_confirmation_proofs( +pub fn make_complex_relayer_confirmation_proofs< + BridgedRelayChain, + BridgedParachain, + ThisChainWithMessages, + InnerXcmRuntimeCall, +>( lane_id: LaneId, para_header_number: u32, relay_header_number: u32, bridged_para_id: u32, - relayer_id_at_this_chain: AccountIdOf>, + relayer_id_at_this_chain: AccountIdOf, relayers_state: UnrewardedRelayersState, ) -> ( HeaderOf, @@ -288,28 +286,29 @@ pub fn make_complex_relayer_confirmation_proofs + ChainWithGrandpa, - MB: MessageBridge, - UnderlyingChainOf>: bp_runtime::Chain + Parachain, + BridgedParachain: bp_runtime::Chain + Parachain, + ThisChainWithMessages: ChainWithMessages, { // prepare para storage proof containing message delivery proof - let (para_state_root, para_storage_proof) = prepare_message_delivery_storage_proof::( - lane_id, - InboundLaneData { - relayers: vec![ - UnrewardedRelayer { - relayer: relayer_id_at_this_chain.into(), - messages: DeliveredMessages::new(1) - }; - relayers_state.unrewarded_relayer_entries as usize - ] - .into(), - last_confirmed_nonce: 1, - }, - StorageProofSize::Minimal(0), - ); + let (para_state_root, para_storage_proof) = + prepare_message_delivery_storage_proof::( + lane_id, + InboundLaneData { + relayers: vec![ + UnrewardedRelayer { + relayer: relayer_id_at_this_chain.into(), + messages: DeliveredMessages::new(1) + }; + relayers_state.unrewarded_relayer_entries as usize + ] + .into(), + last_confirmed_nonce: 1, + }, + UnverifiedStorageProofParams::default(), + ); let (relay_chain_header, justification, bridged_para_head, parachain_heads, para_heads_proof) = - make_complex_bridged_parachain_heads_proof::( + make_complex_bridged_parachain_heads_proof::( para_state_root, para_header_number, relay_header_number, @@ -334,7 +333,7 @@ where } /// Make bridged parachain header with given state root and relay header that is finalizing it. -pub fn make_complex_bridged_parachain_heads_proof( +pub fn make_complex_bridged_parachain_heads_proof( para_state_root: ParaHash, para_header_number: u32, relay_header_number: BlockNumberOf, @@ -350,20 +349,17 @@ pub fn make_complex_bridged_parachain_heads_proof( where BridgedRelayChain: bp_runtime::Chain + ChainWithGrandpa, - MB: MessageBridge, - ::BridgedChain: Send + Sync + 'static, - ::ThisChain: Send + Sync + 'static, - UnderlyingChainOf>: bp_runtime::Chain + Parachain, + BridgedParachain: bp_runtime::Chain + Parachain, { let bridged_para_head = ParaHead( - bp_test_utils::test_header_with_root::>( + bp_test_utils::test_header_with_root::>( para_header_number.into(), para_state_root, ) .encode(), ); let (relay_state_root, para_heads_proof, parachain_heads) = - prepare_parachain_heads_proof::>(vec![( + prepare_parachain_heads_proof::>(vec![( bridged_para_id, bridged_para_head.clone(), )]); diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/Cargo.toml b/cumulus/parachains/runtimes/collectives/collectives-westend/Cargo.toml index 87cf42ba87d836976a8997d90ce99eea9c1f1e9f..43fc9083937c351d0df2190c7593bf1e8126e800 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/Cargo.toml +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/Cargo.toml @@ -54,7 +54,6 @@ sp-inherents = { workspace = true } sp-offchain = { workspace = true } sp-runtime = { workspace = true } sp-session = { workspace = true } -sp-std = { workspace = true } sp-storage = { workspace = true } sp-transaction-pool = { workspace = true } sp-version = { workspace = true } @@ -229,7 +228,6 @@ std = [ "sp-offchain/std", "sp-runtime/std", "sp-session/std", - "sp-std/std", "sp-storage/std", "sp-transaction-pool/std", "sp-version/std", diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/impls.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/impls.rs index e5b176fc77873805fb0e4ed6dba74d720ea3479a..ed5d4870e4a6d1722e1587a650395c6dd2c742dd 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/impls.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/impls.rs @@ -14,6 +14,8 @@ // limitations under the License. use crate::OriginCaller; +use alloc::boxed::Box; +use core::{cmp::Ordering, marker::PhantomData}; use frame_support::{ dispatch::DispatchResultWithPostInfo, traits::{Currency, PrivilegeCmp}, @@ -21,7 +23,6 @@ use frame_support::{ }; use pallet_alliance::{ProposalIndex, ProposalProvider}; use sp_runtime::DispatchError; -use sp_std::{cmp::Ordering, marker::PhantomData, prelude::*}; type AccountIdOf = ::AccountId; diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/lib.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/lib.rs index f37af88c28436cd333333dffc8d451eb177c0f58..d843d6f6f776e0c4eadec44c72925a19402423df 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/lib.rs @@ -42,8 +42,12 @@ mod weights; pub mod xcm_config; // Fellowship configurations. pub mod fellowship; + +extern crate alloc; + pub use ambassador::pallet_ambassador_origins; +use alloc::{vec, vec::Vec}; use ambassador::AmbassadorCoreInstance; use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases; use fellowship::{pallet_fellowship_origins, Fellows, FellowshipCoreInstance}; @@ -57,7 +61,6 @@ use sp_runtime::{ ApplyExtrinsicResult, Perbill, }; -use sp_std::prelude::*; #[cfg(feature = "std")] use sp_version::NativeVersion; use sp_version::RuntimeVersion; @@ -837,7 +840,7 @@ impl_runtime_apis! { Runtime::metadata_at_version(version) } - fn metadata_versions() -> sp_std::vec::Vec { + fn metadata_versions() -> alloc::vec::Vec { Runtime::metadata_versions() } } @@ -1047,7 +1050,7 @@ impl_runtime_apis! { use frame_system_benchmarking::Pallet as SystemBench; impl frame_system_benchmarking::Config for Runtime { - fn setup_set_code_requirements(code: &sp_std::vec::Vec) -> Result<(), BenchmarkError> { + fn setup_set_code_requirements(code: &alloc::vec::Vec) -> Result<(), BenchmarkError> { ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32); Ok(()) } @@ -1096,7 +1099,7 @@ impl_runtime_apis! { } fn set_up_complex_asset_transfer( - ) -> Option<(Assets, u32, Location, Box)> { + ) -> Option<(Assets, u32, Location, alloc::boxed::Box)> { // Collectives only supports teleports to system parachain. // Relay/native token can be teleported between Collectives and Relay. let native_location = Parent.into(); diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/cumulus_pallet_parachain_system.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/cumulus_pallet_parachain_system.rs index 0b7a2fc21cde4f12c821a0e89982db4813f3f832..92c8c88b515474ed5335f306c487ca1217a938b6 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/cumulus_pallet_parachain_system.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/cumulus_pallet_parachain_system.rs @@ -47,7 +47,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weight functions for `cumulus_pallet_parachain_system`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_message_queue.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_message_queue.rs index 4bd71c4e7d497b84f9a5b910015e439b69e41ef9..0bb6d3d0f1c451e6fd9bde07cced236845d380a6 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_message_queue.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_message_queue.rs @@ -43,7 +43,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weight functions for `pallet_message_queue`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/xcm_config.rs index c68f230a16dc3d35b861df5aa7667d61d4cf53cf..ae4fe9e84337b833c5188452ceea3e2769048d02 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/xcm_config.rs @@ -40,10 +40,10 @@ use xcm_builder::{ DenyReserveTransferToRelayChain, DenyThenTry, EnsureXcmOrigin, FixedWeightBounds, FrameTransactionalProcessor, FungibleAdapter, IsConcrete, LocatableAssetId, OriginToPluralityVoice, ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, - SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, - SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, - UsingComponents, WithComputedOrigin, WithUniqueTopic, XcmFeeManagerFromComponents, - XcmFeeToAccount, + SendXcmFeeToAccount, SiblingParachainAsNative, SiblingParachainConvertsVia, + SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, + TrailingSetTopicAsId, UsingComponents, WithComputedOrigin, WithUniqueTopic, + XcmFeeManagerFromComponents, }; use xcm_executor::XcmExecutor; @@ -209,7 +209,7 @@ impl xcm_executor::Config for XcmConfig { type AssetExchanger = (); type FeeManager = XcmFeeManagerFromComponents< WaivedLocations, - XcmFeeToAccount, + SendXcmFeeToAccount, >; type MessageExporter = (); type UniversalAliases = Nothing; diff --git a/cumulus/parachains/runtimes/contracts/contracts-rococo/Cargo.toml b/cumulus/parachains/runtimes/contracts/contracts-rococo/Cargo.toml index 4fb4bcde02351b9485dc2a5ccf6b48cc729633e7..1fcebb3f16a96d2db051ab1d0108d44abc394f4f 100644 --- a/cumulus/parachains/runtimes/contracts/contracts-rococo/Cargo.toml +++ b/cumulus/parachains/runtimes/contracts/contracts-rococo/Cargo.toml @@ -31,7 +31,6 @@ sp-inherents = { workspace = true } sp-offchain = { workspace = true } sp-runtime = { workspace = true } sp-session = { workspace = true } -sp-std = { workspace = true } sp-storage = { workspace = true } sp-transaction-pool = { workspace = true } sp-version = { workspace = true } @@ -133,7 +132,6 @@ std = [ "sp-offchain/std", "sp-runtime/std", "sp-session/std", - "sp-std/std", "sp-storage/std", "sp-transaction-pool/std", "sp-version/std", diff --git a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs index fcd786711bbe90096f2ef5b8d427cec23879027b..e8cc9d02fb0e4c6ac2db7ada26a641fea055ea76 100644 --- a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs +++ b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/contracts.rs @@ -65,6 +65,7 @@ impl Config for Runtime { type AddressGenerator = DefaultAddressGenerator; type MaxCodeLen = ConstU32<{ 123 * 1024 }>; type MaxStorageKeyLen = ConstU32<128>; + type MaxTransientStorageSize = ConstU32<{ 1 * 1024 * 1024 }>; type UnsafeUnstableInterface = ConstBool; type UploadOrigin = EnsureSigned; type InstantiateOrigin = EnsureSigned; diff --git a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs index d2fe0689f5155ece3c3f1397aa18e0a33583e5d6..47ce6f3628ecdd6a426ccbed9f503258d3c6171a 100644 --- a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs @@ -29,6 +29,9 @@ mod contracts; mod weights; mod xcm_config; +extern crate alloc; + +use alloc::{vec, vec::Vec}; use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases; use cumulus_primitives_core::AggregateMessageOrigin; use sp_api::impl_runtime_apis; @@ -40,7 +43,6 @@ use sp_runtime::{ ApplyExtrinsicResult, Perbill, }; -use sp_std::prelude::*; #[cfg(feature = "std")] use sp_version::NativeVersion; use sp_version::RuntimeVersion; @@ -487,7 +489,7 @@ impl_runtime_apis! { Runtime::metadata_at_version(version) } - fn metadata_versions() -> sp_std::vec::Vec { + fn metadata_versions() -> alloc::vec::Vec { Runtime::metadata_versions() } } @@ -765,7 +767,7 @@ impl_runtime_apis! { use frame_system_benchmarking::Pallet as SystemBench; impl frame_system_benchmarking::Config for Runtime { - fn setup_set_code_requirements(code: &sp_std::vec::Vec) -> Result<(), BenchmarkError> { + fn setup_set_code_requirements(code: &alloc::vec::Vec) -> Result<(), BenchmarkError> { ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32); Ok(()) } @@ -815,7 +817,7 @@ impl_runtime_apis! { } fn set_up_complex_asset_transfer( - ) -> Option<(Assets, u32, Location, Box)> { + ) -> Option<(Assets, u32, Location, alloc::boxed::Box)> { // Contracts-System-Para only supports teleports to system parachain. // Relay/native token can be teleported between Contracts-System-Para and Relay. let native_location = Parent.into(); diff --git a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs index ef5ded1731d0d9f3ff60e1e8cb71cd1fe18ca81b..6a41cf75d354693d232b9719289b8edefe1ec835 100644 --- a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs @@ -42,10 +42,10 @@ use xcm_builder::{ AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, DenyReserveTransferToRelayChain, DenyThenTry, EnsureXcmOrigin, FixedWeightBounds, FrameTransactionalProcessor, FungibleAdapter, IsConcrete, NativeAsset, ParentAsSuperuser, - ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, - SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, - TrailingSetTopicAsId, UsingComponents, WithComputedOrigin, WithUniqueTopic, - XcmFeeManagerFromComponents, XcmFeeToAccount, + ParentIsPreset, RelayChainAsNative, SendXcmFeeToAccount, SiblingParachainAsNative, + SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, + SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, + WithComputedOrigin, WithUniqueTopic, XcmFeeManagerFromComponents, }; use xcm_executor::XcmExecutor; @@ -191,7 +191,7 @@ impl xcm_executor::Config for XcmConfig { type AssetExchanger = (); type FeeManager = XcmFeeManagerFromComponents< WaivedLocations, - XcmFeeToAccount, + SendXcmFeeToAccount, >; type MessageExporter = (); type UniversalAliases = Nothing; diff --git a/cumulus/parachains/runtimes/coretime/coretime-rococo/Cargo.toml b/cumulus/parachains/runtimes/coretime/coretime-rococo/Cargo.toml index 57a0782b1ef665b376d86ea8cfa750e3b0b4f007..2920bc428d90b202d1035cb3cbe309dd99097013 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-rococo/Cargo.toml +++ b/cumulus/parachains/runtimes/coretime/coretime-rococo/Cargo.toml @@ -49,7 +49,6 @@ sp-genesis-builder = { workspace = true } sp-offchain = { workspace = true } sp-runtime = { workspace = true } sp-session = { workspace = true } -sp-std = { workspace = true } sp-storage = { workspace = true } sp-transaction-pool = { workspace = true } sp-version = { workspace = true } @@ -133,7 +132,6 @@ std = [ "sp-offchain/std", "sp-runtime/std", "sp-session/std", - "sp-std/std", "sp-storage/std", "sp-transaction-pool/std", "sp-version/std", diff --git a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/lib.rs b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/lib.rs index 6e36539c7bf79a9ef31b991c432473b90d724185..9fd0093840d3fb7008a8fd0f67cb55b858d8600a 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/lib.rs @@ -33,6 +33,9 @@ mod coretime; mod weights; pub mod xcm_config; +extern crate alloc; + +use alloc::{vec, vec::Vec}; use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases; use cumulus_primitives_core::{AggregateMessageOrigin, ParaId}; use frame_support::{ @@ -66,7 +69,6 @@ use sp_runtime::{ transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, DispatchError, MultiAddress, Perbill, }; -use sp_std::prelude::*; #[cfg(feature = "std")] use sp_version::NativeVersion; use sp_version::RuntimeVersion; @@ -552,7 +554,7 @@ impl_runtime_apis! { Runtime::metadata_at_version(version) } - fn metadata_versions() -> sp_std::vec::Vec { + fn metadata_versions() -> alloc::vec::Vec { Runtime::metadata_versions() } } @@ -774,7 +776,7 @@ impl_runtime_apis! { use frame_system_benchmarking::Pallet as SystemBench; impl frame_system_benchmarking::Config for Runtime { - fn setup_set_code_requirements(code: &sp_std::vec::Vec) -> Result<(), BenchmarkError> { + fn setup_set_code_requirements(code: &alloc::vec::Vec) -> Result<(), BenchmarkError> { ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32); Ok(()) } diff --git a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/mod.rs index 9f79cea831aed66a0d073109233731751cdf99ed..b8db473f10662d5b1ef045d28f943fe0cb1430b9 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/mod.rs @@ -18,10 +18,10 @@ mod pallet_xcm_benchmarks_fungible; mod pallet_xcm_benchmarks_generic; use crate::{xcm_config::MaxAssetsIntoHolding, Runtime}; +use alloc::vec::Vec; use frame_support::weights::Weight; use pallet_xcm_benchmarks_fungible::WeightInfo as XcmFungibleWeight; use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; -use sp_std::prelude::*; use xcm::{latest::prelude::*, DoubleEncoded}; trait WeighAssets { diff --git a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs index 7ff1cce2e072339dccd52c0809aafd59337db7b4..73a71980530707930681ebc82a5cd563372eb24e 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs @@ -43,7 +43,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weights for `pallet_xcm_benchmarks::fungible`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index 16412eb49a5267d3f3f38cdd285e8f3b248a5f99..676048f92ad937e7cb80f268fdc1ca4e90779d42 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -43,7 +43,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weights for `pallet_xcm_benchmarks::generic`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/xcm_config.rs index c16b40b8675fbce2878bca4ba1106b89bbd9e9b1..f56a3c42de0210669f55f0f27feb23b44b055cd6 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/xcm_config.rs @@ -43,10 +43,10 @@ use xcm_builder::{ AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, DenyReserveTransferToRelayChain, DenyThenTry, EnsureXcmOrigin, FrameTransactionalProcessor, FungibleAdapter, IsConcrete, NonFungibleAdapter, ParentAsSuperuser, ParentIsPreset, - RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, + RelayChainAsNative, SendXcmFeeToAccount, SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, - XcmFeeManagerFromComponents, XcmFeeToAccount, + XcmFeeManagerFromComponents, }; use xcm_executor::XcmExecutor; @@ -213,7 +213,7 @@ impl xcm_executor::Config for XcmConfig { type AssetExchanger = (); type FeeManager = XcmFeeManagerFromComponents< WaivedLocations, - XcmFeeToAccount, + SendXcmFeeToAccount, >; type MessageExporter = (); type UniversalAliases = Nothing; diff --git a/cumulus/parachains/runtimes/coretime/coretime-westend/Cargo.toml b/cumulus/parachains/runtimes/coretime/coretime-westend/Cargo.toml index d3bf6b43a7ed7453e3c12dc8ecdafeee787e04b5..07a4332800d7f22451caa43ff6668c57ec4fabd7 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-westend/Cargo.toml +++ b/cumulus/parachains/runtimes/coretime/coretime-westend/Cargo.toml @@ -48,7 +48,6 @@ sp-genesis-builder = { workspace = true } sp-offchain = { workspace = true } sp-runtime = { workspace = true } sp-session = { workspace = true } -sp-std = { workspace = true } sp-storage = { workspace = true } sp-transaction-pool = { workspace = true } sp-version = { workspace = true } @@ -131,7 +130,6 @@ std = [ "sp-offchain/std", "sp-runtime/std", "sp-session/std", - "sp-std/std", "sp-storage/std", "sp-transaction-pool/std", "sp-version/std", diff --git a/cumulus/parachains/runtimes/coretime/coretime-westend/src/lib.rs b/cumulus/parachains/runtimes/coretime/coretime-westend/src/lib.rs index 74fdd971f5ce05ba87ec3c1cbf2ac3d233a4d73b..7907f252cf8e47a1d1694c7721f72a81e660dc74 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-westend/src/lib.rs @@ -33,6 +33,9 @@ mod coretime; mod weights; pub mod xcm_config; +extern crate alloc; + +use alloc::{vec, vec::Vec}; use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases; use cumulus_primitives_core::{AggregateMessageOrigin, ParaId}; use frame_support::{ @@ -66,7 +69,6 @@ use sp_runtime::{ transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, DispatchError, MultiAddress, Perbill, }; -use sp_std::prelude::*; #[cfg(feature = "std")] use sp_version::NativeVersion; use sp_version::RuntimeVersion; @@ -543,7 +545,7 @@ impl_runtime_apis! { Runtime::metadata_at_version(version) } - fn metadata_versions() -> sp_std::vec::Vec { + fn metadata_versions() -> alloc::vec::Vec { Runtime::metadata_versions() } } @@ -765,7 +767,7 @@ impl_runtime_apis! { use frame_system_benchmarking::Pallet as SystemBench; impl frame_system_benchmarking::Config for Runtime { - fn setup_set_code_requirements(code: &sp_std::vec::Vec) -> Result<(), BenchmarkError> { + fn setup_set_code_requirements(code: &alloc::vec::Vec) -> Result<(), BenchmarkError> { ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32); Ok(()) } diff --git a/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/mod.rs index 99af88812da2be05bd9273585ea7d186be9f8b90..f35f7bfc188dce73525b5742345e7eb9ed459385 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/mod.rs @@ -17,10 +17,10 @@ mod pallet_xcm_benchmarks_fungible; mod pallet_xcm_benchmarks_generic; use crate::{xcm_config::MaxAssetsIntoHolding, Runtime}; +use alloc::vec::Vec; use frame_support::weights::Weight; use pallet_xcm_benchmarks_fungible::WeightInfo as XcmFungibleWeight; use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; -use sp_std::prelude::*; use xcm::{latest::prelude::*, DoubleEncoded}; trait WeighAssets { diff --git a/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs b/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs index 8e1461c4a99e2e95dea078280844a157ab4084de..ddfc599fa579dd7ae4b83d0a94b0e7092fbdc9c1 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs @@ -43,7 +43,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weights for `pallet_xcm_benchmarks::fungible`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index 9657fa55c1f2fdd4cf6ffdc4888e13e22a262155..7390f35e3974060abf4efd0e621239fa6a9bead0 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -43,7 +43,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weights for `pallet_xcm_benchmarks::generic`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/coretime/coretime-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/coretime/coretime-westend/src/xcm_config.rs index b12765870bfdbbc7eb495a52e9ec4e931dc442da..da8aa1c18bdf44e50643fe6b85cd755051e23c0f 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-westend/src/xcm_config.rs @@ -43,10 +43,10 @@ use xcm_builder::{ AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, DenyReserveTransferToRelayChain, DenyThenTry, EnsureXcmOrigin, FrameTransactionalProcessor, FungibleAdapter, IsConcrete, NonFungibleAdapter, ParentAsSuperuser, ParentIsPreset, - RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, + RelayChainAsNative, SendXcmFeeToAccount, SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, - XcmFeeManagerFromComponents, XcmFeeToAccount, + XcmFeeManagerFromComponents, }; use xcm_executor::XcmExecutor; @@ -221,7 +221,7 @@ impl xcm_executor::Config for XcmConfig { type AssetExchanger = (); type FeeManager = XcmFeeManagerFromComponents< WaivedLocations, - XcmFeeToAccount, + SendXcmFeeToAccount, >; type MessageExporter = (); type UniversalAliases = Nothing; diff --git a/cumulus/parachains/runtimes/glutton/glutton-westend/Cargo.toml b/cumulus/parachains/runtimes/glutton/glutton-westend/Cargo.toml index c201c8375be0d900d3797b11d2597e120eef873c..d20b62a557b950e080ae7eca38526d6af9846861 100644 --- a/cumulus/parachains/runtimes/glutton/glutton-westend/Cargo.toml +++ b/cumulus/parachains/runtimes/glutton/glutton-westend/Cargo.toml @@ -35,7 +35,6 @@ pallet-message-queue = { workspace = true } sp-offchain = { workspace = true } sp-runtime = { workspace = true } sp-session = { workspace = true } -sp-std = { workspace = true } sp-storage = { workspace = true } sp-transaction-pool = { workspace = true } sp-version = { workspace = true } @@ -109,7 +108,6 @@ std = [ "sp-offchain/std", "sp-runtime/std", "sp-session/std", - "sp-std/std", "sp-storage/std", "sp-transaction-pool/std", "sp-version/std", diff --git a/cumulus/parachains/runtimes/glutton/glutton-westend/src/lib.rs b/cumulus/parachains/runtimes/glutton/glutton-westend/src/lib.rs index a204bb7276cfe3b58e5d4b9c9737eeaa5a018128..1b505ad3acbf7aa22a84ce9923a621d826358122 100644 --- a/cumulus/parachains/runtimes/glutton/glutton-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/glutton/glutton-westend/src/lib.rs @@ -47,6 +47,9 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); pub mod weights; pub mod xcm_config; +extern crate alloc; + +use alloc::{vec, vec::Vec}; use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases; use sp_api::impl_runtime_apis; pub use sp_consensus_aura::sr25519::AuthorityId as AuraId; @@ -57,7 +60,6 @@ use sp_runtime::{ transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, }; -use sp_std::prelude::*; #[cfg(feature = "std")] use sp_version::NativeVersion; use sp_version::RuntimeVersion; @@ -345,7 +347,7 @@ impl_runtime_apis! { Runtime::metadata_at_version(version) } - fn metadata_versions() -> sp_std::vec::Vec { + fn metadata_versions() -> alloc::vec::Vec { Runtime::metadata_versions() } } @@ -455,7 +457,7 @@ impl_runtime_apis! { use frame_system_benchmarking::Pallet as SystemBench; impl frame_system_benchmarking::Config for Runtime { - fn setup_set_code_requirements(code: &sp_std::vec::Vec) -> Result<(), BenchmarkError> { + fn setup_set_code_requirements(code: &alloc::vec::Vec) -> Result<(), BenchmarkError> { ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32); Ok(()) } diff --git a/cumulus/parachains/runtimes/people/people-rococo/Cargo.toml b/cumulus/parachains/runtimes/people/people-rococo/Cargo.toml index 890de672e0b5ed74a11435a28dc9f81bbde9297b..a732bec2352d2dfd6fe7e842cb6a5d3206291d7d 100644 --- a/cumulus/parachains/runtimes/people/people-rococo/Cargo.toml +++ b/cumulus/parachains/runtimes/people/people-rococo/Cargo.toml @@ -45,7 +45,6 @@ sp-inherents = { workspace = true } sp-offchain = { workspace = true } sp-runtime = { workspace = true } sp-session = { workspace = true } -sp-std = { workspace = true } sp-storage = { workspace = true } sp-transaction-pool = { workspace = true } sp-version = { workspace = true } @@ -128,7 +127,6 @@ std = [ "sp-offchain/std", "sp-runtime/std", "sp-session/std", - "sp-std/std", "sp-storage/std", "sp-transaction-pool/std", "sp-version/std", diff --git a/cumulus/parachains/runtimes/people/people-rococo/src/lib.rs b/cumulus/parachains/runtimes/people/people-rococo/src/lib.rs index ff31aba8a27716120f455414058d1aa6e17c95e6..4f007c3fc39db185df12cee525509d9a1433a9d9 100644 --- a/cumulus/parachains/runtimes/people/people-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/people/people-rococo/src/lib.rs @@ -22,6 +22,9 @@ pub mod people; mod weights; pub mod xcm_config; +extern crate alloc; + +use alloc::{vec, vec::Vec}; use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases; use cumulus_primitives_core::{AggregateMessageOrigin, ParaId}; use frame_support::{ @@ -59,7 +62,6 @@ use sp_runtime::{ ApplyExtrinsicResult, }; pub use sp_runtime::{MultiAddress, Perbill, Permill}; -use sp_std::prelude::*; #[cfg(feature = "std")] use sp_version::NativeVersion; use sp_version::RuntimeVersion; @@ -521,7 +523,7 @@ impl_runtime_apis! { Runtime::metadata_at_version(version) } - fn metadata_versions() -> sp_std::vec::Vec { + fn metadata_versions() -> alloc::vec::Vec { Runtime::metadata_versions() } } @@ -737,7 +739,7 @@ impl_runtime_apis! { use frame_system_benchmarking::Pallet as SystemBench; impl frame_system_benchmarking::Config for Runtime { - fn setup_set_code_requirements(code: &sp_std::vec::Vec) -> Result<(), BenchmarkError> { + fn setup_set_code_requirements(code: &alloc::vec::Vec) -> Result<(), BenchmarkError> { ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32); Ok(()) } diff --git a/cumulus/parachains/runtimes/people/people-rococo/src/people.rs b/cumulus/parachains/runtimes/people/people-rococo/src/people.rs index 88a89711019d59436c1ca270bbf19781f6dc77f0..8211447d68c8a5a53457d1651cc95754c125f7fd 100644 --- a/cumulus/parachains/runtimes/people/people-rococo/src/people.rs +++ b/cumulus/parachains/runtimes/people/people-rococo/src/people.rs @@ -28,7 +28,6 @@ use sp_runtime::{ traits::{AccountIdConversion, Verify}, RuntimeDebug, }; -use sp_std::prelude::*; parameter_types! { // 27 | Min encoded size of `Registration` @@ -94,8 +93,8 @@ pub enum IdentityField { )] #[codec(mel_bound())] pub struct IdentityInfo { - /// A reasonable display name for the controller of the account. This should be whatever the - /// account is typically known as and should not be confusable with other entities, given + /// A reasonable display name for the controller of the account. This should be whatever the + /// account is typically known as and should not be confusable with other entities, given /// reasonable context. /// /// Stored as UTF-8. @@ -151,7 +150,7 @@ impl IdentityInformationProvider for IdentityInfo { #[cfg(feature = "runtime-benchmarks")] fn create_identity_info() -> Self { - let data = Data::Raw(vec![0; 32].try_into().unwrap()); + let data = Data::Raw(alloc::vec![0; 32].try_into().unwrap()); IdentityInfo { display: data.clone(), diff --git a/cumulus/parachains/runtimes/people/people-rococo/src/weights/cumulus_pallet_parachain_system.rs b/cumulus/parachains/runtimes/people/people-rococo/src/weights/cumulus_pallet_parachain_system.rs index fcea5fd1bf679c803509dd4529b45e4994a7438c..5715d56c2186836556973dc6bebbfec77ac99762 100644 --- a/cumulus/parachains/runtimes/people/people-rococo/src/weights/cumulus_pallet_parachain_system.rs +++ b/cumulus/parachains/runtimes/people/people-rococo/src/weights/cumulus_pallet_parachain_system.rs @@ -20,7 +20,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weight functions for `cumulus_pallet_parachain_system`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/people/people-rococo/src/weights/pallet_message_queue.rs b/cumulus/parachains/runtimes/people/people-rococo/src/weights/pallet_message_queue.rs index fe1911b77a72dbfed0309722a1c59f37b56cb40f..47c67901407366a9f07959e2e22ed5bc83c61a76 100644 --- a/cumulus/parachains/runtimes/people/people-rococo/src/weights/pallet_message_queue.rs +++ b/cumulus/parachains/runtimes/people/people-rococo/src/weights/pallet_message_queue.rs @@ -20,7 +20,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weight functions for `pallet_message_queue`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/mod.rs index 4afd65bdcfea18208046edb4cfe693207cada3bb..11c1bad9aa17866d882f4410d76065a18ab4ef28 100644 --- a/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/mod.rs @@ -17,10 +17,10 @@ mod pallet_xcm_benchmarks_fungible; mod pallet_xcm_benchmarks_generic; use crate::{xcm_config::MaxAssetsIntoHolding, Runtime}; +use alloc::vec::Vec; use frame_support::weights::Weight; use pallet_xcm_benchmarks_fungible::WeightInfo as XcmFungibleWeight; use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; -use sp_std::prelude::*; use xcm::{latest::prelude::*, DoubleEncoded}; trait WeighAssets { diff --git a/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs b/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs index b279399e7a96b68ac68f7e12ed165efb324fab9b..2364798596d50f396a3a732c1e9dc1ad6c48a5bf 100644 --- a/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs +++ b/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs @@ -42,7 +42,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weights for `pallet_xcm_benchmarks::fungible`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index e2be324ee2d48c42a8d7340c8cbcd3a52b161f19..a50c8860c48f84197843a9fd4d44ddb39d742095 100644 --- a/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/cumulus/parachains/runtimes/people/people-rococo/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -42,7 +42,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weights for `pallet_xcm_benchmarks::generic`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/people/people-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/people/people-rococo/src/xcm_config.rs index cca964fb2441bbe8bd40d909eb90766907918df2..96ab3eafa785fe0135916d072666d7102e5027c3 100644 --- a/cumulus/parachains/runtimes/people/people-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/people/people-rococo/src/xcm_config.rs @@ -40,10 +40,10 @@ use xcm_builder::{ AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, DenyReserveTransferToRelayChain, DenyThenTry, DescribeTerminus, EnsureXcmOrigin, FrameTransactionalProcessor, FungibleAdapter, HashedDescription, IsConcrete, ParentAsSuperuser, - ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, - SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, - TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, - XcmFeeManagerFromComponents, XcmFeeToAccount, + ParentIsPreset, RelayChainAsNative, SendXcmFeeToAccount, SiblingParachainAsNative, + SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, + SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, + WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, XcmFeeManagerFromComponents, }; use xcm_executor::XcmExecutor; @@ -219,7 +219,7 @@ impl xcm_executor::Config for XcmConfig { type AssetExchanger = (); type FeeManager = XcmFeeManagerFromComponents< WaivedLocations, - XcmFeeToAccount, + SendXcmFeeToAccount, >; type MessageExporter = (); type UniversalAliases = Nothing; diff --git a/cumulus/parachains/runtimes/people/people-westend/Cargo.toml b/cumulus/parachains/runtimes/people/people-westend/Cargo.toml index 83068e489d2ebb3919d20ac7747d5236ceb5aeb7..20c7e691ebc88622dc57b4a026533fae67cf3044 100644 --- a/cumulus/parachains/runtimes/people/people-westend/Cargo.toml +++ b/cumulus/parachains/runtimes/people/people-westend/Cargo.toml @@ -45,7 +45,6 @@ sp-inherents = { workspace = true } sp-offchain = { workspace = true } sp-runtime = { workspace = true } sp-session = { workspace = true } -sp-std = { workspace = true } sp-storage = { workspace = true } sp-transaction-pool = { workspace = true } sp-version = { workspace = true } @@ -127,7 +126,6 @@ std = [ "sp-offchain/std", "sp-runtime/std", "sp-session/std", - "sp-std/std", "sp-storage/std", "sp-transaction-pool/std", "sp-version/std", diff --git a/cumulus/parachains/runtimes/people/people-westend/src/lib.rs b/cumulus/parachains/runtimes/people/people-westend/src/lib.rs index 6adaa4b4e50201ae1a073d25a4021ec8e84bfa8a..1378324ce7b022e306c39ce4d8b1669ef057eb96 100644 --- a/cumulus/parachains/runtimes/people/people-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/people/people-westend/src/lib.rs @@ -22,6 +22,9 @@ pub mod people; mod weights; pub mod xcm_config; +extern crate alloc; + +use alloc::{vec, vec::Vec}; use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases; use cumulus_primitives_core::{AggregateMessageOrigin, ParaId}; use frame_support::{ @@ -59,7 +62,6 @@ use sp_runtime::{ ApplyExtrinsicResult, }; pub use sp_runtime::{MultiAddress, Perbill, Permill}; -use sp_std::prelude::*; #[cfg(feature = "std")] use sp_version::NativeVersion; use sp_version::RuntimeVersion; @@ -521,7 +523,7 @@ impl_runtime_apis! { Runtime::metadata_at_version(version) } - fn metadata_versions() -> sp_std::vec::Vec { + fn metadata_versions() -> alloc::vec::Vec { Runtime::metadata_versions() } } @@ -737,7 +739,7 @@ impl_runtime_apis! { use frame_system_benchmarking::Pallet as SystemBench; impl frame_system_benchmarking::Config for Runtime { - fn setup_set_code_requirements(code: &sp_std::vec::Vec) -> Result<(), BenchmarkError> { + fn setup_set_code_requirements(code: &alloc::vec::Vec) -> Result<(), BenchmarkError> { ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32); Ok(()) } diff --git a/cumulus/parachains/runtimes/people/people-westend/src/people.rs b/cumulus/parachains/runtimes/people/people-westend/src/people.rs index a5c0e66a3f882df14cbbd8dba51572834738015e..0255fd074b1119cf6432a2f9b0346e6523c181f8 100644 --- a/cumulus/parachains/runtimes/people/people-westend/src/people.rs +++ b/cumulus/parachains/runtimes/people/people-westend/src/people.rs @@ -28,7 +28,6 @@ use sp_runtime::{ traits::{AccountIdConversion, Verify}, RuntimeDebug, }; -use sp_std::prelude::*; parameter_types! { // 27 | Min encoded size of `Registration` @@ -151,7 +150,7 @@ impl IdentityInformationProvider for IdentityInfo { #[cfg(feature = "runtime-benchmarks")] fn create_identity_info() -> Self { - let data = Data::Raw(vec![0; 32].try_into().unwrap()); + let data = Data::Raw(alloc::vec![0; 32].try_into().unwrap()); IdentityInfo { display: data.clone(), diff --git a/cumulus/parachains/runtimes/people/people-westend/src/weights/cumulus_pallet_parachain_system.rs b/cumulus/parachains/runtimes/people/people-westend/src/weights/cumulus_pallet_parachain_system.rs index fcea5fd1bf679c803509dd4529b45e4994a7438c..5715d56c2186836556973dc6bebbfec77ac99762 100644 --- a/cumulus/parachains/runtimes/people/people-westend/src/weights/cumulus_pallet_parachain_system.rs +++ b/cumulus/parachains/runtimes/people/people-westend/src/weights/cumulus_pallet_parachain_system.rs @@ -20,7 +20,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weight functions for `cumulus_pallet_parachain_system`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/people/people-westend/src/weights/pallet_message_queue.rs b/cumulus/parachains/runtimes/people/people-westend/src/weights/pallet_message_queue.rs index fe1911b77a72dbfed0309722a1c59f37b56cb40f..47c67901407366a9f07959e2e22ed5bc83c61a76 100644 --- a/cumulus/parachains/runtimes/people/people-westend/src/weights/pallet_message_queue.rs +++ b/cumulus/parachains/runtimes/people/people-westend/src/weights/pallet_message_queue.rs @@ -20,7 +20,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weight functions for `pallet_message_queue`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/mod.rs b/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/mod.rs index b2579230c9ed7afaf9d187a9e783992723444b3a..b1fc7ad8ed832ec6aa9a65c5e4ad3334ff3225d1 100644 --- a/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/mod.rs +++ b/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/mod.rs @@ -17,10 +17,10 @@ mod pallet_xcm_benchmarks_fungible; mod pallet_xcm_benchmarks_generic; use crate::{xcm_config::MaxAssetsIntoHolding, Runtime}; +use alloc::vec::Vec; use frame_support::weights::Weight; use pallet_xcm_benchmarks_fungible::WeightInfo as XcmFungibleWeight; use pallet_xcm_benchmarks_generic::WeightInfo as XcmGeneric; -use sp_std::prelude::*; use xcm::{latest::prelude::*, DoubleEncoded}; trait WeighAssets { diff --git a/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs b/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs index efffd318817106baf4e2f7661f4cd0a8c333b722..92d08a24618075d21614ae53ed17e3618fc2f8ea 100644 --- a/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs +++ b/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs @@ -42,7 +42,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weights for `pallet_xcm_benchmarks::fungible`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index d7b10f95c792a9874bd98ccf4eb20bdf87e20bb0..861f038199596ef9813275e58914f252d8842a87 100644 --- a/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/cumulus/parachains/runtimes/people/people-westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -42,7 +42,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weights for `pallet_xcm_benchmarks::generic`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/parachains/runtimes/people/people-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/people/people-westend/src/xcm_config.rs index 3926ddcf21efe09933e85552b3fc31f368d69e9b..f35e920d7cb752a4e6e8e427294726f1854e5bb4 100644 --- a/cumulus/parachains/runtimes/people/people-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/people/people-westend/src/xcm_config.rs @@ -40,10 +40,10 @@ use xcm_builder::{ AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, DenyReserveTransferToRelayChain, DenyThenTry, DescribeTerminus, EnsureXcmOrigin, FrameTransactionalProcessor, FungibleAdapter, HashedDescription, IsConcrete, ParentAsSuperuser, - ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia, - SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, - TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, - XcmFeeManagerFromComponents, XcmFeeToAccount, + ParentIsPreset, RelayChainAsNative, SendXcmFeeToAccount, SiblingParachainAsNative, + SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, + SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, + WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, XcmFeeManagerFromComponents, }; use xcm_executor::XcmExecutor; @@ -227,7 +227,7 @@ impl xcm_executor::Config for XcmConfig { type AssetExchanger = (); type FeeManager = XcmFeeManagerFromComponents< WaivedLocations, - XcmFeeToAccount, + SendXcmFeeToAccount, >; type MessageExporter = (); type UniversalAliases = Nothing; diff --git a/cumulus/parachains/runtimes/starters/seedling/Cargo.toml b/cumulus/parachains/runtimes/starters/seedling/Cargo.toml index 8a7c5922362e888723826a04d31b941264a0e5b8..c76c09a31234e6077f97e38c7e38fe4fbddeae86 100644 --- a/cumulus/parachains/runtimes/starters/seedling/Cargo.toml +++ b/cumulus/parachains/runtimes/starters/seedling/Cargo.toml @@ -30,7 +30,6 @@ sp-inherents = { workspace = true } sp-offchain = { workspace = true } sp-runtime = { workspace = true } sp-session = { workspace = true } -sp-std = { workspace = true } sp-transaction-pool = { workspace = true } sp-version = { workspace = true } @@ -74,7 +73,6 @@ std = [ "sp-offchain/std", "sp-runtime/std", "sp-session/std", - "sp-std/std", "sp-transaction-pool/std", "sp-version/std", "substrate-wasm-builder", diff --git a/cumulus/parachains/runtimes/starters/seedling/src/lib.rs b/cumulus/parachains/runtimes/starters/seedling/src/lib.rs index 461133f6cfc06ad8cea140ea19d6df6c8aebb520..1fe72604d3731eed1dee3d27477e0e829cccfba0 100644 --- a/cumulus/parachains/runtimes/starters/seedling/src/lib.rs +++ b/cumulus/parachains/runtimes/starters/seedling/src/lib.rs @@ -27,6 +27,9 @@ #[cfg(feature = "std")] include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); +extern crate alloc; + +use alloc::{vec, vec::Vec}; use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases; use sp_api::impl_runtime_apis; pub use sp_consensus_aura::sr25519::AuthorityId as AuraId; @@ -37,7 +40,6 @@ use sp_runtime::{ transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, }; -use sp_std::prelude::*; #[cfg(feature = "std")] use sp_version::NativeVersion; use sp_version::RuntimeVersion; @@ -310,7 +312,7 @@ impl_runtime_apis! { Runtime::metadata_at_version(version) } - fn metadata_versions() -> sp_std::vec::Vec { + fn metadata_versions() -> alloc::vec::Vec { Runtime::metadata_versions() } } diff --git a/cumulus/parachains/runtimes/starters/shell/Cargo.toml b/cumulus/parachains/runtimes/starters/shell/Cargo.toml index 4a1271ca658406b2f4d6c100a70e1ca7b46ef8eb..8f3b2204cfe34b8bb73c6a9062c9a91df262a8e4 100644 --- a/cumulus/parachains/runtimes/starters/shell/Cargo.toml +++ b/cumulus/parachains/runtimes/starters/shell/Cargo.toml @@ -29,7 +29,6 @@ sp-inherents = { workspace = true } sp-offchain = { workspace = true } sp-runtime = { workspace = true } sp-session = { workspace = true } -sp-std = { workspace = true } sp-transaction-pool = { workspace = true } sp-version = { workspace = true } pallet-message-queue = { workspace = true } @@ -77,7 +76,6 @@ std = [ "sp-offchain/std", "sp-runtime/std", "sp-session/std", - "sp-std/std", "sp-transaction-pool/std", "sp-version/std", "substrate-wasm-builder", diff --git a/cumulus/parachains/runtimes/starters/shell/src/lib.rs b/cumulus/parachains/runtimes/starters/shell/src/lib.rs index 7422b580cc3e08c1df8af5e9dce23d79d0c4e1a8..1dfbe2b6c41c840846e1d64a4d87e7c9c1b0c7cf 100644 --- a/cumulus/parachains/runtimes/starters/shell/src/lib.rs +++ b/cumulus/parachains/runtimes/starters/shell/src/lib.rs @@ -31,6 +31,9 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); pub mod xcm_config; +extern crate alloc; + +use alloc::{vec, vec::Vec}; use codec::{Decode, Encode}; use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases; use cumulus_primitives_core::AggregateMessageOrigin; @@ -45,7 +48,6 @@ use sp_runtime::{ transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, }; -use sp_std::prelude::*; #[cfg(feature = "std")] use sp_version::NativeVersion; use sp_version::RuntimeVersion; @@ -280,7 +282,7 @@ impl sp_runtime::traits::SignedExtension for DisallowSigned { type Pre = (); fn additional_signed( &self, - ) -> sp_std::result::Result<(), sp_runtime::transaction_validity::TransactionValidityError> { + ) -> core::result::Result<(), sp_runtime::transaction_validity::TransactionValidityError> { Ok(()) } fn pre_dispatch( @@ -368,7 +370,7 @@ impl_runtime_apis! { Runtime::metadata_at_version(version) } - fn metadata_versions() -> sp_std::vec::Vec { + fn metadata_versions() -> alloc::vec::Vec { Runtime::metadata_versions() } } diff --git a/cumulus/parachains/runtimes/test-utils/Cargo.toml b/cumulus/parachains/runtimes/test-utils/Cargo.toml index 5e895271ab17f8d9d4cf13cded7f1ebc9716000e..01d7fcc2b5c8b77c7daa90d807634193545e95ec 100644 --- a/cumulus/parachains/runtimes/test-utils/Cargo.toml +++ b/cumulus/parachains/runtimes/test-utils/Cargo.toml @@ -21,7 +21,6 @@ pallet-timestamp = { workspace = true } sp-consensus-aura = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } sp-tracing = { workspace = true, default-features = true } sp-core = { workspace = true } @@ -68,7 +67,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", "xcm-executor/std", "xcm/std", ] diff --git a/cumulus/parachains/runtimes/test-utils/src/lib.rs b/cumulus/parachains/runtimes/test-utils/src/lib.rs index 3c84243306fbe518dd00ee78411d9ec032e90446..3fc3822a63eb9a2c98bc273814854ee2d56035bf 100644 --- a/cumulus/parachains/runtimes/test-utils/src/lib.rs +++ b/cumulus/parachains/runtimes/test-utils/src/lib.rs @@ -13,7 +13,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use sp_std::marker::PhantomData; +use core::marker::PhantomData; use codec::{Decode, DecodeLimit}; use cumulus_primitives_core::{ diff --git a/cumulus/parachains/runtimes/testing/penpal/Cargo.toml b/cumulus/parachains/runtimes/testing/penpal/Cargo.toml index bdd0dfac6065759d10108a7961dbaf987e0ebb16..1a2737f3aa224c1dbf016173a259aafb0224341a 100644 --- a/cumulus/parachains/runtimes/testing/penpal/Cargo.toml +++ b/cumulus/parachains/runtimes/testing/penpal/Cargo.toml @@ -51,7 +51,6 @@ sp-inherents = { workspace = true } sp-offchain = { workspace = true } sp-runtime = { workspace = true } sp-session = { workspace = true } -sp-std = { workspace = true } sp-storage = { workspace = true } sp-transaction-pool = { workspace = true } sp-version = { workspace = true } @@ -128,7 +127,6 @@ std = [ "sp-offchain/std", "sp-runtime/std", "sp-session/std", - "sp-std/std", "sp-storage/std", "sp-transaction-pool/std", "sp-version/std", diff --git a/cumulus/parachains/runtimes/testing/penpal/src/lib.rs b/cumulus/parachains/runtimes/testing/penpal/src/lib.rs index 8d03f8332764f4a1a478ab4bef9c3dfd663e7169..bf39c02a3f59460156c37e6c652bc69fa7237a2d 100644 --- a/cumulus/parachains/runtimes/testing/penpal/src/lib.rs +++ b/cumulus/parachains/runtimes/testing/penpal/src/lib.rs @@ -32,6 +32,9 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); mod weights; pub mod xcm_config; +extern crate alloc; + +use alloc::{vec, vec::Vec}; use codec::Encode; use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases; use cumulus_primitives_core::{AggregateMessageOrigin, ParaId}; @@ -69,7 +72,6 @@ use sp_runtime::{ ApplyExtrinsicResult, }; pub use sp_runtime::{traits::ConvertInto, MultiAddress, Perbill, Permill}; -use sp_std::prelude::*; #[cfg(feature = "std")] use sp_version::NativeVersion; use sp_version::RuntimeVersion; @@ -737,7 +739,7 @@ impl_runtime_apis! { Runtime::metadata_at_version(version) } - fn metadata_versions() -> sp_std::vec::Vec { + fn metadata_versions() -> alloc::vec::Vec { Runtime::metadata_versions() } } diff --git a/cumulus/parachains/runtimes/testing/penpal/src/xcm_config.rs b/cumulus/parachains/runtimes/testing/penpal/src/xcm_config.rs index 08a2da260c57e67b17eecf55f3845049e371b996..eca7c7bbc3c2daa4291ba84a11e67b335377e4df 100644 --- a/cumulus/parachains/runtimes/testing/penpal/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/testing/penpal/src/xcm_config.rs @@ -47,11 +47,11 @@ use xcm_builder::{ AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, AsPrefixedGeneralIndex, ConvertedConcreteId, EnsureXcmOrigin, FixedWeightBounds, FrameTransactionalProcessor, FungibleAdapter, FungiblesAdapter, IsConcrete, LocalMint, NativeAsset, NoChecking, - ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, - SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32, - SovereignSignedViaLocation, StartsWith, TakeWeightCredit, TrailingSetTopicAsId, - UsingComponents, WithComputedOrigin, WithUniqueTopic, XcmFeeManagerFromComponents, - XcmFeeToAccount, + ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, SendXcmFeeToAccount, + SiblingParachainAsNative, SiblingParachainConvertsVia, SignedAccountId32AsNative, + SignedToAccountId32, SovereignSignedViaLocation, StartsWith, TakeWeightCredit, + TrailingSetTopicAsId, UsingComponents, WithComputedOrigin, WithUniqueTopic, + XcmFeeManagerFromComponents, }; use xcm_executor::{traits::JustTry, XcmExecutor}; @@ -351,7 +351,7 @@ impl xcm_executor::Config for XcmConfig { type AssetExchanger = (); type FeeManager = XcmFeeManagerFromComponents< (), - XcmFeeToAccount, + SendXcmFeeToAccount, >; type MessageExporter = (); type UniversalAliases = Nothing; diff --git a/cumulus/parachains/runtimes/testing/rococo-parachain/Cargo.toml b/cumulus/parachains/runtimes/testing/rococo-parachain/Cargo.toml index 7cbb614babe7988831db0898e6b08242cc66efe0..a0ad248bb7048f9a19cec45f97ad4242c9455f83 100644 --- a/cumulus/parachains/runtimes/testing/rococo-parachain/Cargo.toml +++ b/cumulus/parachains/runtimes/testing/rococo-parachain/Cargo.toml @@ -35,7 +35,6 @@ sp-inherents = { workspace = true } sp-offchain = { workspace = true } sp-runtime = { workspace = true } sp-session = { workspace = true } -sp-std = { workspace = true } sp-transaction-pool = { workspace = true } sp-version = { workspace = true } @@ -106,7 +105,6 @@ std = [ "sp-offchain/std", "sp-runtime/std", "sp-session/std", - "sp-std/std", "sp-transaction-pool/std", "sp-version/std", "substrate-wasm-builder", diff --git a/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs b/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs index 40f2b78ffd6d5201ff4f8b2c04016f3f0261f71a..dff7046f1972614d30210b6ac6d21c24e0350aea 100644 --- a/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs +++ b/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs @@ -22,6 +22,9 @@ #[cfg(feature = "std")] include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); +extern crate alloc; + +use alloc::{vec, vec::Vec}; use cumulus_pallet_parachain_system::RelayNumberMonotonicallyIncreases; use polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery; use sp_api::impl_runtime_apis; @@ -32,7 +35,6 @@ use sp_runtime::{ transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, }; -use sp_std::prelude::*; #[cfg(feature = "std")] use sp_version::NativeVersion; use sp_version::RuntimeVersion; @@ -711,7 +713,7 @@ impl_runtime_apis! { Runtime::metadata_at_version(version) } - fn metadata_versions() -> sp_std::vec::Vec { + fn metadata_versions() -> alloc::vec::Vec { Runtime::metadata_versions() } } diff --git a/cumulus/polkadot-parachain/Cargo.toml b/cumulus/polkadot-parachain/Cargo.toml index 7085211dad26aa7a916f9a71f9afab79793688c0..b20d2a28fa7f3be2b6517dab5fc422c68d1ec787 100644 --- a/cumulus/polkadot-parachain/Cargo.toml +++ b/cumulus/polkadot-parachain/Cargo.toml @@ -24,6 +24,7 @@ hex-literal = { workspace = true, default-features = true } log = { workspace = true, default-features = true } serde = { features = ["derive"], workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } +docify = { workspace = true } # Local rococo-parachain-runtime = { workspace = true } diff --git a/cumulus/polkadot-parachain/src/cli.rs b/cumulus/polkadot-parachain/src/cli.rs index d06354dda22057fda87bb21e47340e38835abb64..a5fe33dffc9672682e0585194981e42141803de6 100644 --- a/cumulus/polkadot-parachain/src/cli.rs +++ b/cumulus/polkadot-parachain/src/cli.rs @@ -90,6 +90,13 @@ pub struct Cli { #[arg(long)] pub no_hardware_benchmarks: bool, + /// Export all `PoVs` build by this collator to the given folder. + /// + /// This is useful for debugging issues that are occurring while validating these `PoVs` on the + /// relay chain. + #[arg(long)] + pub export_pov_to_path: Option, + /// Relay chain arguments #[arg(raw = true)] pub relay_chain_args: Vec, @@ -97,7 +104,10 @@ pub struct Cli { impl Cli { pub(crate) fn node_extra_args(&self) -> NodeExtraArgs { - NodeExtraArgs { use_slot_based_consensus: self.experimental_use_slot_based } + NodeExtraArgs { + use_slot_based_consensus: self.experimental_use_slot_based, + export_pov: self.export_pov_to_path.clone(), + } } } diff --git a/cumulus/polkadot-parachain/src/command.rs b/cumulus/polkadot-parachain/src/command.rs index fcf6c06f42227d5f8b9bb4d0c50686f699854511..e867a41bee2b807852ddf8dbb47379a9afb1cc9c 100644 --- a/cumulus/polkadot-parachain/src/command.rs +++ b/cumulus/polkadot-parachain/src/command.rs @@ -17,8 +17,7 @@ #[cfg(feature = "runtime-benchmarks")] use crate::service::Block; use crate::{ - chain_spec, - chain_spec::GenericChainSpec, + chain_spec::{self, GenericChainSpec}, cli::{Cli, RelayChainCli, Subcommand}, common::NodeExtraArgs, fake_runtime_api::{ @@ -388,7 +387,7 @@ impl SubstrateCli for RelayChainCli { fn new_node_spec( config: &sc_service::Configuration, - extra_args: NodeExtraArgs, + extra_args: &NodeExtraArgs, ) -> std::result::Result, sc_cli::Error> { Ok(match config.chain_spec.runtime()? { Runtime::AssetHubPolkadot => @@ -421,35 +420,35 @@ pub fn run() -> Result<()> { Some(Subcommand::CheckBlock(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|config| { - let node = new_node_spec(&config, cli.node_extra_args())?; + let node = new_node_spec(&config, &cli.node_extra_args())?; node.prepare_check_block_cmd(config, cmd) }) }, Some(Subcommand::ExportBlocks(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|config| { - let node = new_node_spec(&config, cli.node_extra_args())?; + let node = new_node_spec(&config, &cli.node_extra_args())?; node.prepare_export_blocks_cmd(config, cmd) }) }, Some(Subcommand::ExportState(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|config| { - let node = new_node_spec(&config, cli.node_extra_args())?; + let node = new_node_spec(&config, &cli.node_extra_args())?; node.prepare_export_state_cmd(config, cmd) }) }, Some(Subcommand::ImportBlocks(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|config| { - let node = new_node_spec(&config, cli.node_extra_args())?; + let node = new_node_spec(&config, &cli.node_extra_args())?; node.prepare_import_blocks_cmd(config, cmd) }) }, Some(Subcommand::Revert(cmd)) => { let runner = cli.create_runner(cmd)?; runner.async_run(|config| { - let node = new_node_spec(&config, cli.node_extra_args())?; + let node = new_node_spec(&config, &cli.node_extra_args())?; node.prepare_revert_cmd(config, cmd) }) }, @@ -471,7 +470,7 @@ pub fn run() -> Result<()> { Some(Subcommand::ExportGenesisHead(cmd)) => { let runner = cli.create_runner(cmd)?; runner.sync_run(|config| { - let node = new_node_spec(&config, cli.node_extra_args())?; + let node = new_node_spec(&config, &cli.node_extra_args())?; node.run_export_genesis_head_cmd(config, cmd) }) }, @@ -494,12 +493,12 @@ pub fn run() -> Result<()> { )) }), BenchmarkCmd::Block(cmd) => runner.sync_run(|config| { - let node = new_node_spec(&config, cli.node_extra_args())?; + let node = new_node_spec(&config, &cli.node_extra_args())?; node.run_benchmark_block_cmd(config, cmd) }), #[cfg(feature = "runtime-benchmarks")] BenchmarkCmd::Storage(cmd) => runner.sync_run(|config| { - let node = new_node_spec(&config, cli.node_extra_args())?; + let node = new_node_spec(&config, &cli.node_extra_args())?; node.run_benchmark_storage_cmd(config, cmd) }), BenchmarkCmd::Machine(cmd) => @@ -607,9 +606,9 @@ async fn start_node( extra_args: NodeExtraArgs, hwbench: Option, ) -> Result { - let node_spec = new_node_spec(&config, extra_args)?; + let node_spec = new_node_spec(&config, &extra_args)?; node_spec - .start_node(config, polkadot_config, collator_options, id, hwbench) + .start_node(config, polkadot_config, collator_options, id, hwbench, extra_args) .await .map_err(Into::into) } diff --git a/cumulus/polkadot-parachain/src/common/mod.rs b/cumulus/polkadot-parachain/src/common/mod.rs index 9f5febafe30427fbd549b79e81c83d2392a795d5..d7718931b8726af15f9348c22596df9406f99c75 100644 --- a/cumulus/polkadot-parachain/src/common/mod.rs +++ b/cumulus/polkadot-parachain/src/common/mod.rs @@ -26,6 +26,7 @@ use sp_block_builder::BlockBuilder; use sp_runtime::traits::Block as BlockT; use sp_session::SessionKeys; use sp_transaction_pool::runtime_api::TaggedTransactionQueue; +use std::path::PathBuf; /// Convenience trait that defines the basic bounds for the `RuntimeApi` of a parachain node. pub trait NodeRuntimeApi: @@ -69,4 +70,7 @@ where /// Extra args that are passed when creating a new node spec. pub struct NodeExtraArgs { pub use_slot_based_consensus: bool, + + /// If set, each `PoV` build by the node will be exported to this folder. + pub export_pov: Option, } diff --git a/cumulus/polkadot-parachain/src/fake_runtime_api/asset_hub_polkadot_aura.rs b/cumulus/polkadot-parachain/src/fake_runtime_api/asset_hub_polkadot_aura.rs index 0b79d338c16813238e70a29d454e91882113128f..7d54e9b4be04304f612916efc292b6a2b2fd6ed7 100644 --- a/cumulus/polkadot-parachain/src/fake_runtime_api/asset_hub_polkadot_aura.rs +++ b/cumulus/polkadot-parachain/src/fake_runtime_api/asset_hub_polkadot_aura.rs @@ -53,7 +53,7 @@ sp_api::impl_runtime_apis! { unimplemented!() } - fn metadata_versions() -> sp_std::vec::Vec { + fn metadata_versions() -> Vec { unimplemented!() } } diff --git a/cumulus/polkadot-parachain/src/fake_runtime_api/aura.rs b/cumulus/polkadot-parachain/src/fake_runtime_api/aura.rs index 823eb9ab584a06ea1370d6b4c03ce124c426f9fe..ca5fc8bdf119b586d1d34f39122af2b6c9801831 100644 --- a/cumulus/polkadot-parachain/src/fake_runtime_api/aura.rs +++ b/cumulus/polkadot-parachain/src/fake_runtime_api/aura.rs @@ -53,7 +53,7 @@ sp_api::impl_runtime_apis! { unimplemented!() } - fn metadata_versions() -> sp_std::vec::Vec { + fn metadata_versions() -> Vec { unimplemented!() } } diff --git a/cumulus/polkadot-parachain/src/service.rs b/cumulus/polkadot-parachain/src/service.rs index f5f6189d1f0d6b399f584df77bf70bd3961781df..ef01f7f1f6a660575b9311d7fcbdc5698aff2334 100644 --- a/cumulus/polkadot-parachain/src/service.rs +++ b/cumulus/polkadot-parachain/src/service.rs @@ -15,13 +15,16 @@ // along with Cumulus. If not, see . use cumulus_client_cli::{CollatorOptions, ExportGenesisHeadCommand}; -use cumulus_client_collator::service::CollatorService; -use cumulus_client_consensus_aura::collators::{ - lookahead::{self as aura, Params as AuraParams}, - slot_based::{self as slot_based, Params as SlotBasedParams}, +use cumulus_client_collator::service::{ + CollatorService, ServiceInterface as CollatorServiceInterface, +}; +use cumulus_client_consensus_aura::collators::lookahead::{self as aura, Params as AuraParams}; +#[docify::export(slot_based_colator_import)] +use cumulus_client_consensus_aura::collators::slot_based::{ + self as slot_based, Params as SlotBasedParams, }; use cumulus_client_consensus_common::ParachainBlockImport as TParachainBlockImport; -use cumulus_client_consensus_proposer::Proposer; +use cumulus_client_consensus_proposer::{Proposer, ProposerInterface}; use cumulus_client_consensus_relay_chain::Verifier as RelayChainVerifier; #[allow(deprecated)] use cumulus_client_service::old_consensus; @@ -62,6 +65,7 @@ use sc_sysinfo::HwBench; use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle}; use sc_transaction_pool::FullPool; use sp_api::ProvideRuntimeApi; +use sp_inherents::CreateInherentDataProviders; use sp_keystore::KeystorePtr; use sp_runtime::{app_crypto::AppCrypto, traits::Header as HeaderT}; use std::{marker::PhantomData, pin::Pin, sync::Arc, time::Duration}; @@ -121,6 +125,7 @@ where overseer_handle: OverseerHandle, announce_block: Arc>) + Send + Sync>, backend: Arc, + node_extra_args: NodeExtraArgs, ) -> Result<(), sc_service::Error>; } @@ -222,6 +227,7 @@ pub(crate) trait NodeSpec { collator_options: CollatorOptions, para_id: ParaId, hwbench: Option, + node_extra_args: NodeExtraArgs, ) -> Pin>>> where Net: NetworkBackend, @@ -357,6 +363,7 @@ pub(crate) trait NodeSpec { overseer_handle, announce_block, backend.clone(), + node_extra_args, )?; } @@ -520,7 +527,7 @@ where const SYBIL_RESISTANCE: CollatorSybilResistance = CollatorSybilResistance::Resistant; } -pub fn new_aura_node_spec(extra_args: NodeExtraArgs) -> Box +pub fn new_aura_node_spec(extra_args: &NodeExtraArgs) -> Box where RuntimeApi: ConstructNodeRuntimeApi>, RuntimeApi::RuntimeApi: AuraRuntimeApi @@ -563,6 +570,7 @@ impl StartConsensus for StartRelayChainConsensus { overseer_handle: OverseerHandle, announce_block: Arc>) + Send + Sync>, _backend: Arc, + _node_extra_args: NodeExtraArgs, ) -> Result<(), Error> { let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording( task_manager.spawn_handle(), @@ -623,6 +631,48 @@ pub(crate) struct StartSlotBasedAuraConsensus( PhantomData<(RuntimeApi, AuraId)>, ); +impl StartSlotBasedAuraConsensus +where + RuntimeApi: ConstructNodeRuntimeApi>, + RuntimeApi::RuntimeApi: AuraRuntimeApi, + AuraId: AuraIdT + Sync, +{ + #[docify::export_content] + fn launch_slot_based_collator( + params: SlotBasedParams< + ParachainBlockImport, + CIDP, + ParachainClient, + ParachainBackend, + Arc, + CHP, + Proposer, + CS, + >, + task_manager: &TaskManager, + ) where + CIDP: CreateInherentDataProviders + 'static, + CIDP::InherentDataProviders: Send, + CHP: cumulus_client_consensus_common::ValidationCodeHashProvider + Send + 'static, + Proposer: ProposerInterface + Send + Sync + 'static, + CS: CollatorServiceInterface + Send + Sync + Clone + 'static, + { + let (collation_future, block_builder_future) = + slot_based::run::::Pair, _, _, _, _, _, _, _, _>(params); + + task_manager.spawn_essential_handle().spawn( + "collation-task", + Some("parachain-block-authoring"), + collation_future, + ); + task_manager.spawn_essential_handle().spawn( + "block-builder-task", + Some("parachain-block-authoring"), + block_builder_future, + ); + } +} + impl StartConsensus for StartSlotBasedAuraConsensus where @@ -645,6 +695,7 @@ where _overseer_handle: OverseerHandle, announce_block: Arc>) + Send + Sync>, backend: Arc, + _node_extra_args: NodeExtraArgs, ) -> Result<(), Error> { let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording( task_manager.spawn_handle(), @@ -683,19 +734,10 @@ where slot_drift: Duration::from_secs(1), }; - let (collation_future, block_builder_future) = - slot_based::run::::Pair, _, _, _, _, _, _, _, _>(params); + // We have a separate function only to be able to use `docify::export` on this piece of + // code. + Self::launch_slot_based_collator(params, task_manager); - task_manager.spawn_essential_handle().spawn( - "collation-task", - Some("parachain-block-authoring"), - collation_future, - ); - task_manager.spawn_essential_handle().spawn( - "block-builder-task", - Some("parachain-block-authoring"), - block_builder_future, - ); Ok(()) } } @@ -749,6 +791,7 @@ where overseer_handle: OverseerHandle, announce_block: Arc>) + Send + Sync>, backend: Arc, + node_extra_args: NodeExtraArgs, ) -> Result<(), Error> { let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording( task_manager.spawn_handle(), @@ -765,33 +808,37 @@ where client.clone(), ); - let params = AuraParams { - create_inherent_data_providers: move |_, ()| async move { Ok(()) }, - block_import, - para_client: client.clone(), - para_backend: backend, - relay_client: relay_chain_interface, - code_hash_provider: { - let client = client.clone(); - move |block_hash| { - client.code_at(block_hash).ok().map(|c| ValidationCode::from(c).hash()) - } + let params = aura::ParamsWithExport { + export_pov: node_extra_args.export_pov, + params: AuraParams { + create_inherent_data_providers: move |_, ()| async move { Ok(()) }, + block_import, + para_client: client.clone(), + para_backend: backend, + relay_client: relay_chain_interface, + code_hash_provider: { + let client = client.clone(); + move |block_hash| { + client.code_at(block_hash).ok().map(|c| ValidationCode::from(c).hash()) + } + }, + keystore, + collator_key, + para_id, + overseer_handle, + relay_chain_slot_duration, + proposer: Proposer::new(proposer_factory), + collator_service, + authoring_duration: Duration::from_millis(1500), + reinitialize: false, }, - keystore, - collator_key, - para_id, - overseer_handle, - relay_chain_slot_duration, - proposer: Proposer::new(proposer_factory), - collator_service, - authoring_duration: Duration::from_millis(1500), - reinitialize: false, }; - let fut = async move { - wait_for_aura(client).await; - aura::run::::Pair, _, _, _, _, _, _, _, _>(params).await; - }; + let fut = + async move { + wait_for_aura(client).await; + aura::run_with_export::::Pair, _, _, _, _, _, _, _, _>(params).await; + }; task_manager.spawn_essential_handle().spawn("aura", None, fut); Ok(()) @@ -873,6 +920,7 @@ pub(crate) trait DynNodeSpec { collator_options: CollatorOptions, para_id: ParaId, hwbench: Option, + node_extra_args: NodeExtraArgs, ) -> Pin>>>; } @@ -963,6 +1011,7 @@ where collator_options: CollatorOptions, para_id: ParaId, hwbench: Option, + node_extra_args: NodeExtraArgs, ) -> Pin>>> { match parachain_config.network.network_backend { sc_network::config::NetworkBackendType::Libp2p => @@ -972,6 +1021,7 @@ where collator_options, para_id, hwbench, + node_extra_args, ), sc_network::config::NetworkBackendType::Litep2p => ::start_node::( @@ -980,6 +1030,7 @@ where collator_options, para_id, hwbench, + node_extra_args, ), } } diff --git a/cumulus/primitives/aura/Cargo.toml b/cumulus/primitives/aura/Cargo.toml index f17c2035edd66a46be4810fa470357c1ccd3fdbd..062b9ce736e7f7b9d36f23908bf94437a06f22cb 100644 --- a/cumulus/primitives/aura/Cargo.toml +++ b/cumulus/primitives/aura/Cargo.toml @@ -16,7 +16,6 @@ codec = { features = ["derive"], workspace = true } sp-api = { workspace = true } sp-consensus-aura = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } # Polkadot polkadot-core-primitives = { workspace = true } @@ -31,5 +30,4 @@ std = [ "sp-api/std", "sp-consensus-aura/std", "sp-runtime/std", - "sp-std/std", ] diff --git a/cumulus/primitives/core/Cargo.toml b/cumulus/primitives/core/Cargo.toml index f41213e9485e2509965a25ce556f687a185bba9a..533d368d3b00ed883b1996d376a80f4d5d970570 100644 --- a/cumulus/primitives/core/Cargo.toml +++ b/cumulus/primitives/core/Cargo.toml @@ -16,7 +16,6 @@ scale-info = { features = ["derive"], workspace = true } # Substrate sp-api = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } sp-trie = { workspace = true } # Polkadot @@ -35,7 +34,6 @@ std = [ "scale-info/std", "sp-api/std", "sp-runtime/std", - "sp-std/std", "sp-trie/std", "xcm/std", ] diff --git a/cumulus/primitives/core/src/lib.rs b/cumulus/primitives/core/src/lib.rs index 29216d513465160eb94db76faedb6e7fd992b461..6eafecfc3ff574689b5dd3125b97c0e5bade844a 100644 --- a/cumulus/primitives/core/src/lib.rs +++ b/cumulus/primitives/core/src/lib.rs @@ -18,11 +18,13 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + +use alloc::vec::Vec; use codec::{Decode, Encode, MaxEncodedLen}; use polkadot_parachain_primitives::primitives::HeadData; use scale_info::TypeInfo; use sp_runtime::RuntimeDebug; -use sp_std::prelude::*; pub use polkadot_core_primitives::InboundDownwardMessage; pub use polkadot_parachain_primitives::primitives::{ @@ -202,7 +204,7 @@ pub struct ParachainBlockData { /// The header of the parachain block. header: B::Header, /// The extrinsics of the parachain block. - extrinsics: sp_std::vec::Vec, + extrinsics: alloc::vec::Vec, /// The data that is required to emulate the storage accesses executed by all extrinsics. storage_proof: sp_trie::CompactProof, } @@ -211,7 +213,7 @@ impl ParachainBlockData { /// Creates a new instance of `Self`. pub fn new( header: ::Header, - extrinsics: sp_std::vec::Vec<::Extrinsic>, + extrinsics: alloc::vec::Vec<::Extrinsic>, storage_proof: sp_trie::CompactProof, ) -> Self { Self { header, extrinsics, storage_proof } @@ -243,7 +245,7 @@ impl ParachainBlockData { } /// Deconstruct into the inner parts. - pub fn deconstruct(self) -> (B::Header, sp_std::vec::Vec, sp_trie::CompactProof) { + pub fn deconstruct(self) -> (B::Header, alloc::vec::Vec, sp_trie::CompactProof) { (self.header, self.extrinsics, self.storage_proof) } } diff --git a/cumulus/primitives/parachain-inherent/Cargo.toml b/cumulus/primitives/parachain-inherent/Cargo.toml index c07fe07545614c375634027df171948dbdb95285..172af4b9ec63e0843fdf59cdf90f21c842d60b41 100644 --- a/cumulus/primitives/parachain-inherent/Cargo.toml +++ b/cumulus/primitives/parachain-inherent/Cargo.toml @@ -19,7 +19,6 @@ sp-core = { workspace = true } sp-inherents = { workspace = true } sp-runtime = { optional = true, workspace = true } sp-state-machine = { optional = true, workspace = true } -sp-std = { workspace = true } sp-trie = { workspace = true } # Cumulus @@ -36,6 +35,5 @@ std = [ "sp-inherents/std", "sp-runtime?/std", "sp-state-machine?/std", - "sp-std/std", "sp-trie/std", ] diff --git a/cumulus/primitives/parachain-inherent/src/lib.rs b/cumulus/primitives/parachain-inherent/src/lib.rs index 75a56693958e6a982e21851384535217157b9c82..ad4b39b547c5f24f123e8abfd5a352dd1008adae 100644 --- a/cumulus/primitives/parachain-inherent/src/lib.rs +++ b/cumulus/primitives/parachain-inherent/src/lib.rs @@ -27,14 +27,16 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + use cumulus_primitives_core::{ relay_chain::{BlakeTwo256, Hash as RelayHash, HashT as _}, InboundDownwardMessage, InboundHrmpMessage, ParaId, PersistedValidationData, }; +use alloc::{collections::btree_map::BTreeMap, vec::Vec}; use scale_info::TypeInfo; use sp_inherents::InherentIdentifier; -use sp_std::{collections::btree_map::BTreeMap, vec::Vec}; /// The identifier for the parachain inherent. pub const INHERENT_IDENTIFIER: InherentIdentifier = *b"sysi1337"; diff --git a/cumulus/primitives/storage-weight-reclaim/Cargo.toml b/cumulus/primitives/storage-weight-reclaim/Cargo.toml index af32fb68d8bb20e6c61b2065ddfe948c98bd64a6..3a98fdd017aef9b7e411ef59d56fecc89bf0c897 100644 --- a/cumulus/primitives/storage-weight-reclaim/Cargo.toml +++ b/cumulus/primitives/storage-weight-reclaim/Cargo.toml @@ -18,7 +18,6 @@ frame-support = { workspace = true } frame-system = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } cumulus-primitives-core = { workspace = true } cumulus-primitives-proof-size-hostfunction = { workspace = true } @@ -41,6 +40,5 @@ std = [ "scale-info/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", "sp-trie/std", ] diff --git a/cumulus/primitives/storage-weight-reclaim/src/lib.rs b/cumulus/primitives/storage-weight-reclaim/src/lib.rs index 35fa334f51c6996c48825cec03a0a90df5b0acbe..f48dd927ee962a23a0d831ec071469bb34e517e3 100644 --- a/cumulus/primitives/storage-weight-reclaim/src/lib.rs +++ b/cumulus/primitives/storage-weight-reclaim/src/lib.rs @@ -18,6 +18,7 @@ #![cfg_attr(not(feature = "std"), no_std)] use codec::{Decode, Encode}; +use core::marker::PhantomData; use cumulus_primitives_core::Weight; use cumulus_primitives_proof_size_hostfunction::{ storage_proof_size::storage_proof_size, PROOF_RECORDING_DISABLED, @@ -33,7 +34,6 @@ use sp_runtime::{ transaction_validity::TransactionValidityError, DispatchResult, }; -use sp_std::marker::PhantomData; const LOG_TARGET: &'static str = "runtime::storage_reclaim"; @@ -199,6 +199,7 @@ where #[cfg(test)] mod tests { use super::*; + use core::marker::PhantomData; use frame_support::{ assert_ok, dispatch::{DispatchClass, PerDispatchClass}, @@ -206,7 +207,6 @@ mod tests { }; use frame_system::{BlockWeight, CheckWeight}; use sp_runtime::{AccountId32, BuildStorage}; - use sp_std::marker::PhantomData; use sp_trie::proof_size_extension::ProofSizeExt; type Test = cumulus_test_runtime::Runtime; diff --git a/cumulus/primitives/timestamp/Cargo.toml b/cumulus/primitives/timestamp/Cargo.toml index f7bf53a9d7d7cb4180f7afd9bc0c574e89675513..a50011bc3f0e911f2c682fcc02dc8a7693101ffc 100644 --- a/cumulus/primitives/timestamp/Cargo.toml +++ b/cumulus/primitives/timestamp/Cargo.toml @@ -15,7 +15,6 @@ futures = { workspace = true } # Substrate sp-inherents = { workspace = true } -sp-std = { workspace = true } sp-timestamp = { workspace = true } # Cumulus @@ -27,6 +26,5 @@ std = [ "codec/std", "cumulus-primitives-core/std", "sp-inherents/std", - "sp-std/std", "sp-timestamp/std", ] diff --git a/cumulus/primitives/timestamp/src/lib.rs b/cumulus/primitives/timestamp/src/lib.rs index e6aba6d0bb74043c134400387d84429cf0a712d1..5365f83efdf1111eaf727a4a8fe87ec4f2065726 100644 --- a/cumulus/primitives/timestamp/src/lib.rs +++ b/cumulus/primitives/timestamp/src/lib.rs @@ -27,9 +27,9 @@ #![cfg_attr(not(feature = "std"), no_std)] +use core::time::Duration; use cumulus_primitives_core::relay_chain::Slot; use sp_inherents::{Error, InherentData}; -use sp_std::time::Duration; pub use sp_timestamp::{InherentType, INHERENT_IDENTIFIER}; diff --git a/cumulus/primitives/utility/Cargo.toml b/cumulus/primitives/utility/Cargo.toml index a2fa2dd9806dca4743d13215ae4a30b7738567b7..82d18c8c0aac60b98fad565857fff5561a1ac21e 100644 --- a/cumulus/primitives/utility/Cargo.toml +++ b/cumulus/primitives/utility/Cargo.toml @@ -17,7 +17,6 @@ log = { workspace = true } frame-support = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } pallet-asset-conversion = { workspace = true } # Polkadot @@ -42,7 +41,6 @@ std = [ "polkadot-runtime-parachains/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", "xcm-builder/std", "xcm-executor/std", "xcm/std", diff --git a/cumulus/primitives/utility/src/lib.rs b/cumulus/primitives/utility/src/lib.rs index 64784eb36f846f7b325aaaa5ed72966e3d59a1b8..9d5bf4e231eb0d4893360d107d92079b775db1df 100644 --- a/cumulus/primitives/utility/src/lib.rs +++ b/cumulus/primitives/utility/src/lib.rs @@ -19,7 +19,11 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + +use alloc::{vec, vec::Vec}; use codec::Encode; +use core::marker::PhantomData; use cumulus_primitives_core::{MessageSendError, UpwardMessageSender}; use frame_support::{ defensive, @@ -33,7 +37,6 @@ use sp_runtime::{ traits::{Saturating, Zero}, SaturatedConversion, }; -use sp_std::{marker::PhantomData, prelude::*}; use xcm::{latest::prelude::*, VersionedLocation, VersionedXcm, WrapVersion}; use xcm_builder::{InspectMessageQueues, TakeRevenue}; use xcm_executor::{ @@ -803,7 +806,7 @@ mod test_trader { /// needed. #[cfg(feature = "runtime-benchmarks")] pub struct ToParentDeliveryHelper( - sp_std::marker::PhantomData<(XcmConfig, ExistentialDeposit, PriceForDelivery)>, + core::marker::PhantomData<(XcmConfig, ExistentialDeposit, PriceForDelivery)>, ); #[cfg(feature = "runtime-benchmarks")] diff --git a/cumulus/templates/xcm-bench-template.hbs b/cumulus/templates/xcm-bench-template.hbs index 5d0ded403f63496e93c4b118ea4137830c8a9b0d..119924bca2ee1fc1d4b568a63930bb13128c77e5 100644 --- a/cumulus/templates/xcm-bench-template.hbs +++ b/cumulus/templates/xcm-bench-template.hbs @@ -17,7 +17,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weights for `{{pallet}}`. pub struct WeightInfo(PhantomData); diff --git a/cumulus/test/relay-sproof-builder/Cargo.toml b/cumulus/test/relay-sproof-builder/Cargo.toml index 454266c90ba74008bbe33d65891e16fb516737e4..e266b5807081aa1bc3dd8d5793d1f03342f094fc 100644 --- a/cumulus/test/relay-sproof-builder/Cargo.toml +++ b/cumulus/test/relay-sproof-builder/Cargo.toml @@ -16,7 +16,6 @@ codec = { features = ["derive"], workspace = true } sp-runtime = { workspace = true } sp-state-machine = { workspace = true } sp-trie = { workspace = true } -sp-std = { workspace = true } # Polkadot polkadot-primitives = { workspace = true } @@ -32,6 +31,5 @@ std = [ "polkadot-primitives/std", "sp-runtime/std", "sp-state-machine/std", - "sp-std/std", "sp-trie/std", ] diff --git a/cumulus/test/relay-sproof-builder/src/lib.rs b/cumulus/test/relay-sproof-builder/src/lib.rs index fbd2692a36b466827376e0917adfc93aac10a739..d1016085c8073d67f2b8d50a224dce39711403f3 100644 --- a/cumulus/test/relay-sproof-builder/src/lib.rs +++ b/cumulus/test/relay-sproof-builder/src/lib.rs @@ -14,12 +14,14 @@ // You should have received a copy of the GNU General Public License // along with Cumulus. If not, see . +extern crate alloc; + +use alloc::collections::btree_map::BTreeMap; use cumulus_primitives_core::{ relay_chain, AbridgedHostConfiguration, AbridgedHrmpChannel, ParaId, }; use polkadot_primitives::UpgradeGoAhead; use sp_runtime::traits::HashingFor; -use sp_std::collections::btree_map::BTreeMap; use sp_trie::PrefixedMemoryDB; /// Builds a sproof (portmanteau of 'spoof' and 'proof') of the relay chain state. diff --git a/cumulus/test/runtime/Cargo.toml b/cumulus/test/runtime/Cargo.toml index d5582f2d2a23b28832a5731e1f0ae30ede21d266..54b83e2dfedae35583a7c8baf5308a9d709c1f4a 100644 --- a/cumulus/test/runtime/Cargo.toml +++ b/cumulus/test/runtime/Cargo.toml @@ -36,7 +36,6 @@ sp-offchain = { workspace = true } sp-runtime = { workspace = true } sp-session = { workspace = true } sp-consensus-aura = { workspace = true } -sp-std = { workspace = true } sp-transaction-pool = { workspace = true } sp-version = { workspace = true } @@ -87,7 +86,6 @@ std = [ "sp-offchain/std", "sp-runtime/std", "sp-session/std", - "sp-std/std", "sp-transaction-pool/std", "sp-version/std", "substrate-wasm-builder", diff --git a/cumulus/test/runtime/src/lib.rs b/cumulus/test/runtime/src/lib.rs index 97cb02ab779effdffedac4b4b1bebfe3e5970e5b..274f16ab630d6c0f9cff092b0ed79624e2a27a67 100644 --- a/cumulus/test/runtime/src/lib.rs +++ b/cumulus/test/runtime/src/lib.rs @@ -33,6 +33,10 @@ pub mod elastic_scaling { } mod test_pallet; + +extern crate alloc; + +use alloc::{vec, vec::Vec}; use frame_support::{derive_impl, traits::OnRuntimeUpgrade, PalletId}; use sp_api::{decl_runtime_apis, impl_runtime_apis}; pub use sp_consensus_aura::sr25519::AuthorityId as AuraId; @@ -44,7 +48,6 @@ use sp_runtime::{ transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, MultiSignature, }; -use sp_std::prelude::*; #[cfg(feature = "std")] use sp_version::NativeVersion; use sp_version::RuntimeVersion; @@ -454,7 +457,7 @@ impl_runtime_apis! { Runtime::metadata_at_version(version) } - fn metadata_versions() -> sp_std::vec::Vec { + fn metadata_versions() -> Vec { Runtime::metadata_versions() } } diff --git a/cumulus/test/runtime/src/test_pallet.rs b/cumulus/test/runtime/src/test_pallet.rs index 7f43f713fadc4c96776adfea90cdd17365a6b1cd..61195386ae79d2501965a8048a08c12143407348 100644 --- a/cumulus/test/runtime/src/test_pallet.rs +++ b/cumulus/test/runtime/src/test_pallet.rs @@ -42,7 +42,7 @@ pub mod pallet { #[pallet::weight(0)] pub fn set_custom_validation_head_data( _: OriginFor, - custom_header: sp_std::vec::Vec, + custom_header: alloc::vec::Vec, ) -> DispatchResult { cumulus_pallet_parachain_system::Pallet::::set_custom_validation_head_data( custom_header, @@ -79,7 +79,7 @@ pub mod pallet { #[pallet::genesis_config] pub struct GenesisConfig { #[serde(skip)] - pub _config: sp_std::marker::PhantomData, + pub _config: core::marker::PhantomData, } #[pallet::genesis_build] diff --git a/cumulus/xcm/xcm-emulator/src/lib.rs b/cumulus/xcm/xcm-emulator/src/lib.rs index 1a3f3930cb3478d9e7811c49becbfdd7874bbe48..8de3660c223627155a27f5ecc659a3ea030d7b02 100644 --- a/cumulus/xcm/xcm-emulator/src/lib.rs +++ b/cumulus/xcm/xcm-emulator/src/lib.rs @@ -14,6 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . +extern crate alloc; + pub use codec::{Decode, Encode, EncodeLike, MaxEncodedLen}; pub use lazy_static::lazy_static; pub use log; @@ -24,6 +26,8 @@ pub use std::{ }; // Substrate +pub use alloc::collections::vec_deque::VecDeque; +pub use core::{cell::RefCell, fmt::Debug}; pub use cumulus_primitives_core::AggregateMessageOrigin as CumulusAggregateMessageOrigin; pub use frame_support::{ assert_ok, @@ -44,7 +48,6 @@ pub use sp_core::{parameter_types, sr25519, storage::Storage, Pair}; pub use sp_crypto_hashing::blake2_256; pub use sp_io::TestExternalities; pub use sp_runtime::BoundedSlice; -pub use sp_std::{cell::RefCell, collections::vec_deque::VecDeque, fmt::Debug}; pub use sp_tracing; // Cumulus diff --git a/docker/dockerfiles/bridges_zombienet_tests_injected.Dockerfile b/docker/dockerfiles/bridges_zombienet_tests_injected.Dockerfile index e17952ccee804d5ff82339c1770f96f28c1cdab8..60698de1d6addf53385ba6e3f30b36e9a1d7f784 100644 --- a/docker/dockerfiles/bridges_zombienet_tests_injected.Dockerfile +++ b/docker/dockerfiles/bridges_zombienet_tests_injected.Dockerfile @@ -1,7 +1,7 @@ # this image is built on top of existing Zombienet image ARG ZOMBIENET_IMAGE # this image uses substrate-relay image built elsewhere -ARG SUBSTRATE_RELAY_IMAGE=docker.io/paritytech/substrate-relay:v1.6.4 +ARG SUBSTRATE_RELAY_IMAGE=docker.io/paritytech/substrate-relay:v1.6.6 # metadata ARG VCS_REF diff --git a/docs/sdk/src/guides/enable_elastic_scaling_mvp.rs b/docs/sdk/src/guides/enable_elastic_scaling_mvp.rs new file mode 100644 index 0000000000000000000000000000000000000000..bc4f36c271fe3c063f85c9debb32fd78f7e33efa --- /dev/null +++ b/docs/sdk/src/guides/enable_elastic_scaling_mvp.rs @@ -0,0 +1,142 @@ +//! # Enable elastic scaling MVP for a parachain +//! +//!

This guide assumes full familiarity with Asynchronous Backing and its +//! terminology, as defined in https://wiki.polkadot.network/docs/maintain-guides-async-backing. +//! Furthermore, the parachain should have already been upgraded according to the guide.
+//! +//! ## Quick introduction to elastic scaling +//! +//! [Elastic scaling](https://polkadot.network/blog/elastic-scaling-streamling-growth-on-polkadot) +//! is a feature that will enable parachains to seamlessly scale up/down the number of used cores. +//! This can be desirable in order to increase the compute or storage throughput of a parachain or +//! to lower the latency between a transaction being submitted and it getting built in a parachain +//! block. +//! +//! At present, with Asynchronous Backing enabled, a parachain can only include a block on the relay +//! chain every 6 seconds, irregardless of how many cores the parachain acquires. Elastic scaling +//! builds further on the 10x throughput increase of Async Backing, enabling collators to submit up +//! to 3 parachain blocks per relay chain block, resulting in a further 3x throughput increase. +//! +//! ## Current limitations of the MVP +//! +//! The full implementation of elastic scaling spans across the entire relay/parachain stack and is +//! still [work in progress](https://github.com/paritytech/polkadot-sdk/issues/1829). +//! The MVP is still considered experimental software, so stability is not guaranteed. +//! If you encounter any problems, +//! [please open an issue](https://github.com/paritytech/polkadot-sdk/issues). +//! Below are described the current limitations of the MVP: +//! +//! 1. **Limited core count**. Parachain block authoring is sequential, so the second block will +//! start being built only after the previous block is imported. The current block production is +//! capped at 2 seconds of execution. Therefore, assuming the full 2 seconds are used, a +//! parachain can only utilise at most 3 cores in a relay chain slot of 6 seconds. If the full +//! execution time is not being used, higher core counts can be achieved. +//! 2. **Single collator requirement for consistently scaling beyond a core at full authorship +//! duration of 2 seconds per block.** Using the current implementation with multiple collators +//! adds additional latency to the block production pipeline. Assuming block execution takes +//! about the same as authorship, the additional overhead is equal the duration of the authorship +//! plus the block announcement. Each collator must first import the previous block before +//! authoring a new one, so it is clear that the highest throughput can be achieved using a +//! single collator. Experiments show that the peak performance using more than one collator +//! (measured up to 10 collators) is utilising 2 cores with authorship time of 1.3 seconds per +//! block, which leaves 400ms for networking overhead. This would allow for 2.6 seconds of +//! execution, compared to the 2 seconds async backing enabled. +//! [More experiments](https://github.com/paritytech/polkadot-sdk/issues/4696) are being +//! conducted in this space. +//! 3. **Trusted collator set.** The collator set needs to be trusted until there’s a mitigation +//! that would prevent or deter multiple collators from submitting the same collation to multiple +//! backing groups. A solution is being discussed +//! [here](https://github.com/polkadot-fellows/RFCs/issues/92). +//! 4. **Fixed scaling.** For true elasticity, the parachain must be able to seamlessly acquire or +//! sell coretime as the user demand grows and shrinks over time, in an automated manner. This is +//! currently lacking - a parachain can only scale up or down by “manually” acquiring coretime. +//! This is not in the scope of the relay chain functionality. Parachains can already start +//! implementing such autoscaling, but we aim to provide a framework/examples for developing +//! autoscaling strategies. +//! +//! Another hard limitation that is not envisioned to ever be lifted is that parachains which create +//! forks will generally not be able to utilise the full number of cores they acquire. +//! +//! ## Using elastic scaling MVP +//! +//! ### Prerequisites +//! +//! - Ensure Asynchronous Backing is enabled on the network and you have enabled it on the parachain +//! using [`crate::guides::async_backing_guide`]. +//! - Ensure the `AsyncBackingParams.max_candidate_depth` value is configured to a value that is at +//! least double the maximum targeted parachain velocity. For example, if the parachain will build +//! at most 3 candidates per relay chain block, the `max_candidate_depth` should be at least 6. +//! - Use a trusted single collator for maximum throughput. +//! - Ensure enough coretime is assigned to the parachain. For maximum throughput the upper bound is +//! 3 cores. +//! +//!
Phase 1 is not needed if using the `polkadot-parachain` binary built +//! from the latest polkadot-sdk release! Simply pass the `--experimental-use-slot-based` parameter +//! to the command line and jump to Phase 2.
+//! +//! The following steps assume using the cumulus parachain template. +//! +//! ### Phase 1 - (For custom parachain node) Update Parachain Node +//! +//! This assumes you are using +//! [the latest parachain template](https://github.com/paritytech/polkadot-sdk/tree/master/templates/parachain). +//! +//! This phase consists of plugging in the new slot-based collator. +//! +//! 1. In `node/src/service.rs` import the slot based collator instead of the lookahead collator. +#![doc = docify::embed!("../../cumulus/polkadot-parachain/src/service.rs", slot_based_colator_import)] +//! +//! 2. In `start_consensus()` +//! - Remove the `overseer_handle` param (also remove the +//! `OverseerHandle` type import if it’s not used elsewhere). +//! - Rename `AuraParams` to `SlotBasedParams`, remove the `overseer_handle` field and add a +//! `slot_drift` field with a value of `Duration::from_secs(1)`. +//! - Replace the single future returned by `aura::run` with the two futures returned by it and +//! spawn them as separate tasks: +#![doc = docify::embed!("../../cumulus/polkadot-parachain/src/service.rs", launch_slot_based_collator)] +//! +//! 3. In `start_parachain_node()` remove the `overseer_handle` param passed to `start_consensus`. +//! +//! ### Phase 2 - Activate fixed factor scaling in the runtime +//! +//! This phase consists of a couple of changes needed to be made to the parachain’s runtime in order +//! to utilise fixed factor scaling. +//! +//! First of all, you need to decide the upper limit to how many parachain blocks you need to +//! produce per relay chain block (in direct correlation with the number of acquired cores). This +//! should be either 1 (no scaling), 2 or 3. This is called the parachain velocity. +//! +//! If you configure a velocity which is different from the number of assigned cores, the measured +//! velocity in practice will be the minimum of these two. +//! +//! The chosen velocity will also be used to compute: +//! - The slot duration, by dividing the 6000 ms duration of the relay chain slot duration by the +//! velocity. +//! - The unincluded segment capacity, by multiplying the velocity with 2 and adding 1 to +//! it. +//! +//! Let’s assume a desired maximum velocity of 3 parachain blocks per relay chain block. The needed +//! changes would all be done in `runtime/src/lib.rs`: +//! +//! 1. Rename `BLOCK_PROCESSING_VELOCITY` to `MAX_BLOCK_PROCESSING_VELOCITY` and increase it to the +//! desired value. In this example, 3. +//! +//! ```ignore +//! const MAX_BLOCK_PROCESSING_VELOCITY: u32 = 3; +//! ``` +//! +//! 2. Set the `MILLISECS_PER_BLOCK` to the desired value. +//! +//! ```ignore +//! const MILLISECS_PER_BLOCK: u32 = +//! RELAY_CHAIN_SLOT_DURATION_MILLIS / MAX_BLOCK_PROCESSING_VELOCITY; +//! ``` +//! Note: for a parachain which measures time in terms of its own block number, changing block +//! time may cause complications, requiring additional changes. See here more information: +//! [`crate::guides::async_backing_guide#timing-by-block-number`]. +//! +//! 3. Increase the `UNINCLUDED_SEGMENT_CAPACITY` to the desired value. +//! +//! ```ignore +//! const UNINCLUDED_SEGMENT_CAPACITY: u32 = 2 * MAX_BLOCK_PROCESSING_VELOCITY + 1; +//! ``` diff --git a/docs/sdk/src/guides/mod.rs b/docs/sdk/src/guides/mod.rs index 8296ed447e143d3fadcfbb2157786eea8934947f..9384f4c82ab3e37e5d15e0cb853c7d01731b4b41 100644 --- a/docs/sdk/src/guides/mod.rs +++ b/docs/sdk/src/guides/mod.rs @@ -41,3 +41,6 @@ pub mod async_backing_guide; /// How to enable metadata hash verification in the runtime. pub mod enable_metadata_hash; + +/// How to enable elastic scaling MVP on a parachain. +pub mod enable_elastic_scaling_mvp; diff --git a/docs/sdk/src/reference_docs/chain_spec_runtime/Cargo.toml b/docs/sdk/src/reference_docs/chain_spec_runtime/Cargo.toml index 9cf921a492a515ee424f0e47674a9aef2414b034..02849571203285d5a9bbc19d4d3aecad8495c214 100644 --- a/docs/sdk/src/reference_docs/chain_spec_runtime/Cargo.toml +++ b/docs/sdk/src/reference_docs/chain_spec_runtime/Cargo.toml @@ -33,7 +33,6 @@ pallet-transaction-payment-rpc-runtime-api = { workspace = true } sp-genesis-builder = { workspace = true } sp-runtime = { features = ["serde"], workspace = true } sp-core = { workspace = true } -sp-std = { workspace = true } sp-keyring = { workspace = true } sp-application-crypto = { features = ["serde"], workspace = true } @@ -63,7 +62,6 @@ std = [ "sp-genesis-builder/std", "sp-keyring/std", "sp-runtime/std", - "sp-std/std", "serde/std", "serde_json/std", diff --git a/docs/sdk/src/reference_docs/chain_spec_runtime/src/lib.rs b/docs/sdk/src/reference_docs/chain_spec_runtime/src/lib.rs index 4606104fb9680628f10dc4ff7738f9c4740ced62..e7effce1bd6697196c3af45bde27e811250d0e5f 100644 --- a/docs/sdk/src/reference_docs/chain_spec_runtime/src/lib.rs +++ b/docs/sdk/src/reference_docs/chain_spec_runtime/src/lib.rs @@ -19,6 +19,8 @@ //! A minimal runtime that shows runtime genesis state. +extern crate alloc; + pub mod pallets; pub mod presets; pub mod runtime; diff --git a/docs/sdk/src/reference_docs/chain_spec_runtime/src/pallets.rs b/docs/sdk/src/reference_docs/chain_spec_runtime/src/pallets.rs index be4455aa21979f8915d32b0a85c84e278ba3b83f..2ff2d9539e2dbdd13997f925474ecbaf5a2836c7 100644 --- a/docs/sdk/src/reference_docs/chain_spec_runtime/src/pallets.rs +++ b/docs/sdk/src/reference_docs/chain_spec_runtime/src/pallets.rs @@ -17,6 +17,7 @@ //! Pallets for the chain-spec demo runtime. +use alloc::vec::Vec; use frame::prelude::*; #[docify::export] diff --git a/docs/sdk/src/reference_docs/chain_spec_runtime/src/presets.rs b/docs/sdk/src/reference_docs/chain_spec_runtime/src/presets.rs index c51947f6cc7cb0c53f8fbf52f2f80a370b1f681c..02c2d90f7c827f51dfe913fd0743109b9f96618a 100644 --- a/docs/sdk/src/reference_docs/chain_spec_runtime/src/presets.rs +++ b/docs/sdk/src/reference_docs/chain_spec_runtime/src/presets.rs @@ -18,10 +18,10 @@ //! Presets for the chain-spec demo runtime. use crate::pallets::{FooEnum, SomeFooData1, SomeFooData2}; +use alloc::vec; use serde_json::{json, to_string, Value}; use sp_application_crypto::Ss58Codec; use sp_keyring::AccountKeyring; -use sp_std::vec; /// A demo preset with strings only. pub const PRESET_1: &str = "preset_1"; @@ -122,7 +122,7 @@ fn preset_invalid() -> Value { /// /// If no preset with given `id` exits `None` is returned. #[docify::export] -pub fn get_builtin_preset(id: &sp_genesis_builder::PresetId) -> Option> { +pub fn get_builtin_preset(id: &sp_genesis_builder::PresetId) -> Option> { let preset = match id.try_into() { Ok(PRESET_1) => preset_1(), Ok(PRESET_2) => preset_2(), diff --git a/docs/sdk/src/reference_docs/chain_spec_runtime/src/runtime.rs b/docs/sdk/src/reference_docs/chain_spec_runtime/src/runtime.rs index 6d9bc1260b11fa79004b40ded4ab20343cf29037..c45f0126337e5a42b83fee6e80c5be04c03c1d73 100644 --- a/docs/sdk/src/reference_docs/chain_spec_runtime/src/runtime.rs +++ b/docs/sdk/src/reference_docs/chain_spec_runtime/src/runtime.rs @@ -25,6 +25,7 @@ use crate::{ pallets::{pallet_bar, pallet_foo}, presets::*, }; +use alloc::{vec, vec::Vec}; use frame::{ deps::frame_support::{ genesis_builder_helper::{build_state, get_preset}, diff --git a/master.wasm b/master.wasm deleted file mode 100644 index 7ebb14371243afa4956a107374b27a4e686f0360..0000000000000000000000000000000000000000 Binary files a/master.wasm and /dev/null differ diff --git a/modified.wasm b/modified.wasm deleted file mode 100644 index 7ebb14371243afa4956a107374b27a4e686f0360..0000000000000000000000000000000000000000 Binary files a/modified.wasm and /dev/null differ diff --git a/polkadot/core-primitives/Cargo.toml b/polkadot/core-primitives/Cargo.toml index 800434670f83bada72c95423081d89cd1ddeb46d..42ca27953738e5c06dc5cb904323ee6a5bbc91f2 100644 --- a/polkadot/core-primitives/Cargo.toml +++ b/polkadot/core-primitives/Cargo.toml @@ -11,7 +11,6 @@ workspace = true [dependencies] sp-core = { workspace = true } -sp-std = { workspace = true } sp-runtime = { workspace = true } scale-info = { features = ["derive"], workspace = true } codec = { features = ["derive"], workspace = true } @@ -23,5 +22,4 @@ std = [ "scale-info/std", "sp-core/std", "sp-runtime/std", - "sp-std/std", ] diff --git a/polkadot/core-primitives/src/lib.rs b/polkadot/core-primitives/src/lib.rs index 072c045a8c7039da82e0128d00e1886a7817ec4d..666636def46048ad2d97c48d5b82591df3108fcc 100644 --- a/polkadot/core-primitives/src/lib.rs +++ b/polkadot/core-primitives/src/lib.rs @@ -20,6 +20,8 @@ //! //! These core Polkadot types are used by the relay chain and the Parachains. +extern crate alloc; + use codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_runtime::{ @@ -81,8 +83,8 @@ impl std::fmt::Display for CandidateHash { } } -impl sp_std::fmt::Debug for CandidateHash { - fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { +impl core::fmt::Debug for CandidateHash { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{:?}", self.0) } } @@ -119,7 +121,7 @@ pub type Remark = [u8; 32]; /// A message sent from the relay-chain down to a parachain. /// /// The size of the message is limited by the `config.max_downward_message_size` parameter. -pub type DownwardMessage = sp_std::vec::Vec; +pub type DownwardMessage = alloc::vec::Vec; /// A wrapped version of `DownwardMessage`. The difference is that it has attached the block number /// when the message was sent. @@ -139,7 +141,7 @@ pub struct InboundHrmpMessage { /// enacted. pub sent_at: BlockNumber, /// The message payload. - pub data: sp_std::vec::Vec, + pub data: alloc::vec::Vec, } /// An HRMP message seen from the perspective of a sender. @@ -148,7 +150,7 @@ pub struct OutboundHrmpMessage { /// The para that will get this message in its downward message queue. pub recipient: Id, /// The message payload. - pub data: sp_std::vec::Vec, + pub data: alloc::vec::Vec, } /// `V2` primitives. diff --git a/polkadot/node/core/pvf/Cargo.toml b/polkadot/node/core/pvf/Cargo.toml index 7444f7927f568359fe2a33392468b1f38d1e400f..d603af04bf061fc16dfb00979e3aaf85b21adb60 100644 --- a/polkadot/node/core/pvf/Cargo.toml +++ b/polkadot/node/core/pvf/Cargo.toml @@ -60,7 +60,7 @@ test-parachain-adder = { workspace = true } test-parachain-halt = { workspace = true } [target.'cfg(target_os = "linux")'.dev-dependencies] -libc = "0.2.153" +libc = "0.2.155" procfs = "0.16.0" rusty-fork = "0.3.0" sc-sysinfo = { workspace = true, default-features = true } diff --git a/polkadot/node/core/pvf/tests/it/main.rs b/polkadot/node/core/pvf/tests/it/main.rs index d62a1aef230990057c5c408a840f51bc66a5029f..9ad486657512c7a6dda6c3b907500c074aef7433 100644 --- a/polkadot/node/core/pvf/tests/it/main.rs +++ b/polkadot/node/core/pvf/tests/it/main.rs @@ -523,20 +523,17 @@ async fn prepare_can_run_serially() { #[cfg(all(feature = "ci-only-tests", target_os = "linux"))] #[tokio::test] async fn all_security_features_work() { - // Landlock is only available starting Linux 5.13, and we may be testing on an old kernel. let can_enable_landlock = { - let sysinfo = sc_sysinfo::gather_sysinfo(); - // The version will look something like "5.15.0-87-generic". - let version = sysinfo.linux_kernel.unwrap(); - let version_split: Vec<&str> = version.split(".").collect(); - let major: u32 = version_split[0].parse().unwrap(); - let minor: u32 = version_split[1].parse().unwrap(); - if major >= 6 { - true - } else if major == 5 { - minor >= 13 + let res = unsafe { libc::syscall(libc::SYS_landlock_create_ruleset, 0usize, 0usize, 1u32) }; + if res == -1 { + let err = std::io::Error::last_os_error().raw_os_error().unwrap(); + if err == libc::ENOSYS { + false + } else { + panic!("Unexpected errno from landlock check: {err}"); + } } else { - false + true } }; diff --git a/polkadot/node/malus/src/interceptor.rs b/polkadot/node/malus/src/interceptor.rs index b44ffc8956b52581f0d27eeb7e794ffacc922fb7..2181118646d568e2b59db6dbf61e24dfac90257b 100644 --- a/polkadot/node/malus/src/interceptor.rs +++ b/polkadot/node/malus/src/interceptor.rs @@ -90,6 +90,10 @@ where >::Error: std::fmt::Debug, { async fn send_message(&mut self, msg: OutgoingMessage) { + self.send_message_with_priority::(msg).await; + } + + async fn send_message_with_priority(&mut self, msg: OutgoingMessage) { let msg = < <>::Message as overseer::AssociateOutgoing >::OutgoingMessages as From>::from(msg); @@ -103,7 +107,14 @@ where } } - fn try_send_message(&mut self, msg: OutgoingMessage) -> Result<(), TrySendError> { + fn try_send_message( + &mut self, + msg: OutgoingMessage, + ) -> Result<(), polkadot_node_subsystem_util::metered::TrySendError> { + self.try_send_message_with_priority::(msg) + } + + fn try_send_message_with_priority(&mut self, msg: OutgoingMessage) -> Result<(), TrySendError> { let msg = < <>::Message as overseer::AssociateOutgoing >::OutgoingMessages as From>::from(msg); diff --git a/polkadot/node/network/approval-distribution/src/lib.rs b/polkadot/node/network/approval-distribution/src/lib.rs index 369d82b45b094b30f0b65d72d54d5c14c1e28440..d48fb08a311c7496556eec797cbd2bd751a1472a 100644 --- a/polkadot/node/network/approval-distribution/src/lib.rs +++ b/polkadot/node/network/approval-distribution/src/lib.rs @@ -1431,6 +1431,21 @@ impl State { let required_routing = topology.map_or(RequiredRouting::PendingTopology, |t| { t.local_grid_neighbors().required_routing_by_index(validator_index, local) }); + // Peers that we will send the assignment to. + let mut peers = HashSet::new(); + + let peers_to_route_to = topology + .as_ref() + .map(|t| t.peers_to_route(required_routing)) + .unwrap_or_default(); + + for peer in peers_to_route_to { + if !entry.known_by.contains_key(&peer) { + continue + } + + peers.insert(peer); + } // All the peers that know the relay chain block. let peers_to_filter = entry.known_by(); @@ -1456,20 +1471,13 @@ impl State { let n_peers_total = self.peer_views.len(); let source_peer = source.peer_id(); - // Peers that we will send the assignment to. - let mut peers = Vec::new(); - // Filter destination peers for peer in peers_to_filter.into_iter() { if Some(peer) == source_peer { continue } - if let Some(true) = topology - .as_ref() - .map(|t| t.local_grid_neighbors().route_to_peer(required_routing, &peer)) - { - peers.push(peer); + if peers.contains(&peer) { continue } @@ -1485,7 +1493,11 @@ impl State { if route_random { approval_entry.routing_info_mut().mark_randomly_sent(peer); - peers.push(peer); + peers.insert(peer); + } + + if approval_entry.routing_info().random_routing.is_complete() { + break } } diff --git a/polkadot/node/network/approval-distribution/src/tests.rs b/polkadot/node/network/approval-distribution/src/tests.rs index 5ad034464767efc3757c3812967d88c71a6fbdd3..2d08807f97b60b817657a53af6a351002c04ff73 100644 --- a/polkadot/node/network/approval-distribution/src/tests.rs +++ b/polkadot/node/network/approval-distribution/src/tests.rs @@ -2404,7 +2404,7 @@ fn propagates_locally_generated_assignment_to_both_dimensions() { let assignments = vec![(cert.clone(), candidate_index)]; let approvals = vec![approval.clone()]; - let assignment_sent_peers = assert_matches!( + let mut assignment_sent_peers = assert_matches!( overseer_recv(overseer).await, AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage( sent_peers, @@ -2428,12 +2428,14 @@ fn propagates_locally_generated_assignment_to_both_dimensions() { assert_matches!( overseer_recv(overseer).await, AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage( - sent_peers, + mut sent_peers, Versioned::V1(protocol_v1::ValidationProtocol::ApprovalDistribution( protocol_v1::ApprovalDistributionMessage::Approvals(sent_approvals) )) )) => { // Random sampling is reused from the assignment. + sent_peers.sort(); + assignment_sent_peers.sort(); assert_eq!(sent_peers, assignment_sent_peers); assert_eq!(sent_approvals, approvals); } @@ -2678,7 +2680,7 @@ fn propagates_to_required_after_connect() { let assignments = vec![(cert.clone(), candidate_index)]; let approvals = vec![approval.clone()]; - let assignment_sent_peers = assert_matches!( + let mut assignment_sent_peers = assert_matches!( overseer_recv(overseer).await, AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage( sent_peers, @@ -2702,12 +2704,14 @@ fn propagates_to_required_after_connect() { assert_matches!( overseer_recv(overseer).await, AllMessages::NetworkBridgeTx(NetworkBridgeTxMessage::SendValidationMessage( - sent_peers, + mut sent_peers, Versioned::V1(protocol_v1::ValidationProtocol::ApprovalDistribution( protocol_v1::ApprovalDistributionMessage::Approvals(sent_approvals) )) )) => { // Random sampling is reused from the assignment. + sent_peers.sort(); + assignment_sent_peers.sort(); assert_eq!(sent_peers, assignment_sent_peers); assert_eq!(sent_approvals, approvals); } diff --git a/polkadot/node/network/availability-distribution/src/tests/state.rs b/polkadot/node/network/availability-distribution/src/tests/state.rs index befbff0a2f27efc0f91f1c23f9bdcc1ded704a8f..97e616f79fb759c0800946b762aca03acba9c4bc 100644 --- a/polkadot/node/network/availability-distribution/src/tests/state.rs +++ b/polkadot/node/network/availability-distribution/src/tests/state.rs @@ -216,7 +216,7 @@ impl TestState { // Test will fail if this does not happen until timeout. let mut remaining_stores = self.valid_chunks.len(); - let TestSubsystemContextHandle { tx, mut rx } = harness.virtual_overseer; + let TestSubsystemContextHandle { tx, mut rx, .. } = harness.virtual_overseer; // Spawning necessary as incoming queue can only hold a single item, we don't want to dead // lock ;-) diff --git a/polkadot/node/network/bridge/src/rx/mod.rs b/polkadot/node/network/bridge/src/rx/mod.rs index 84e935366d0cb7734d5b0aec102032aa0c85edec..56965ce6ba404c2e6fc2b189ce75ac9122cbf67c 100644 --- a/polkadot/node/network/bridge/src/rx/mod.rs +++ b/polkadot/node/network/bridge/src/rx/mod.rs @@ -1135,13 +1135,33 @@ async fn dispatch_validation_events_to_all( I: IntoIterator>, I::IntoIter: Send, { + macro_rules! send_message { + ($event:expr, $message:ident) => { + if let Ok(event) = $event.focus() { + let has_high_priority = matches!( + event, + // NetworkBridgeEvent::OurViewChange(..) must also be here, + // but it is sent via an unbounded channel. + // See https://github.com/paritytech/polkadot-sdk/issues/824 + NetworkBridgeEvent::PeerConnected(..) | + NetworkBridgeEvent::PeerDisconnected(..) | + NetworkBridgeEvent::PeerViewChange(..) + ); + let message = $message::from(event); + if has_high_priority { + sender.send_message_with_priority::(message).await; + } else { + sender.send_message(message).await; + } + } + }; + } + for event in events { - sender - .send_messages(event.focus().map(StatementDistributionMessage::from)) - .await; - sender.send_messages(event.focus().map(BitfieldDistributionMessage::from)).await; - sender.send_messages(event.focus().map(ApprovalDistributionMessage::from)).await; - sender.send_messages(event.focus().map(GossipSupportMessage::from)).await; + send_message!(event, StatementDistributionMessage); + send_message!(event, BitfieldDistributionMessage); + send_message!(event, ApprovalDistributionMessage); + send_message!(event, GossipSupportMessage); } } diff --git a/polkadot/node/network/bridge/src/rx/tests.rs b/polkadot/node/network/bridge/src/rx/tests.rs index 6182bf3d883b5be19231d534babf1c70973da00d..392ff7391a1c1ddded8cfde1bce96adc3a27476a 100644 --- a/polkadot/node/network/bridge/src/rx/tests.rs +++ b/polkadot/node/network/bridge/src/rx/tests.rs @@ -880,6 +880,8 @@ fn peer_view_updates_sent_via_overseer() { &mut virtual_overseer, ) .await; + + assert_eq!(virtual_overseer.message_counter.with_high_priority(), 8); } network_handle @@ -895,6 +897,7 @@ fn peer_view_updates_sent_via_overseer() { &mut virtual_overseer, ) .await; + assert_eq!(virtual_overseer.message_counter.with_high_priority(), 12); virtual_overseer }); } @@ -930,6 +933,8 @@ fn peer_messages_sent_via_overseer() { &mut virtual_overseer, ) .await; + + assert_eq!(virtual_overseer.message_counter.with_high_priority(), 8); } let approval_distribution_message = @@ -970,6 +975,7 @@ fn peer_messages_sent_via_overseer() { &mut virtual_overseer, ) .await; + assert_eq!(virtual_overseer.message_counter.with_high_priority(), 12); virtual_overseer }); } @@ -1008,6 +1014,8 @@ fn peer_disconnect_from_just_one_peerset() { &mut virtual_overseer, ) .await; + + assert_eq!(virtual_overseer.message_counter.with_high_priority(), 8); } { @@ -1036,6 +1044,7 @@ fn peer_disconnect_from_just_one_peerset() { &mut virtual_overseer, ) .await; + assert_eq!(virtual_overseer.message_counter.with_high_priority(), 12); // to show that we're still connected on the collation protocol, send a view update. @@ -1094,6 +1103,8 @@ fn relays_collation_protocol_messages() { &mut virtual_overseer, ) .await; + + assert_eq!(virtual_overseer.message_counter.with_high_priority(), 8); } { @@ -1201,6 +1212,8 @@ fn different_views_on_different_peer_sets() { &mut virtual_overseer, ) .await; + + assert_eq!(virtual_overseer.message_counter.with_high_priority(), 8); } { @@ -1247,6 +1260,8 @@ fn different_views_on_different_peer_sets() { ) .await; + assert_eq!(virtual_overseer.message_counter.with_high_priority(), 12); + assert_sends_collation_event_to_all( NetworkBridgeEvent::PeerViewChange(peer, view_b.clone()), &mut virtual_overseer, @@ -1481,6 +1496,8 @@ fn network_protocol_versioning_subsystem_msg() { &mut virtual_overseer, ) .await; + + assert_eq!(virtual_overseer.message_counter.with_high_priority(), 8); } let approval_distribution_message = diff --git a/polkadot/node/network/protocol/src/grid_topology.rs b/polkadot/node/network/protocol/src/grid_topology.rs index a14d24610722bfad2d26df9526d8e6d7411e6f68..4dd7d29fc25cde5a010e6c4c28969c142dba6098 100644 --- a/polkadot/node/network/protocol/src/grid_topology.rs +++ b/polkadot/node/network/protocol/src/grid_topology.rs @@ -313,6 +313,23 @@ impl SessionGridTopologyEntry { self.topology.is_validator(peer) } + /// Returns the list of peers to route based on the required routing. + pub fn peers_to_route(&self, required_routing: RequiredRouting) -> Vec { + match required_routing { + RequiredRouting::All => self.topology.peer_ids.iter().copied().collect(), + RequiredRouting::GridX => self.local_neighbors.peers_x.iter().copied().collect(), + RequiredRouting::GridY => self.local_neighbors.peers_y.iter().copied().collect(), + RequiredRouting::GridXY => self + .local_neighbors + .peers_x + .iter() + .chain(self.local_neighbors.peers_y.iter()) + .copied() + .collect(), + RequiredRouting::None | RequiredRouting::PendingTopology => Vec::new(), + } + } + /// Updates the known peer ids for the passed authorities ids. pub fn update_authority_ids( &mut self, @@ -524,6 +541,11 @@ impl RandomRouting { pub fn inc_sent(&mut self) { self.sent += 1 } + + /// Returns `true` if we already took all the necessary samples. + pub fn is_complete(&self) -> bool { + self.sent >= self.target + } } /// Routing mode diff --git a/polkadot/node/network/statement-distribution/benches/statement-distribution-regression-bench.rs b/polkadot/node/network/statement-distribution/benches/statement-distribution-regression-bench.rs index 9cbe385e3f42ee5be7dc0e5cda44bdbc92930828..4e7206e0a366d0ff85728313f307ec4a8caf81ea 100644 --- a/polkadot/node/network/statement-distribution/benches/statement-distribution-regression-bench.rs +++ b/polkadot/node/network/statement-distribution/benches/statement-distribution-regression-bench.rs @@ -63,7 +63,7 @@ fn main() -> Result<(), String> { ("Received from peers", 106.4000, 0.001), ("Sent to peers", 127.9100, 0.001), ])); - messages.extend(average_usage.check_cpu_usage(&[("statement-distribution", 0.0390, 0.1)])); + messages.extend(average_usage.check_cpu_usage(&[("statement-distribution", 0.0374, 0.1)])); if messages.is_empty() { Ok(()) diff --git a/polkadot/node/network/statement-distribution/src/lib.rs b/polkadot/node/network/statement-distribution/src/lib.rs index 4d56c795f13b29949a7a3b3e7f9bfc85e89ab274..33431eb1edce585943100e4c23d7234a39779f9c 100644 --- a/polkadot/node/network/statement-distribution/src/lib.rs +++ b/polkadot/node/network/statement-distribution/src/lib.rs @@ -284,7 +284,14 @@ impl StatementDistributionSubsystem { ); }, MuxedMessage::Response(result) => { - v2::handle_response(&mut ctx, &mut state, result, &mut self.reputation).await; + v2::handle_response( + &mut ctx, + &mut state, + result, + &mut self.reputation, + &self.metrics, + ) + .await; }, MuxedMessage::RetryRequest(()) => { // A pending request is ready to retry. This is only a signal to call @@ -320,7 +327,8 @@ impl StatementDistributionSubsystem { let mode = prospective_parachains_mode(ctx.sender(), activated.hash).await?; if let ProspectiveParachainsMode::Enabled { .. } = mode { let res = - v2::handle_active_leaves_update(ctx, state, activated, mode).await; + v2::handle_active_leaves_update(ctx, state, activated, mode, &metrics) + .await; // Regardless of the result of leaf activation, we always prune before // handling it to avoid leaks. v2::handle_deactivate_leaves(state, &deactivated); @@ -370,6 +378,7 @@ impl StatementDistributionSubsystem { relay_parent, statement, &mut self.reputation, + &self.metrics, ) .await?; } @@ -428,11 +437,24 @@ impl StatementDistributionSubsystem { if target.targets_current() { // pass to v2. - v2::handle_network_update(ctx, state, event, &mut self.reputation).await; + v2::handle_network_update( + ctx, + state, + event, + &mut self.reputation, + &self.metrics, + ) + .await; } }, StatementDistributionMessage::Backed(candidate_hash) => { - crate::v2::handle_backed_candidate_message(ctx, state, candidate_hash).await; + crate::v2::handle_backed_candidate_message( + ctx, + state, + candidate_hash, + &self.metrics, + ) + .await; }, }, } diff --git a/polkadot/node/network/statement-distribution/src/metrics.rs b/polkadot/node/network/statement-distribution/src/metrics.rs index 1bc994174263905d3058154ead29eaaa16bd2ad4..e21fff1e6421e3c90df07c6c1c1237721ce33760 100644 --- a/polkadot/node/network/statement-distribution/src/metrics.rs +++ b/polkadot/node/network/statement-distribution/src/metrics.rs @@ -25,13 +25,13 @@ const HISTOGRAM_LATENCY_BUCKETS: &[f64] = &[ #[derive(Clone)] struct MetricsInner { // V1 - statements_distributed: prometheus::Counter, sent_requests: prometheus::Counter, received_responses: prometheus::CounterVec, network_bridge_update: prometheus::HistogramVec, statements_unexpected: prometheus::CounterVec, created_message_size: prometheus::Gauge, // V1+ + statements_distributed: prometheus::Counter, active_leaves_update: prometheus::Histogram, share: prometheus::Histogram, // V2+ @@ -51,6 +51,13 @@ impl Metrics { } } + /// Update statements distributed counter by an amount + pub fn on_statements_distributed(&self, n: usize) { + if let Some(metrics) = &self.0 { + metrics.statements_distributed.inc_by(n as u64); + } + } + /// Update sent requests counter /// This counter is updated merely for the statements sent via request/response method, /// meaning that it counts large statements only diff --git a/polkadot/node/network/statement-distribution/src/v2/mod.rs b/polkadot/node/network/statement-distribution/src/v2/mod.rs index 2bb9c82c6a6fa00a84b5274a12f7e79398ca89f3..47d350849b206913b9e493cd9befd6086d0c4e7b 100644 --- a/polkadot/node/network/statement-distribution/src/v2/mod.rs +++ b/polkadot/node/network/statement-distribution/src/v2/mod.rs @@ -400,6 +400,7 @@ pub(crate) async fn handle_network_update( state: &mut State, update: NetworkBridgeEvent, reputation: &mut ReputationAggregator, + metrics: &Metrics, ) { match update { NetworkBridgeEvent::PeerConnected(peer_id, role, protocol_version, mut authority_ids) => { @@ -483,23 +484,33 @@ pub(crate) async fn handle_network_update( net_protocol::StatementDistributionMessage::V3( protocol_v3::StatementDistributionMessage::Statement(relay_parent, statement), ) => - handle_incoming_statement(ctx, state, peer_id, relay_parent, statement, reputation) - .await, + handle_incoming_statement( + ctx, + state, + peer_id, + relay_parent, + statement, + reputation, + metrics, + ) + .await, net_protocol::StatementDistributionMessage::V2( protocol_v2::StatementDistributionMessage::BackedCandidateManifest(inner), ) | net_protocol::StatementDistributionMessage::V3( protocol_v3::StatementDistributionMessage::BackedCandidateManifest(inner), - ) => handle_incoming_manifest(ctx, state, peer_id, inner, reputation).await, + ) => handle_incoming_manifest(ctx, state, peer_id, inner, reputation, metrics).await, net_protocol::StatementDistributionMessage::V2( protocol_v2::StatementDistributionMessage::BackedCandidateKnown(inner), ) | net_protocol::StatementDistributionMessage::V3( protocol_v3::StatementDistributionMessage::BackedCandidateKnown(inner), - ) => handle_incoming_acknowledgement(ctx, state, peer_id, inner, reputation).await, + ) => + handle_incoming_acknowledgement(ctx, state, peer_id, inner, reputation, metrics) + .await, }, NetworkBridgeEvent::PeerViewChange(peer_id, view) => - handle_peer_view_update(ctx, state, peer_id, view).await, + handle_peer_view_update(ctx, state, peer_id, view, metrics).await, NetworkBridgeEvent::OurViewChange(_view) => { // handled by `handle_activated_leaf` }, @@ -539,6 +550,7 @@ pub(crate) async fn handle_active_leaves_update( state: &mut State, activated: &ActivatedLeaf, leaf_mode: ProspectiveParachainsMode, + metrics: &Metrics, ) -> JfyiErrorResult<()> { let max_candidate_depth = match leaf_mode { ProspectiveParachainsMode::Disabled => return Ok(()), @@ -714,7 +726,8 @@ pub(crate) async fn handle_active_leaves_update( for (peer, fresh) in update_peers { for fresh_relay_parent in fresh { - send_peer_messages_for_relay_parent(ctx, state, peer, fresh_relay_parent).await; + send_peer_messages_for_relay_parent(ctx, state, peer, fresh_relay_parent, metrics) + .await; } } } @@ -815,6 +828,7 @@ async fn handle_peer_view_update( state: &mut State, peer: PeerId, new_view: View, + metrics: &Metrics, ) { let fresh_implicit = { let peer_data = match state.peers.get_mut(&peer) { @@ -826,7 +840,7 @@ async fn handle_peer_view_update( }; for new_relay_parent in fresh_implicit { - send_peer_messages_for_relay_parent(ctx, state, peer, new_relay_parent).await; + send_peer_messages_for_relay_parent(ctx, state, peer, new_relay_parent, metrics).await; } } @@ -857,6 +871,7 @@ async fn send_peer_messages_for_relay_parent( state: &mut State, peer: PeerId, relay_parent: Hash, + metrics: &Metrics, ) { let peer_data = match state.peers.get_mut(&peer) { None => return, @@ -889,6 +904,7 @@ async fn send_peer_messages_for_relay_parent( &mut active.cluster_tracker, &state.candidates, &relay_parent_state.statement_store, + metrics, ) .await; } @@ -901,6 +917,7 @@ async fn send_peer_messages_for_relay_parent( &per_session_state.groups, relay_parent_state, &state.candidates, + metrics, ) .await; } @@ -949,6 +966,7 @@ async fn send_pending_cluster_statements( cluster_tracker: &mut ClusterTracker, candidates: &Candidates, statement_store: &StatementStore, + metrics: &Metrics, ) { let pending_statements = cluster_tracker.pending_statements_for(peer_validator_id); let network_messages = pending_statements @@ -974,12 +992,12 @@ async fn send_pending_cluster_statements( }) .collect::>(); - if network_messages.is_empty() { - return + if !network_messages.is_empty() { + let count = network_messages.len(); + ctx.send_message(NetworkBridgeTxMessage::SendValidationMessages(network_messages)) + .await; + metrics.on_statements_distributed(count); } - - ctx.send_message(NetworkBridgeTxMessage::SendValidationMessages(network_messages)) - .await; } /// Send a peer all pending grid messages / acknowledgements / follow up statements @@ -993,6 +1011,7 @@ async fn send_pending_grid_messages( groups: &Groups, relay_parent_state: &mut PerRelayParentState, candidates: &Candidates, + metrics: &Metrics, ) { let pending_manifests = { let local_validator = match relay_parent_state.local_validator.as_mut() { @@ -1005,6 +1024,7 @@ async fn send_pending_grid_messages( }; let mut messages: Vec<(Vec, net_protocol::VersionedValidationProtocol)> = Vec::new(); + let mut statements_count = 0; for (candidate_hash, kind) in pending_manifests { let confirmed_candidate = match candidates.get_confirmed(&candidate_hash) { None => continue, // sanity @@ -1079,7 +1099,7 @@ async fn send_pending_grid_messages( }; }, grid::ManifestKind::Acknowledgement => { - messages.extend(acknowledgement_and_statement_messages( + let (m, c) = acknowledgement_and_statement_messages( peer_id, peer_validator_id, groups, @@ -1088,7 +1108,9 @@ async fn send_pending_grid_messages( group_index, candidate_hash, local_knowledge, - )); + ); + messages.extend(m); + statements_count += c; }, } } @@ -1107,8 +1129,9 @@ async fn send_pending_grid_messages( let pending_statements = grid_tracker.all_pending_statements_for(peer_validator_id); - let extra_statements = - pending_statements.into_iter().filter_map(|(originator, compact)| { + let extra_statements = pending_statements + .into_iter() + .filter_map(|(originator, compact)| { let res = pending_statement_network_message( &relay_parent_state.statement_store, relay_parent, @@ -1128,15 +1151,17 @@ async fn send_pending_grid_messages( } res - }); + }) + .collect::>(); + statements_count += extra_statements.len(); messages.extend(extra_statements); } - if messages.is_empty() { - return + if !messages.is_empty() { + ctx.send_message(NetworkBridgeTxMessage::SendValidationMessages(messages)).await; + metrics.on_statements_distributed(statements_count); } - ctx.send_message(NetworkBridgeTxMessage::SendValidationMessages(messages)).await; } // Imports a locally originating statement and distributes it to peers. @@ -1147,6 +1172,7 @@ pub(crate) async fn share_local_statement( relay_parent: Hash, statement: SignedFullStatementWithPVD, reputation: &mut ReputationAggregator, + metrics: &Metrics, ) -> JfyiErrorResult<()> { let per_relay_parent = match state.per_relay_parent.get_mut(&relay_parent) { None => return Err(JfyiError::InvalidShare), @@ -1269,11 +1295,12 @@ pub(crate) async fn share_local_statement( &state.authorities, &state.peers, compact_statement, + metrics, ) .await; if let Some(post_confirmation) = post_confirmation { - apply_post_confirmation(ctx, state, post_confirmation, reputation).await; + apply_post_confirmation(ctx, state, post_confirmation, reputation, metrics).await; } Ok(()) @@ -1310,6 +1337,7 @@ async fn circulate_statement( authorities: &HashMap, peers: &HashMap, statement: SignedStatement, + metrics: &Metrics, ) { let session_info = &per_session.session_info; @@ -1446,6 +1474,7 @@ async fn circulate_statement( .into(), )) .await; + metrics.on_statement_distributed(); } if !statement_to_v3_peers.is_empty() { @@ -1465,6 +1494,7 @@ async fn circulate_statement( .into(), )) .await; + metrics.on_statement_distributed(); } } /// Check a statement signature under this parent hash. @@ -1511,6 +1541,7 @@ async fn handle_incoming_statement( relay_parent: Hash, statement: UncheckedSignedStatement, reputation: &mut ReputationAggregator, + metrics: &Metrics, ) { let peer_state = match state.peers.get(&peer) { None => { @@ -1787,6 +1818,7 @@ async fn handle_incoming_statement( &state.authorities, &state.peers, checked_statement, + metrics, ) .await; } else { @@ -1944,6 +1976,7 @@ async fn provide_candidate_to_grid( per_session: &PerSessionState, authorities: &HashMap, peers: &HashMap, + metrics: &Metrics, ) { let local_validator = match relay_parent_state.local_validator { Some(ref mut v) => v, @@ -2131,8 +2164,10 @@ async fn provide_candidate_to_grid( .await; } if !post_statements.is_empty() { + let count = post_statements.len(); ctx.send_message(NetworkBridgeTxMessage::SendValidationMessages(post_statements)) .await; + metrics.on_statements_distributed(count); } } @@ -2532,6 +2567,7 @@ async fn handle_incoming_manifest( peer: PeerId, manifest: net_protocol::v2::BackedCandidateManifest, reputation: &mut ReputationAggregator, + metrics: &Metrics, ) { gum::debug!( target: LOG_TARGET, @@ -2588,7 +2624,7 @@ async fn handle_incoming_manifest( ) }; - let messages = acknowledgement_and_statement_messages( + let (messages, statements_count) = acknowledgement_and_statement_messages( &( peer, state @@ -2609,6 +2645,7 @@ async fn handle_incoming_manifest( if !messages.is_empty() { ctx.send_message(NetworkBridgeTxMessage::SendValidationMessages(messages)).await; + metrics.on_statements_distributed(statements_count); } } else if !state.candidates.is_confirmed(&manifest.candidate_hash) { // 5. if unconfirmed, add request entry @@ -2636,9 +2673,9 @@ fn acknowledgement_and_statement_messages( group_index: GroupIndex, candidate_hash: CandidateHash, local_knowledge: StatementFilter, -) -> Vec<(Vec, net_protocol::VersionedValidationProtocol)> { +) -> (Vec<(Vec, net_protocol::VersionedValidationProtocol)>, usize) { let local_validator = match relay_parent_state.local_validator.as_mut() { - None => return Vec::new(), + None => return (Vec::new(), 0), Some(l) => l, }; @@ -2666,7 +2703,7 @@ fn acknowledgement_and_statement_messages( "Bug ValidationVersion::V1 should not be used in statement-distribution v2, legacy should have handled this" ); - return Vec::new() + return (Vec::new(), 0) }, }; @@ -2687,10 +2724,11 @@ fn acknowledgement_and_statement_messages( candidate_hash, peer, ); + let statements_count = statement_messages.len(); messages.extend(statement_messages.into_iter().map(|m| (vec![peer.0], m))); - messages + (messages, statements_count) } #[overseer::contextbounds(StatementDistribution, prefix=self::overseer)] @@ -2700,6 +2738,7 @@ async fn handle_incoming_acknowledgement( peer: PeerId, acknowledgement: net_protocol::v2::BackedCandidateAcknowledgement, reputation: &mut ReputationAggregator, + metrics: &Metrics, ) { // The key difference between acknowledgments and full manifests is that only // the candidate hash is included alongside the bitfields, so the candidate @@ -2780,10 +2819,12 @@ async fn handle_incoming_acknowledgement( ); if !messages.is_empty() { + let count = messages.len(); ctx.send_message(NetworkBridgeTxMessage::SendValidationMessages( messages.into_iter().map(|m| (vec![peer], m)).collect(), )) .await; + metrics.on_statements_distributed(count); } } @@ -2793,6 +2834,7 @@ pub(crate) async fn handle_backed_candidate_message( ctx: &mut Context, state: &mut State, candidate_hash: CandidateHash, + metrics: &Metrics, ) { // If the candidate is unknown or unconfirmed, it's a race (pruned before receiving message) // or a bug. Ignore if so @@ -2834,6 +2876,7 @@ pub(crate) async fn handle_backed_candidate_message( per_session, &state.authorities, &state.peers, + metrics, ) .await; @@ -2855,6 +2898,7 @@ async fn send_cluster_candidate_statements( state: &mut State, candidate_hash: CandidateHash, relay_parent: Hash, + metrics: &Metrics, ) { let relay_parent_state = match state.per_relay_parent.get_mut(&relay_parent) { None => return, @@ -2897,6 +2941,7 @@ async fn send_cluster_candidate_statements( &state.authorities, &state.peers, statement, + metrics, ) .await; } @@ -2914,6 +2959,7 @@ async fn apply_post_confirmation( state: &mut State, post_confirmation: PostConfirmation, reputation: &mut ReputationAggregator, + metrics: &Metrics, ) { for peer in post_confirmation.reckoning.incorrect { modify_reputation(reputation, ctx.sender(), peer, COST_INACCURATE_ADVERTISEMENT).await; @@ -2927,6 +2973,7 @@ async fn apply_post_confirmation( state, candidate_hash, post_confirmation.hypothetical.relay_parent(), + metrics, ) .await; new_confirmed_candidate_fragment_chain_updates(ctx, state, post_confirmation.hypothetical) @@ -3052,6 +3099,7 @@ pub(crate) async fn handle_response( state: &mut State, response: UnhandledResponse, reputation: &mut ReputationAggregator, + metrics: &Metrics, ) { let &requests::CandidateIdentifier { relay_parent, candidate_hash, group_index } = response.candidate_identifier(); @@ -3151,7 +3199,7 @@ pub(crate) async fn handle_response( }; // Note that this implicitly circulates all statements via the cluster. - apply_post_confirmation(ctx, state, post_confirmation, reputation).await; + apply_post_confirmation(ctx, state, post_confirmation, reputation, metrics).await; let confirmed = state.candidates.get_confirmed(&candidate_hash).expect("just confirmed; qed"); diff --git a/polkadot/node/overseer/src/lib.rs b/polkadot/node/overseer/src/lib.rs index 24985a99913d82cc265d1cd3b6d6db66dd282247..4e13d5eda76f61c646ad0814e1ec3d8068a11ca1 100644 --- a/polkadot/node/overseer/src/lib.rs +++ b/polkadot/node/overseer/src/lib.rs @@ -105,10 +105,11 @@ pub use polkadot_node_metrics::{ pub use orchestra as gen; pub use orchestra::{ - contextbounds, orchestra, subsystem, FromOrchestra, MapSubsystem, MessagePacket, - OrchestraError as OverseerError, SignalsReceived, Spawner, Subsystem, SubsystemContext, - SubsystemIncomingMessages, SubsystemInstance, SubsystemMeterReadouts, SubsystemMeters, - SubsystemSender, TimeoutExt, ToOrchestra, TrySendError, + contextbounds, orchestra, subsystem, FromOrchestra, HighPriority, MapSubsystem, MessagePacket, + NormalPriority, OrchestraError as OverseerError, Priority, PriorityLevel, SignalsReceived, + Spawner, Subsystem, SubsystemContext, SubsystemIncomingMessages, SubsystemInstance, + SubsystemMeterReadouts, SubsystemMeters, SubsystemSender, TimeoutExt, ToOrchestra, + TrySendError, }; #[cfg(any(target_os = "linux", feature = "jemalloc-allocator"))] @@ -495,7 +496,7 @@ pub struct Overseer { RuntimeApiMessage, ProspectiveParachainsMessage, ChainApiMessage, - ])] + ], can_receive_priority_messages)] statement_distribution: StatementDistribution, #[subsystem(AvailabilityDistributionMessage, sends: [ @@ -524,7 +525,7 @@ pub struct Overseer { RuntimeApiMessage, NetworkBridgeTxMessage, ProvisionerMessage, - ])] + ], can_receive_priority_messages)] bitfield_distribution: BitfieldDistribution, #[subsystem(ProvisionerMessage, sends: [ @@ -580,7 +581,7 @@ pub struct Overseer { #[subsystem(blocking, message_capacity: 64000, ApprovalDistributionMessage, sends: [ NetworkBridgeTxMessage, ApprovalVotingMessage, - ])] + ], can_receive_priority_messages)] approval_distribution: ApprovalDistribution, #[subsystem(blocking, ApprovalVotingMessage, sends: [ @@ -599,7 +600,7 @@ pub struct Overseer { NetworkBridgeRxMessage, // TODO RuntimeApiMessage, ChainSelectionMessage, - ])] + ], can_receive_priority_messages)] gossip_support: GossipSupport, #[subsystem(blocking, message_capacity: 32000, DisputeCoordinatorMessage, sends: [ diff --git a/polkadot/node/service/chain-specs/kusama.json b/polkadot/node/service/chain-specs/kusama.json index dfe79fd9c5e5d920ad1da8f1cab38a6796316e97..5d2413ac1e0263bc1cd69d4e9af696c95e909cdd 100644 --- a/polkadot/node/service/chain-specs/kusama.json +++ b/polkadot/node/service/chain-specs/kusama.json @@ -10,8 +10,8 @@ "/dns/kusama-bootnode-1.polkadot.io/tcp/443/wss/p2p/12D3KooWQKqane1SqWJNWMQkbia9qiMWXkcHtAdfW5eVF8hbwEDw", "/dns/kusama-boot.dwellir.com/tcp/30333/ws/p2p/12D3KooWFj2ndawdYyk2spc42Y2arYwb2TUoHLHFAsKuHRzWXwoJ", "/dns/kusama-boot.dwellir.com/tcp/443/wss/p2p/12D3KooWFj2ndawdYyk2spc42Y2arYwb2TUoHLHFAsKuHRzWXwoJ", - "/dns/boot.stake.plus/tcp/31333/p2p/12D3KooWLa1UyG5xLPds2GbiRBCTJjpsVwRWHWN7Dff14yiNJRpR", - "/dns/boot.stake.plus/tcp/31334/wss/p2p/12D3KooWLa1UyG5xLPds2GbiRBCTJjpsVwRWHWN7Dff14yiNJRpR", + "/dns/kusama.boot.stake.plus/tcp/30334/wss/p2p/12D3KooWDQ28HsssSyDnso7ZRiMXGtCGPRi2en6djKDsMf9f7mqE", + "/dns/kusama.boot.stake.plus/tcp/31334/wss/p2p/12D3KooWANYqS81DkERRrBW1swoMgqUHK69pJN8XjQCnS6dnUAps", "/dns/boot-node.helikon.io/tcp/7060/p2p/12D3KooWL4KPqfAsPE2aY1g5Zo1CxsDwcdJ7mmAghK7cg6M2fdbD", "/dns/boot-node.helikon.io/tcp/7062/wss/p2p/12D3KooWL4KPqfAsPE2aY1g5Zo1CxsDwcdJ7mmAghK7cg6M2fdbD", "/dns/kusama.bootnode.amforc.com/tcp/30001/p2p/12D3KooWKvYf6qKaAF8UUDw3KsTwjHLnvkED23yxHbH3npMe8w4G", diff --git a/polkadot/node/service/chain-specs/paseo.json b/polkadot/node/service/chain-specs/paseo.json index e307d5213a396ee9221701e39a9b4be239f591b2..35ac9aa6aa93678192b199f07906d943568ac022 100644 --- a/polkadot/node/service/chain-specs/paseo.json +++ b/polkadot/node/service/chain-specs/paseo.json @@ -5,8 +5,8 @@ "bootNodes": [ "/dns/paseo.bootnode.amforc.com/tcp/29999/wss/p2p/12D3KooWSdf63rZjtGdeWXpQwQwPh8K8c22upcB3B1VmqW8rxrjw", "/dns/paseo.bootnode.amforc.com/tcp/30001/p2p/12D3KooWSdf63rZjtGdeWXpQwQwPh8K8c22upcB3B1VmqW8rxrjw", - "/dns/boot.stake.plus/tcp/43334/wss/p2p/12D3KooWNhgAC3hjZHxaT52EpPFZohkCL1AHFAijqcN8xB9Rwud2", - "/dns/boot.stake.plus/tcp/43333/p2p/12D3KooWNhgAC3hjZHxaT52EpPFZohkCL1AHFAijqcN8xB9Rwud2", + "/dns/paseo.boot.stake.plus/tcp/30334/wss/p2p/12D3KooWDVqd8JXGMPsdYynu2RoBhqftTrFibZyBYibqcjQpHoQu", + "/dns/paseo.boot.stake.plus/tcp/31334/wss/p2p/12D3KooWJ4HjAGR9FUHZhc2jjLQX5Zb2zdJBxPYwrE6Ldpg5jjk4", "/dns/boot.metaspan.io/tcp/36017/wss/p2p/12D3KooWSW6nDfM3SS8rUtjMyjdszivK31bu4a1sRngGa2hFETz7", "/dns/boot.metaspan.io/tcp/36018/p2p/12D3KooWSW6nDfM3SS8rUtjMyjdszivK31bu4a1sRngGa2hFETz7", "/dns/paseo.bootnodes.polkadotters.com/tcp/30538/p2p/12D3KooWPbbFy4TefEGTRF5eTYhq8LEzc4VAHdNUVCbY4nAnhqPP", diff --git a/polkadot/node/service/chain-specs/polkadot.json b/polkadot/node/service/chain-specs/polkadot.json index f79b6db90fcf0cc3513f644edf468ed0c2fc2cd7..553ff1bb3e41e87a9b01c3e1d36019604a83e9b1 100644 --- a/polkadot/node/service/chain-specs/polkadot.json +++ b/polkadot/node/service/chain-specs/polkadot.json @@ -11,8 +11,8 @@ "/dns/polkadot-bootnode-1.polkadot.io/tcp/443/wss/p2p/12D3KooWFN2mhgpkJsDBuNuE5427AcDrsib8EoqGMZmkxWwx3Md4", "/dns/polkadot-boot.dwellir.com/tcp/30334/ws/p2p/12D3KooWKvdDyRKqUfSAaUCbYiLwKY8uK3wDWpCuy2FiDLbkPTDJ", "/dns/polkadot-boot.dwellir.com/tcp/443/wss/p2p/12D3KooWKvdDyRKqUfSAaUCbYiLwKY8uK3wDWpCuy2FiDLbkPTDJ", - "/dns/boot.stake.plus/tcp/30333/p2p/12D3KooWKT4ZHNxXH4icMjdrv7EwWBkfbz5duxE5sdJKKeWFYi5n", - "/dns/boot.stake.plus/tcp/30334/wss/p2p/12D3KooWKT4ZHNxXH4icMjdrv7EwWBkfbz5duxE5sdJKKeWFYi5n", + "/dns/polkadot.boot.stake.plus/tcp/30334/wss/p2p/12D3KooWCZKEvAMJRk9nwTHJcTjgVw6bDEqryQ3B7n7scNtfNqPB", + "/dns/polkadot.boot.stake.plus/tcp/31334/wss/p2p/12D3KooWMFwJV935CyJXE8twfkKxRDnNWeEFd8jZWaoWZF22Hv8S", "/dns/boot-node.helikon.io/tcp/7070/p2p/12D3KooWS9ZcvRxyzrSf6p63QfTCWs12nLoNKhGux865crgxVA4H", "/dns/boot-node.helikon.io/tcp/7072/wss/p2p/12D3KooWS9ZcvRxyzrSf6p63QfTCWs12nLoNKhGux865crgxVA4H", "/dns/polkadot.bootnode.amforc.com/tcp/30001/p2p/12D3KooWT2HyZx5C6BBeLbCKhYG2SqJYuiu7sLMxGzUcQBko3BMr", diff --git a/polkadot/node/service/chain-specs/westend.json b/polkadot/node/service/chain-specs/westend.json index 1bfb5ba334cef24e70b6335436ec10c77929f9e2..9059d525689d9ee2e9103fdda81f039d99b8f470 100644 --- a/polkadot/node/service/chain-specs/westend.json +++ b/polkadot/node/service/chain-specs/westend.json @@ -8,8 +8,8 @@ "/dns/westend-bootnode-1.polkadot.io/tcp/30333/p2p/12D3KooWPVPzs42GvRBShdUMtFsk4SvnByrSdWqb6aeAAHvLMSLS", "/dns/westend-bootnode-1.polkadot.io/tcp/30334/ws/p2p/12D3KooWPVPzs42GvRBShdUMtFsk4SvnByrSdWqb6aeAAHvLMSLS", "/dns/westend-bootnode-1.polkadot.io/tcp/443/wss/p2p/12D3KooWPVPzs42GvRBShdUMtFsk4SvnByrSdWqb6aeAAHvLMSLS", - "/dns/boot.stake.plus/tcp/32333/p2p/12D3KooWK8fjVoSvMq5copQYMsdYreSGPGgcMbGMgbMDPfpf3sm7", - "/dns/boot.stake.plus/tcp/32334/wss/p2p/12D3KooWK8fjVoSvMq5copQYMsdYreSGPGgcMbGMgbMDPfpf3sm7", + "/dns/westend.boot.stake.plus/tcp/30334/wss/p2p/12D3KooWAzfLkJarihZAyDeDet2WpYNkzjpXocGmmDFiRaHJjoyw", + "/dns/westend.boot.stake.plus/tcp/31334/wss/p2p/12D3KooWBdcVpUwnB3AgwZQXcyrvd4yzPBXtSLknvoBSHQZNoftP", "/dns/boot-node.helikon.io/tcp/7080/p2p/12D3KooWRFDPyT8vA8mLzh6dJoyujn4QNjeqi6Ch79eSMz9beKXC", "/dns/boot-node.helikon.io/tcp/7082/wss/p2p/12D3KooWRFDPyT8vA8mLzh6dJoyujn4QNjeqi6Ch79eSMz9beKXC", "/dns/westend.bootnode.amforc.com/tcp/30001/p2p/12D3KooWAPmR7rbm2axPjHzF51yvQNDM5GvWfkF5BTV44Y5vJ3ct", diff --git a/polkadot/node/subsystem-test-helpers/src/lib.rs b/polkadot/node/subsystem-test-helpers/src/lib.rs index 375121c3746377157e852de382c9d2cb64bce496..bdb0647fee6f5aec1dd6322b68c9a38f6e493b98 100644 --- a/polkadot/node/subsystem-test-helpers/src/lib.rs +++ b/polkadot/node/subsystem-test-helpers/src/lib.rs @@ -36,7 +36,7 @@ use std::{ convert::Infallible, future::Future, pin::Pin, - sync::Arc, + sync::{atomic::AtomicUsize, Arc}, task::{Context, Poll, Waker}, time::Duration, }; @@ -146,12 +146,13 @@ pub fn single_item_sink() -> (SingleItemSink, SingleItemStream) { #[derive(Clone)] pub struct TestSubsystemSender { tx: mpsc::UnboundedSender, + message_counter: MessageCounter, } /// Construct a sender/receiver pair. pub fn sender_receiver() -> (TestSubsystemSender, mpsc::UnboundedReceiver) { let (tx, rx) = mpsc::unbounded(); - (TestSubsystemSender { tx }, rx) + (TestSubsystemSender { tx, message_counter: MessageCounter::default() }, rx) } #[async_trait::async_trait] @@ -161,6 +162,11 @@ where OutgoingMessage: Send + 'static, { async fn send_message(&mut self, msg: OutgoingMessage) { + self.send_message_with_priority::(msg).await; + } + + async fn send_message_with_priority(&mut self, msg: OutgoingMessage) { + self.message_counter.increment(P::priority()); self.tx.send(msg.into()).await.expect("test overseer no longer live"); } @@ -168,6 +174,14 @@ where &mut self, msg: OutgoingMessage, ) -> Result<(), TrySendError> { + self.try_send_message_with_priority::(msg) + } + + fn try_send_message_with_priority( + &mut self, + msg: OutgoingMessage, + ) -> Result<(), TrySendError> { + self.message_counter.increment(P::priority()); self.tx.unbounded_send(msg.into()).expect("test overseer no longer live"); Ok(()) } @@ -277,6 +291,9 @@ pub struct TestSubsystemContextHandle { /// Direct access to the receiver. pub rx: mpsc::UnboundedReceiver, + + /// Message counter over subsystems. + pub message_counter: MessageCounter, } impl TestSubsystemContextHandle { @@ -322,6 +339,34 @@ pub fn make_subsystem_context( make_buffered_subsystem_context(spawner, 0) } +/// Message counter over subsystems. +#[derive(Default, Clone)] +pub struct MessageCounter { + total: Arc, + with_high_priority: Arc, +} + +impl MessageCounter { + /// Increment the message counter. + pub fn increment(&mut self, priority_level: overseer::PriorityLevel) { + self.total.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + if matches!(priority_level, overseer::PriorityLevel::High) { + self.with_high_priority.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + } + } + + /// Reset the message counter. + pub fn reset(&mut self) { + self.total.store(0, std::sync::atomic::Ordering::SeqCst); + self.with_high_priority.store(0, std::sync::atomic::Ordering::SeqCst); + } + + /// Get the messages with high priority count. + pub fn with_high_priority(&self) -> usize { + self.with_high_priority.load(std::sync::atomic::Ordering::SeqCst) + } +} + /// Make a test subsystem context with buffered overseer channel. Some tests (e.g. /// `dispute-coordinator`) create too many parallel operations and deadlock unless /// the channel is buffered. Usually `buffer_size=1` is enough. @@ -331,15 +376,23 @@ pub fn make_buffered_subsystem_context( ) -> (TestSubsystemContext>, TestSubsystemContextHandle) { let (overseer_tx, overseer_rx) = mpsc::channel(buffer_size); let (all_messages_tx, all_messages_rx) = mpsc::unbounded(); + let message_counter = MessageCounter::default(); ( TestSubsystemContext { - tx: TestSubsystemSender { tx: all_messages_tx }, + tx: TestSubsystemSender { + tx: all_messages_tx, + message_counter: message_counter.clone(), + }, rx: overseer_rx, spawn: SpawnGlue(spawner), message_buffer: VecDeque::new(), }, - TestSubsystemContextHandle { tx: overseer_tx, rx: all_messages_rx }, + TestSubsystemContextHandle { + tx: overseer_tx, + rx: all_messages_rx, + message_counter: message_counter.clone(), + }, ) } diff --git a/polkadot/parachain/Cargo.toml b/polkadot/parachain/Cargo.toml index 1491af0148e0b16da53078935b802ae3287f6c36..9d0518fd46ade9644af5c21c0a4c5873bfd458e3 100644 --- a/polkadot/parachain/Cargo.toml +++ b/polkadot/parachain/Cargo.toml @@ -15,7 +15,6 @@ workspace = true # various unnecessary Substrate-specific endpoints. codec = { features = ["derive"], workspace = true } scale-info = { features = ["derive", "serde"], workspace = true } -sp-std = { workspace = true } sp-runtime = { features = ["serde"], workspace = true } sp-core = { features = ["serde"], workspace = true } sp-weights = { workspace = true } @@ -37,7 +36,6 @@ std = [ "serde/std", "sp-core/std", "sp-runtime/std", - "sp-std/std", "sp-weights/std", ] runtime-benchmarks = ["sp-runtime/runtime-benchmarks"] diff --git a/polkadot/parachain/src/lib.rs b/polkadot/parachain/src/lib.rs index bd75296bf837128c7b10b8a89a823cb66dc1ca8b..8941b7fbb911e8338972ff37fe3d7231d4841cd2 100644 --- a/polkadot/parachain/src/lib.rs +++ b/polkadot/parachain/src/lib.rs @@ -51,3 +51,5 @@ mod wasm_api; #[cfg(all(not(feature = "std"), feature = "wasm-api"))] pub use wasm_api::*; + +extern crate alloc; diff --git a/polkadot/parachain/src/primitives.rs b/polkadot/parachain/src/primitives.rs index d92bbee8d28d16ea879094607ab74471551c9313..c5757928c3fc2f86fdd6ddb779856f0f39db70f7 100644 --- a/polkadot/parachain/src/primitives.rs +++ b/polkadot/parachain/src/primitives.rs @@ -17,7 +17,7 @@ //! Primitive types which are strictly necessary from a parachain-execution point //! of view. -use sp_std::vec::Vec; +use alloc::vec::Vec; use bounded_collections::{BoundedVec, ConstU32}; use codec::{CompactAs, Decode, Encode, MaxEncodedLen}; @@ -89,14 +89,14 @@ impl ValidationCode { #[derive(Clone, Copy, Encode, Decode, Hash, Eq, PartialEq, PartialOrd, Ord, TypeInfo)] pub struct ValidationCodeHash(Hash); -impl sp_std::fmt::Display for ValidationCodeHash { - fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { +impl core::fmt::Display for ValidationCodeHash { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.0.fmt(f) } } -impl sp_std::fmt::Debug for ValidationCodeHash { - fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { +impl core::fmt::Debug for ValidationCodeHash { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{:?}", self.0) } } @@ -119,9 +119,9 @@ impl From<[u8; 32]> for ValidationCodeHash { } } -impl sp_std::fmt::LowerHex for ValidationCodeHash { - fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { - sp_std::fmt::LowerHex::fmt(&self.0, f) +impl core::fmt::LowerHex for ValidationCodeHash { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + core::fmt::LowerHex::fmt(&self.0, f) } } @@ -225,7 +225,7 @@ impl IsSystem for Id { } } -impl sp_std::ops::Add for Id { +impl core::ops::Add for Id { type Output = Self; fn add(self, other: u32) -> Self { @@ -233,7 +233,7 @@ impl sp_std::ops::Add for Id { } } -impl sp_std::ops::Sub for Id { +impl core::ops::Sub for Id { type Output = Self; fn sub(self, other: u32) -> Self { diff --git a/polkadot/parachain/src/wasm_api.rs b/polkadot/parachain/src/wasm_api.rs index f0c832666284c2476401e2c8e7ced49a31864b7e..1c557c9ae50584b61b25004880f8aa4f86308d06 100644 --- a/polkadot/parachain/src/wasm_api.rs +++ b/polkadot/parachain/src/wasm_api.rs @@ -22,7 +22,7 @@ /// function's entry point. #[cfg(not(feature = "std"))] pub unsafe fn load_params(params: *const u8, len: usize) -> crate::primitives::ValidationParams { - let mut slice = sp_std::slice::from_raw_parts(params, len); + let mut slice = core::slice::from_raw_parts(params, len); codec::Decode::decode(&mut slice).expect("Invalid input data") } diff --git a/polkadot/parachain/test-parachains/adder/Cargo.toml b/polkadot/parachain/test-parachains/adder/Cargo.toml index 1661112a7b3263caa55a9ced38b08f33ac6e3d2f..7a150b75d5cdb28a82cdaf9cdeef3cb0c3a4582d 100644 --- a/polkadot/parachain/test-parachains/adder/Cargo.toml +++ b/polkadot/parachain/test-parachains/adder/Cargo.toml @@ -14,7 +14,6 @@ workspace = true [dependencies] polkadot-parachain-primitives = { features = ["wasm-api"], workspace = true } codec = { features = ["derive"], workspace = true } -sp-std = { workspace = true } tiny-keccak = { features = ["keccak"], workspace = true } dlmalloc = { features = ["global"], workspace = true } @@ -26,4 +25,4 @@ substrate-wasm-builder = { workspace = true, default-features = true } [features] default = ["std"] -std = ["codec/std", "polkadot-parachain-primitives/std", "sp-io/std", "sp-std/std"] +std = ["codec/std", "polkadot-parachain-primitives/std", "sp-io/std"] diff --git a/polkadot/parachain/test-parachains/adder/src/lib.rs b/polkadot/parachain/test-parachains/adder/src/lib.rs index 28914f02511debbc1beba6253e9f1e74dbfacc17..7e8d1bb1e1383fed96525c34ce44eb4c20f9467d 100644 --- a/polkadot/parachain/test-parachains/adder/src/lib.rs +++ b/polkadot/parachain/test-parachains/adder/src/lib.rs @@ -18,6 +18,8 @@ #![no_std] +extern crate alloc; + use codec::{Decode, Encode}; use tiny_keccak::{Hasher as _, Keccak}; diff --git a/polkadot/parachain/test-parachains/adder/src/wasm_validation.rs b/polkadot/parachain/test-parachains/adder/src/wasm_validation.rs index 7dba7a964d3b0468d48799557a363d374f4aea38..9c3c77f7350b902b3f99203d2be0f2d675e77274 100644 --- a/polkadot/parachain/test-parachains/adder/src/wasm_validation.rs +++ b/polkadot/parachain/test-parachains/adder/src/wasm_validation.rs @@ -17,10 +17,10 @@ //! WASM validation for adder parachain. use crate::{BlockData, HeadData}; +use alloc::vec::Vec; use codec::{Decode, Encode}; use core::panic; use polkadot_parachain_primitives::primitives::{HeadData as GenericHeadData, ValidationResult}; -use sp_std::vec::Vec; #[no_mangle] pub extern "C" fn validate_block(params: *const u8, len: usize) -> u64 { @@ -37,10 +37,8 @@ pub extern "C" fn validate_block(params: *const u8, len: usize) -> u64 { polkadot_parachain_primitives::write_result(&ValidationResult { head_data: GenericHeadData(new_head.encode()), new_validation_code: None, - upward_messages: sp_std::vec::Vec::new().try_into().expect("empty vec fits into bounds"), - horizontal_messages: sp_std::vec::Vec::new() - .try_into() - .expect("empty vec fits into bounds"), + upward_messages: alloc::vec::Vec::new().try_into().expect("empty vec fits into bounds"), + horizontal_messages: alloc::vec::Vec::new().try_into().expect("empty vec fits into bounds"), processed_downward_messages: 0, hrmp_watermark: params.relay_parent_number, }) diff --git a/polkadot/parachain/test-parachains/undying/Cargo.toml b/polkadot/parachain/test-parachains/undying/Cargo.toml index 2466c6a0d69d766f53aafab6c59ae35915570f23..4b2e12ebf435422c713fd2319eee08d9fa45d8dc 100644 --- a/polkadot/parachain/test-parachains/undying/Cargo.toml +++ b/polkadot/parachain/test-parachains/undying/Cargo.toml @@ -14,7 +14,6 @@ workspace = true [dependencies] polkadot-parachain-primitives = { features = ["wasm-api"], workspace = true } codec = { features = ["derive"], workspace = true } -sp-std = { workspace = true } tiny-keccak = { features = ["keccak"], workspace = true } dlmalloc = { features = ["global"], workspace = true } log = { workspace = true } @@ -32,5 +31,4 @@ std = [ "log/std", "polkadot-parachain-primitives/std", "sp-io/std", - "sp-std/std", ] diff --git a/polkadot/parachain/test-parachains/undying/src/lib.rs b/polkadot/parachain/test-parachains/undying/src/lib.rs index dc056e64fa23fb801a34d7d7b276982e4adf4f55..e4ec7e99346bbef4f3ce2fdb03b6084c053926f8 100644 --- a/polkadot/parachain/test-parachains/undying/src/lib.rs +++ b/polkadot/parachain/test-parachains/undying/src/lib.rs @@ -18,8 +18,10 @@ #![no_std] +extern crate alloc; + +use alloc::vec::Vec; use codec::{Decode, Encode}; -use sp_std::vec::Vec; use tiny_keccak::{Hasher as _, Keccak}; #[cfg(not(feature = "std"))] diff --git a/polkadot/parachain/test-parachains/undying/src/wasm_validation.rs b/polkadot/parachain/test-parachains/undying/src/wasm_validation.rs index 23fac43a3c73129b1af27d12cb0a4a79aa3c7be1..46b66aa518e490e117c6d190d52a4d4dc85574d7 100644 --- a/polkadot/parachain/test-parachains/undying/src/wasm_validation.rs +++ b/polkadot/parachain/test-parachains/undying/src/wasm_validation.rs @@ -37,8 +37,8 @@ pub extern "C" fn validate_block(params: *const u8, len: usize) -> u64 { polkadot_parachain_primitives::write_result(&ValidationResult { head_data: GenericHeadData(new_head.encode()), new_validation_code: None, - upward_messages: sp_std::vec::Vec::new().try_into().expect("empty vec fits within bounds"), - horizontal_messages: sp_std::vec::Vec::new() + upward_messages: alloc::vec::Vec::new().try_into().expect("empty vec fits within bounds"), + horizontal_messages: alloc::vec::Vec::new() .try_into() .expect("empty vec fits within bounds"), processed_downward_messages: 0, diff --git a/polkadot/primitives/Cargo.toml b/polkadot/primitives/Cargo.toml index c0b510a8fe9d0118fba52f7c8869210c3121969c..8f7ec314ecffe6d7ca7f1f943a47971b4a1e9558 100644 --- a/polkadot/primitives/Cargo.toml +++ b/polkadot/primitives/Cargo.toml @@ -28,7 +28,6 @@ sp-consensus-slots = { features = ["serde"], workspace = true } sp-io = { workspace = true } sp-keystore = { optional = true, workspace = true } sp-staking = { features = ["serde"], workspace = true } -sp-std = { workspace = true } polkadot-core-primitives = { workspace = true } polkadot-parachain-primitives = { workspace = true } @@ -55,7 +54,6 @@ std = [ "sp-keystore?/std", "sp-runtime/std", "sp-staking/std", - "sp-std/std", ] runtime-benchmarks = [ "polkadot-parachain-primitives/runtime-benchmarks", diff --git a/polkadot/primitives/src/lib.rs b/polkadot/primitives/src/lib.rs index 061794ca06d1be1883fd3605eb5bc691e5b7b23b..73736fd4a3d6b7fc6f164952fbbc6a49f139de88 100644 --- a/polkadot/primitives/src/lib.rs +++ b/polkadot/primitives/src/lib.rs @@ -31,6 +31,8 @@ pub mod vstaging; // unstable functions. pub mod runtime_api; +extern crate alloc; + // Current primitives not requiring versioning are exported here. // Primitives requiring versioning must not be exported and must be referred by an exact version. pub use v7::{ diff --git a/polkadot/primitives/src/runtime_api.rs b/polkadot/primitives/src/runtime_api.rs index 7bd92be35c159db35b3db7b9dd91afcc73eebd81..b4816ad15075dcc8d739259b779bfda1a9b5c84a 100644 --- a/polkadot/primitives/src/runtime_api.rs +++ b/polkadot/primitives/src/runtime_api.rs @@ -121,12 +121,12 @@ use crate::{ SessionIndex, SessionInfo, ValidatorId, ValidatorIndex, ValidatorSignature, }; -use polkadot_core_primitives as pcp; -use polkadot_parachain_primitives::primitives as ppp; -use sp_std::{ +use alloc::{ collections::{btree_map::BTreeMap, vec_deque::VecDeque}, - prelude::*, + vec::Vec, }; +use polkadot_core_primitives as pcp; +use polkadot_parachain_primitives::primitives as ppp; sp_api::decl_runtime_apis! { /// The API for querying the state of parachains on-chain. diff --git a/polkadot/primitives/src/v7/async_backing.rs b/polkadot/primitives/src/v7/async_backing.rs index a82d843d28bf1ca9993e7951fa8f51c458bd63c3..55d436e30de07812d4b1d722a5cbb9a85cc7d1aa 100644 --- a/polkadot/primitives/src/v7/async_backing.rs +++ b/polkadot/primitives/src/v7/async_backing.rs @@ -18,6 +18,7 @@ use super::*; +use alloc::vec::Vec; use codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_core::RuntimeDebug; diff --git a/polkadot/primitives/src/v7/executor_params.rs b/polkadot/primitives/src/v7/executor_params.rs index e58cf3e76cc2c75137737c2a6e2b34685e1a78fd..bfd42ec30bd39dbaa3299cda634fd0f4743ab2e2 100644 --- a/polkadot/primitives/src/v7/executor_params.rs +++ b/polkadot/primitives/src/v7/executor_params.rs @@ -22,11 +22,12 @@ //! done in `polkadot-node-core-pvf`. use crate::{BlakeTwo256, HashT as _, PvfExecKind, PvfPrepKind}; +use alloc::{collections::btree_map::BTreeMap, vec, vec::Vec}; use codec::{Decode, Encode}; +use core::{ops::Deref, time::Duration}; use polkadot_core_primitives::Hash; use scale_info::TypeInfo; use serde::{Deserialize, Serialize}; -use sp_std::{collections::btree_map::BTreeMap, ops::Deref, time::Duration, vec, vec::Vec}; /// Default maximum number of wasm values allowed for the stack during execution of a PVF. pub const DEFAULT_LOGICAL_STACK_MAX: u32 = 65536; @@ -134,21 +135,21 @@ impl ExecutorParamsHash { } } -impl sp_std::fmt::Display for ExecutorParamsHash { - fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { +impl core::fmt::Display for ExecutorParamsHash { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.0.fmt(f) } } -impl sp_std::fmt::Debug for ExecutorParamsHash { - fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { +impl core::fmt::Debug for ExecutorParamsHash { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{:?}", self.0) } } -impl sp_std::fmt::LowerHex for ExecutorParamsHash { - fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { - sp_std::fmt::LowerHex::fmt(&self.0, f) +impl core::fmt::LowerHex for ExecutorParamsHash { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + core::fmt::LowerHex::fmt(&self.0, f) } } @@ -159,21 +160,21 @@ impl sp_std::fmt::LowerHex for ExecutorParamsHash { #[derive(Clone, Copy, Encode, Decode, Hash, Eq, PartialEq, PartialOrd, Ord, TypeInfo)] pub struct ExecutorParamsPrepHash(Hash); -impl sp_std::fmt::Display for ExecutorParamsPrepHash { - fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { +impl core::fmt::Display for ExecutorParamsPrepHash { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { self.0.fmt(f) } } -impl sp_std::fmt::Debug for ExecutorParamsPrepHash { - fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { +impl core::fmt::Debug for ExecutorParamsPrepHash { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "{:?}", self.0) } } -impl sp_std::fmt::LowerHex for ExecutorParamsPrepHash { - fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { - sp_std::fmt::LowerHex::fmt(&self.0, f) +impl core::fmt::LowerHex for ExecutorParamsPrepHash { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + core::fmt::LowerHex::fmt(&self.0, f) } } diff --git a/polkadot/primitives/src/v7/metrics.rs b/polkadot/primitives/src/v7/metrics.rs index 1a29471c5450aa23ad00f8a41c54aca34ea7dbf4..1d66c9848a7c4016a86f5ed1eb85e880b35bba91 100644 --- a/polkadot/primitives/src/v7/metrics.rs +++ b/polkadot/primitives/src/v7/metrics.rs @@ -16,8 +16,8 @@ //! Runtime metric primitives. +use alloc::vec::Vec; use codec::{Decode, Encode}; -use sp_std::prelude::*; /// Runtime metric operations. #[derive(Encode, Decode)] @@ -42,7 +42,7 @@ pub struct RuntimeMetricUpdate { } fn vec_to_str<'a>(v: &'a Vec, default: &'static str) -> &'a str { - return sp_std::str::from_utf8(v).unwrap_or(default) + return alloc::str::from_utf8(v).unwrap_or(default) } impl RuntimeMetricLabels { @@ -99,7 +99,7 @@ pub trait AsStr { impl AsStr for RuntimeMetricLabel { fn as_str(&self) -> Option<&str> { - sp_std::str::from_utf8(&self.0).ok() + alloc::str::from_utf8(&self.0).ok() } } diff --git a/polkadot/primitives/src/v7/mod.rs b/polkadot/primitives/src/v7/mod.rs index 6b7985847a10699d36ef0f953cd5d2605c6beca0..06b7046520835b5d71f554e1c7c5c357eb6a6de9 100644 --- a/polkadot/primitives/src/v7/mod.rs +++ b/polkadot/primitives/src/v7/mod.rs @@ -16,15 +16,17 @@ //! `V7` Primitives. +use alloc::{ + vec, + vec::{IntoIter, Vec}, +}; use bitvec::{field::BitField, slice::BitSlice, vec::BitVec}; use codec::{Decode, Encode}; -use scale_info::TypeInfo; -use sp_std::{ +use core::{ marker::PhantomData, - prelude::*, slice::{Iter, IterMut}, - vec::IntoIter, }; +use scale_info::TypeInfo; use sp_application_crypto::KeyTypeId; use sp_arithmetic::traits::{BaseArithmetic, Saturating}; @@ -172,10 +174,10 @@ pub type ValidatorSignature = validator_app::Signature; /// A declarations of storage keys where an external observer can find some interesting data. pub mod well_known_keys { use super::{HrmpChannelId, Id, WellKnownKey}; + use alloc::vec::Vec; use codec::Encode as _; use hex_literal::hex; use sp_io::hashing::twox_64; - use sp_std::prelude::*; // A note on generating these magic values below: // @@ -617,13 +619,13 @@ impl CommittedCandidateReceipt { } impl PartialOrd for CommittedCandidateReceipt { - fn partial_cmp(&self, other: &Self) -> Option { + fn partial_cmp(&self, other: &Self) -> Option { Some(self.cmp(other)) } } impl Ord for CommittedCandidateReceipt { - fn cmp(&self, other: &Self) -> sp_std::cmp::Ordering { + fn cmp(&self, other: &Self) -> core::cmp::Ordering { // TODO: compare signatures or something more sane // https://github.com/paritytech/polkadot/issues/222 self.descriptor() @@ -984,7 +986,7 @@ impl GroupRotationInfo { return GroupIndex(0) } - let cores = sp_std::cmp::min(cores, u32::MAX as usize); + let cores = core::cmp::min(cores, u32::MAX as usize); let blocks_since_start = self.now.saturating_sub(self.session_start_block); let rotations = blocks_since_start / self.group_rotation_frequency; @@ -1006,7 +1008,7 @@ impl GroupRotationInfo { return CoreIndex(0) } - let cores = sp_std::cmp::min(cores, u32::MAX as usize); + let cores = core::cmp::min(cores, u32::MAX as usize); let blocks_since_start = self.now.saturating_sub(self.session_start_block); let rotations = blocks_since_start / self.group_rotation_frequency; let rotations = rotations % cores as u32; @@ -1870,7 +1872,7 @@ pub fn effective_minimum_backing_votes( group_len: usize, configured_minimum_backing_votes: u32, ) -> usize { - sp_std::cmp::min(group_len, configured_minimum_backing_votes as usize) + core::cmp::min(group_len, configured_minimum_backing_votes as usize) } /// Information about validator sets of a session. @@ -1966,7 +1968,7 @@ impl PvfCheckStatement { pub struct WellKnownKey { /// The raw storage key. pub key: Vec, - _p: sp_std::marker::PhantomData, + _p: core::marker::PhantomData, } impl From> for WellKnownKey { diff --git a/polkadot/primitives/src/v7/signed.rs b/polkadot/primitives/src/v7/signed.rs index 62e4df2385038f02247ce41fc87a1f4243c73970..f819b379a30ae2dde68d215daea712c7c28ecbb2 100644 --- a/polkadot/primitives/src/v7/signed.rs +++ b/polkadot/primitives/src/v7/signed.rs @@ -17,11 +17,11 @@ use codec::{Decode, Encode}; use scale_info::TypeInfo; +use alloc::vec::Vec; #[cfg(feature = "std")] use sp_application_crypto::AppCrypto; #[cfg(feature = "std")] use sp_keystore::{Error as KeystoreError, KeystorePtr}; -use sp_std::prelude::Vec; use sp_core::RuntimeDebug; use sp_runtime::traits::AppVerify; @@ -57,7 +57,7 @@ pub struct UncheckedSigned { /// The signature by the validator of the signed payload. signature: ValidatorSignature, /// This ensures the real payload is tracked at the typesystem level. - real_payload: sp_std::marker::PhantomData, + real_payload: core::marker::PhantomData, } impl, RealPayload: Encode> Signed { @@ -163,7 +163,7 @@ impl, RealPayload: Encode> Signed, RealPayload: Encode> Signed, RealPayload: Encode> UncheckedSigned, RealPayload: Encode> UncheckedSigned(sp_std::marker::PhantomData); + pub struct VersionUncheckedMigrateToV1(core::marker::PhantomData); impl UncheckedOnRuntimeUpgrade for VersionUncheckedMigrateToV1 { #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { diff --git a/polkadot/runtime/common/src/assigned_slots/mod.rs b/polkadot/runtime/common/src/assigned_slots/mod.rs index d0a531b8b6ca5ad995803edc8cbc45daa88176c2..dd39789e10cfdbb481615f728b6cd223ec64f037 100644 --- a/polkadot/runtime/common/src/assigned_slots/mod.rs +++ b/polkadot/runtime/common/src/assigned_slots/mod.rs @@ -30,6 +30,7 @@ use crate::{ slots::{self, Pallet as Slots, WeightInfo as SlotsWeightInfo}, traits::{LeaseError, Leaser, Registrar}, }; +use alloc::vec::Vec; use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{pallet_prelude::*, traits::Currency}; use frame_system::pallet_prelude::*; @@ -41,7 +42,6 @@ use polkadot_runtime_parachains::{ }; use scale_info::TypeInfo; use sp_runtime::traits::{One, Saturating, Zero}; -use sp_std::prelude::*; const LOG_TARGET: &str = "runtime::assigned_slots"; diff --git a/polkadot/runtime/common/src/auctions.rs b/polkadot/runtime/common/src/auctions.rs index 19d82ae85d0035aea89b5d07f0f042be237da42e..78f20d918bab52b11eccc076070f67a76b95e3de 100644 --- a/polkadot/runtime/common/src/auctions.rs +++ b/polkadot/runtime/common/src/auctions.rs @@ -22,7 +22,9 @@ use crate::{ slot_range::SlotRange, traits::{AuctionStatus, Auctioneer, LeaseError, Leaser, Registrar}, }; +use alloc::{vec, vec::Vec}; use codec::Decode; +use core::mem::swap; use frame_support::{ dispatch::DispatchResult, ensure, @@ -33,7 +35,6 @@ use frame_system::pallet_prelude::BlockNumberFor; pub use pallet::*; use polkadot_primitives::Id as ParaId; use sp_runtime::traits::{CheckedSub, One, Saturating, Zero}; -use sp_std::{mem::swap, prelude::*}; type CurrencyOf = <::Leaser as Leaser>>::Currency; type BalanceOf = <<::Leaser as Leaser>>::Currency as Currency< diff --git a/polkadot/runtime/common/src/claims.rs b/polkadot/runtime/common/src/claims.rs index c12af215a04d7119c1052a09a6eb6bee7ac0acb3..162bf01c38432f95ba25216478205c4046448c98 100644 --- a/polkadot/runtime/common/src/claims.rs +++ b/polkadot/runtime/common/src/claims.rs @@ -16,7 +16,11 @@ //! Pallet to process claims from Ethereum addresses. +#[cfg(not(feature = "std"))] +use alloc::{format, string::String}; +use alloc::{vec, vec::Vec}; use codec::{Decode, Encode}; +use core::fmt::Debug; use frame_support::{ ensure, traits::{Currency, Get, IsSubType, VestingSchedule}, @@ -35,9 +39,6 @@ use sp_runtime::{ }, RuntimeDebug, }; -#[cfg(not(feature = "std"))] -use sp_std::alloc::{format, string::String}; -use sp_std::{fmt::Debug, prelude::*}; type CurrencyOf = <::VestingSchedule as VestingSchedule< ::AccountId, @@ -150,8 +151,8 @@ impl PartialEq for EcdsaSignature { } } -impl sp_std::fmt::Debug for EcdsaSignature { - fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { +impl core::fmt::Debug for EcdsaSignature { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { write!(f, "EcdsaSignature({:?})", &self.0[..]) } } @@ -596,12 +597,12 @@ where ::RuntimeCall: IsSubType>, { #[cfg(feature = "std")] - fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { write!(f, "PrevalidateAttests") } #[cfg(not(feature = "std"))] - fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, _: &mut core::fmt::Formatter) -> core::fmt::Result { Ok(()) } } @@ -612,7 +613,7 @@ where { /// Create new `SignedExtension` to check runtime version. pub fn new() -> Self { - Self(sp_std::marker::PhantomData) + Self(core::marker::PhantomData) } } diff --git a/polkadot/runtime/common/src/crowdloan/migration.rs b/polkadot/runtime/common/src/crowdloan/migration.rs index 3afd6b3fbc94b5b30bad162cfcf8236a029b77da..0ee3872a366ea1baf90e44f61f6ac1662b022dfd 100644 --- a/polkadot/runtime/common/src/crowdloan/migration.rs +++ b/polkadot/runtime/common/src/crowdloan/migration.rs @@ -21,7 +21,7 @@ use frame_support::{ Twox64Concat, }; -pub struct MigrateToTrackInactiveV2(sp_std::marker::PhantomData); +pub struct MigrateToTrackInactiveV2(core::marker::PhantomData); impl OnRuntimeUpgrade for MigrateToTrackInactiveV2 { fn on_runtime_upgrade() -> Weight { let on_chain_version = Pallet::::on_chain_storage_version(); diff --git a/polkadot/runtime/common/src/crowdloan/mod.rs b/polkadot/runtime/common/src/crowdloan/mod.rs index 61d406aa681268d8ef0c66567faf7b74555a287d..8cf288197e3dd56085f96c928ae6a5b7f79a2a86 100644 --- a/polkadot/runtime/common/src/crowdloan/mod.rs +++ b/polkadot/runtime/common/src/crowdloan/mod.rs @@ -55,6 +55,7 @@ use crate::{ slot_range::SlotRange, traits::{Auctioneer, Registrar}, }; +use alloc::{vec, vec::Vec}; use codec::{Decode, Encode}; use frame_support::{ ensure, @@ -77,7 +78,6 @@ use sp_runtime::{ }, MultiSignature, MultiSigner, RuntimeDebug, }; -use sp_std::vec::Vec; type CurrencyOf = <::Auctioneer as Auctioneer>>::Currency; type LeasePeriodOf = <::Auctioneer as Auctioneer>>::LeasePeriod; @@ -832,16 +832,16 @@ impl Pallet { impl crate::traits::OnSwap for Pallet { fn on_swap(one: ParaId, other: ParaId) { - Funds::::mutate(one, |x| Funds::::mutate(other, |y| sp_std::mem::swap(x, y))) + Funds::::mutate(one, |x| Funds::::mutate(other, |y| core::mem::swap(x, y))) } } #[cfg(any(feature = "runtime-benchmarks", test))] mod crypto { + use alloc::vec::Vec; use sp_core::ed25519; use sp_io::crypto::{ed25519_generate, ed25519_sign}; use sp_runtime::{MultiSignature, MultiSigner}; - use sp_std::vec::Vec; pub fn create_ed25519_pubkey(seed: Vec) -> MultiSigner { ed25519_generate(0.into(), Some(seed)).into() @@ -1968,7 +1968,6 @@ mod benchmarking { use polkadot_runtime_parachains::paras; use sp_core::crypto::UncheckedFrom; use sp_runtime::traits::{Bounded, CheckedSub}; - use sp_std::prelude::*; use frame_benchmarking::{account, benchmarks, whitelisted_caller}; diff --git a/polkadot/runtime/common/src/identity_migrator.rs b/polkadot/runtime/common/src/identity_migrator.rs index 7d02e24b5368126d22a8f75e1075a75c50fb7e87..126c886280e6ed713d81c93f5afedbb69b03a1b5 100644 --- a/polkadot/runtime/common/src/identity_migrator.rs +++ b/polkadot/runtime/common/src/identity_migrator.rs @@ -172,6 +172,7 @@ impl OnReapIdentity for () { #[benchmarks] mod benchmarks { use super::*; + use alloc::{boxed::Box, vec, vec::Vec}; use codec::Encode; use frame_support::traits::EnsureOrigin; use frame_system::RawOrigin; @@ -180,7 +181,6 @@ mod benchmarks { traits::{Bounded, Hash, StaticLookup}, Saturating, }; - use sp_std::{boxed::Box, vec::Vec, *}; const SEED: u32 = 0; diff --git a/polkadot/runtime/common/src/impls.rs b/polkadot/runtime/common/src/impls.rs index 709cc69cdbeab470b9de99b16ec4585e09df8fb9..9d61cd018731f1b1761c520e91f8a4b6521fd41a 100644 --- a/polkadot/runtime/common/src/impls.rs +++ b/polkadot/runtime/common/src/impls.rs @@ -28,7 +28,7 @@ use sp_runtime::{traits::TryConvert, Perquintill, RuntimeDebug}; use xcm::VersionedLocation; /// Logic for the author to get a portion of fees. -pub struct ToAuthor(sp_std::marker::PhantomData); +pub struct ToAuthor(core::marker::PhantomData); impl OnUnbalanced>> for ToAuthor where R: pallet_balances::Config + pallet_authorship::Config, @@ -44,7 +44,7 @@ where } } -pub struct DealWithFees(sp_std::marker::PhantomData); +pub struct DealWithFees(core::marker::PhantomData); impl OnUnbalanced>> for DealWithFees where R: pallet_balances::Config + pallet_authorship::Config + pallet_treasury::Config, diff --git a/polkadot/runtime/common/src/integration_tests.rs b/polkadot/runtime/common/src/integration_tests.rs index 052fb0389db40c086d2c13b3d30501e093ef5f90..7a689a517eaa2ab97cd827890a0ffeb60bb59bb6 100644 --- a/polkadot/runtime/common/src/integration_tests.rs +++ b/polkadot/runtime/common/src/integration_tests.rs @@ -24,6 +24,7 @@ use crate::{ slots, traits::{AuctionStatus, Auctioneer, Leaser, Registrar as RegistrarT}, }; +use alloc::sync::Arc; use codec::Encode; use frame_support::{ assert_noop, assert_ok, derive_impl, parameter_types, @@ -50,7 +51,6 @@ use sp_runtime::{ transaction_validity::TransactionPriority, AccountId32, BuildStorage, MultiSignature, }; -use sp_std::sync::Arc; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlockU32; diff --git a/polkadot/runtime/common/src/lib.rs b/polkadot/runtime/common/src/lib.rs index 6e50384f68c9cf5972717a1cc60ad901b5f37dab..41e1cdbab8011bc1cb502c5d87f0214bddfc445a 100644 --- a/polkadot/runtime/common/src/lib.rs +++ b/polkadot/runtime/common/src/lib.rs @@ -41,6 +41,8 @@ mod integration_tests; #[cfg(test)] mod mock; +extern crate alloc; + use frame_support::{ parameter_types, traits::{ConstU32, Currency, OneSessionHandler}, @@ -169,7 +171,7 @@ static_assertions::assert_eq_size!(polkadot_primitives::Balance, u128); /// A placeholder since there is currently no provided session key handler for parachain validator /// keys. -pub struct ParachainSessionKeyPlaceholder(sp_std::marker::PhantomData); +pub struct ParachainSessionKeyPlaceholder(core::marker::PhantomData); impl sp_runtime::BoundToRuntimeAppPublic for ParachainSessionKeyPlaceholder { type Public = ValidatorId; } @@ -198,7 +200,7 @@ impl OneSessionHandler /// A placeholder since there is currently no provided session key handler for parachain validator /// keys. -pub struct AssignmentSessionKeyPlaceholder(sp_std::marker::PhantomData); +pub struct AssignmentSessionKeyPlaceholder(core::marker::PhantomData); impl sp_runtime::BoundToRuntimeAppPublic for AssignmentSessionKeyPlaceholder { type Public = AssignmentId; } diff --git a/polkadot/runtime/common/src/mock.rs b/polkadot/runtime/common/src/mock.rs index 6534110cc21043510e5944d1407d28f9d219c067..54170b07fa62c63c226ee5bac8c095b5e479307f 100644 --- a/polkadot/runtime/common/src/mock.rs +++ b/polkadot/runtime/common/src/mock.rs @@ -37,7 +37,7 @@ thread_local! { static MANAGERS: RefCell>> = RefCell::new(HashMap::new()); } -pub struct TestRegistrar(sp_std::marker::PhantomData); +pub struct TestRegistrar(core::marker::PhantomData); impl Registrar for TestRegistrar { type AccountId = T::AccountId; diff --git a/polkadot/runtime/common/src/paras_registrar/migration.rs b/polkadot/runtime/common/src/paras_registrar/migration.rs index 18bb6bbfb559a23e44109230ad7fd87d0b2682ca..6b110d2ff5d5e03ba74bbd79fa835679d46d33a3 100644 --- a/polkadot/runtime/common/src/paras_registrar/migration.rs +++ b/polkadot/runtime/common/src/paras_registrar/migration.rs @@ -25,7 +25,7 @@ pub struct ParaInfoV1 { } pub struct VersionUncheckedMigrateToV1( - sp_std::marker::PhantomData<(T, UnlockParaIds)>, + core::marker::PhantomData<(T, UnlockParaIds)>, ); impl> UncheckedOnRuntimeUpgrade for VersionUncheckedMigrateToV1 diff --git a/polkadot/runtime/common/src/paras_registrar/mod.rs b/polkadot/runtime/common/src/paras_registrar/mod.rs index 6b9191f7c6f2db0f9e98b0a67ead596d4c3a9822..07f02e92656120267272967d1d86ee3d9181da92 100644 --- a/polkadot/runtime/common/src/paras_registrar/mod.rs +++ b/polkadot/runtime/common/src/paras_registrar/mod.rs @@ -19,6 +19,8 @@ pub mod migration; +use alloc::{vec, vec::Vec}; +use core::result; use frame_support::{ dispatch::DispatchResult, ensure, @@ -34,7 +36,6 @@ use polkadot_runtime_parachains::{ paras::{self, ParaGenesisArgs, UpgradeStrategy}, Origin, ParaLifecycle, }; -use sp_std::{prelude::*, result}; use crate::traits::{OnSwap, Registrar}; use codec::{Decode, Encode}; @@ -210,7 +211,7 @@ pub mod pallet { #[pallet::genesis_config] pub struct GenesisConfig { #[serde(skip)] - pub _config: sp_std::marker::PhantomData, + pub _config: core::marker::PhantomData, pub next_free_para_id: ParaId, } @@ -717,10 +718,9 @@ mod tests { use crate::{ mock::conclude_pvf_checking, paras_registrar, traits::Registrar as RegistrarTrait, }; + use alloc::collections::btree_map::BTreeMap; use frame_support::{ - assert_noop, assert_ok, derive_impl, - error::BadOrigin, - parameter_types, + assert_noop, assert_ok, derive_impl, parameter_types, traits::{OnFinalize, OnInitialize}, }; use frame_system::limits; @@ -731,11 +731,10 @@ mod tests { use sp_io::TestExternalities; use sp_keyring::Sr25519Keyring; use sp_runtime::{ - traits::{BlakeTwo256, IdentityLookup}, + traits::{BadOrigin, BlakeTwo256, IdentityLookup}, transaction_validity::TransactionPriority, BuildStorage, Perbill, }; - use sp_std::collections::btree_map::BTreeMap; type UncheckedExtrinsic = frame_system::mocking::MockUncheckedExtrinsic; type Block = frame_system::mocking::MockBlockU32; diff --git a/polkadot/runtime/common/src/paras_sudo_wrapper.rs b/polkadot/runtime/common/src/paras_sudo_wrapper.rs index 3ff8d4ac08e15d88be618d79e21f2c5d97627982..af93c70b4783f717a2adddd0f0f34365ae27d954 100644 --- a/polkadot/runtime/common/src/paras_sudo_wrapper.rs +++ b/polkadot/runtime/common/src/paras_sudo_wrapper.rs @@ -16,6 +16,7 @@ //! A simple wrapper allowing `Sudo` to call into `paras` routines. +use alloc::boxed::Box; use codec::Encode; use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; @@ -26,7 +27,6 @@ use polkadot_runtime_parachains::{ paras::{self, AssignCoretime, ParaGenesisArgs}, ParaLifecycle, }; -use sp_std::boxed::Box; #[frame_support::pallet] pub mod pallet { diff --git a/polkadot/runtime/common/src/purchase.rs b/polkadot/runtime/common/src/purchase.rs index eb480e4efe1f82f657daaa03cd33d883a01d9f7d..d650548b8ac39a4059a7a9721e5926ae5ab528a9 100644 --- a/polkadot/runtime/common/src/purchase.rs +++ b/polkadot/runtime/common/src/purchase.rs @@ -16,6 +16,7 @@ //! Pallet to process purchase of DOTs. +use alloc::vec::Vec; use codec::{Decode, Encode}; use frame_support::{ pallet_prelude::*, @@ -29,7 +30,6 @@ use sp_runtime::{ traits::{CheckedAdd, Saturating, Verify, Zero}, AnySignature, DispatchError, DispatchResult, Permill, RuntimeDebug, }; -use sp_std::prelude::*; type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; diff --git a/polkadot/runtime/common/src/slots/mod.rs b/polkadot/runtime/common/src/slots/mod.rs index 747b7b5ca634ed0563061aea2d169624a2ed87ac..333f14c6608acb1d62df7fadbfe297741a39d6cd 100644 --- a/polkadot/runtime/common/src/slots/mod.rs +++ b/polkadot/runtime/common/src/slots/mod.rs @@ -25,6 +25,7 @@ pub mod migration; use crate::traits::{LeaseError, Leaser, Registrar}; +use alloc::{vec, vec::Vec}; use frame_support::{ pallet_prelude::*, traits::{Currency, ReservableCurrency}, @@ -34,7 +35,6 @@ use frame_system::pallet_prelude::*; pub use pallet::*; use polkadot_primitives::Id as ParaId; use sp_runtime::traits::{CheckedConversion, CheckedSub, Saturating, Zero}; -use sp_std::prelude::*; type BalanceOf = <::Currency as Currency<::AccountId>>::Balance; @@ -309,7 +309,7 @@ impl Pallet { // Useful when trying to clean up a parachain leases, as this would tell // you all the balances you need to unreserve. fn all_deposits_held(para: ParaId) -> Vec<(T::AccountId, BalanceOf)> { - let mut tracker = sp_std::collections::btree_map::BTreeMap::new(); + let mut tracker = alloc::collections::btree_map::BTreeMap::new(); Leases::::get(para).into_iter().for_each(|lease| match lease { Some((who, amount)) => match tracker.get(&who) { Some(prev_amount) => @@ -329,7 +329,7 @@ impl Pallet { impl crate::traits::OnSwap for Pallet { fn on_swap(one: ParaId, other: ParaId) { - Leases::::mutate(one, |x| Leases::::mutate(other, |y| sp_std::mem::swap(x, y))) + Leases::::mutate(one, |x| Leases::::mutate(other, |y| core::mem::swap(x, y))) } } diff --git a/polkadot/runtime/common/src/traits.rs b/polkadot/runtime/common/src/traits.rs index eadeac74fcdb63cab542ca080cd372b5fbd4f4fd..6e49abcee98b2778cbe2cce201d5daadf15d80f0 100644 --- a/polkadot/runtime/common/src/traits.rs +++ b/polkadot/runtime/common/src/traits.rs @@ -16,12 +16,12 @@ //! Traits used across pallets for Polkadot. +use alloc::vec::*; use frame_support::{ dispatch::DispatchResult, traits::{Currency, ReservableCurrency}, }; use polkadot_primitives::{HeadData, Id as ParaId, ValidationCode}; -use sp_std::vec::*; /// Parachain registration API. pub trait Registrar { diff --git a/polkadot/runtime/common/src/try_runtime.rs b/polkadot/runtime/common/src/try_runtime.rs index 81aa34317bfd7a7f82340bc4a8c10760049fd690..b22e1703292067c56160260aa2494d4958e0c589 100644 --- a/polkadot/runtime/common/src/try_runtime.rs +++ b/polkadot/runtime/common/src/try_runtime.rs @@ -16,13 +16,13 @@ //! Common try-runtime only tests for runtimes. +use alloc::{collections::btree_set::BTreeSet, vec::Vec}; use frame_support::{ dispatch::RawOrigin, traits::{Get, Hooks}, }; use pallet_fast_unstake::{Pallet as FastUnstake, *}; use pallet_staking::*; -use sp_std::{collections::btree_set::BTreeSet, prelude::*}; /// register all inactive nominators for fast-unstake, and progress until they have all been /// processed. diff --git a/polkadot/runtime/common/src/xcm_sender.rs b/polkadot/runtime/common/src/xcm_sender.rs index 5858a0ac3ca76e32729efa30b244f3bfadaa2bdf..dace785a535b914b6da3ca322ea11cfe94f5dbfd 100644 --- a/polkadot/runtime/common/src/xcm_sender.rs +++ b/polkadot/runtime/common/src/xcm_sender.rs @@ -16,7 +16,9 @@ //! XCM sender for relay chain. +use alloc::vec::Vec; use codec::{Decode, Encode}; +use core::marker::PhantomData; use frame_support::traits::Get; use frame_system::pallet_prelude::BlockNumberFor; use polkadot_primitives::Id as ParaId; @@ -25,7 +27,6 @@ use polkadot_runtime_parachains::{ dmp, FeeTracker, }; use sp_runtime::FixedPointNumber; -use sp_std::{marker::PhantomData, prelude::*}; use xcm::prelude::*; use xcm_builder::InspectMessageQueues; use SendError::*; @@ -56,7 +57,7 @@ impl PriceForMessageDelivery for NoPriceForMessageDelivery { } /// Implementation of [`PriceForMessageDelivery`] which returns a fixed price. -pub struct ConstantPrice(sp_std::marker::PhantomData); +pub struct ConstantPrice(core::marker::PhantomData); impl> PriceForMessageDelivery for ConstantPrice { type Id = (); @@ -79,7 +80,7 @@ impl> PriceForMessageDelivery for ConstantPrice { /// - `B`: The base fee to pay for message delivery. /// - `M`: The fee to pay for each and every byte of the message after encoding it. /// - `F`: A fee factor multiplier. It can be understood as the exponent term in the formula. -pub struct ExponentialPrice(sp_std::marker::PhantomData<(A, B, M, F)>); +pub struct ExponentialPrice(core::marker::PhantomData<(A, B, M, F)>); impl, B: Get, M: Get, F: FeeTracker> PriceForMessageDelivery for ExponentialPrice { @@ -169,7 +170,7 @@ pub struct ToParachainDeliveryHelper< ParaId, ToParaIdHelper, >( - sp_std::marker::PhantomData<( + core::marker::PhantomData<( XcmConfig, ExistentialDeposit, PriceForDelivery, @@ -223,7 +224,7 @@ impl< } // overestimate delivery fee - let overestimated_xcm = vec![ClearOrigin; 128].into(); + let overestimated_xcm = alloc::vec![ClearOrigin; 128].into(); let overestimated_fees = PriceForDelivery::price_for_delivery(Parachain::get(), &overestimated_xcm); @@ -258,6 +259,7 @@ impl EnsureForParachain for () { mod tests { use super::*; use crate::integration_tests::new_test_ext; + use alloc::vec; use frame_support::{assert_ok, parameter_types}; use polkadot_runtime_parachains::FeeTracker; use sp_runtime::FixedU128; diff --git a/polkadot/runtime/metrics/Cargo.toml b/polkadot/runtime/metrics/Cargo.toml index 54c685effc1165f7528029f01717ee1ad6f3a298..3709e1eb697ea1a5941b307a4a8abd06238d3b57 100644 --- a/polkadot/runtime/metrics/Cargo.toml +++ b/polkadot/runtime/metrics/Cargo.toml @@ -10,7 +10,6 @@ description = "Runtime metric interface for the Polkadot node" workspace = true [dependencies] -sp-std = { workspace = true } sp-tracing = { workspace = true } codec = { workspace = true } polkadot-primitives = { workspace = true } @@ -25,7 +24,6 @@ std = [ "codec/std", "frame-benchmarking?/std", "polkadot-primitives/std", - "sp-std/std", "sp-tracing/std", ] runtime-metrics = ["frame-benchmarking", "sp-tracing/with-tracing"] diff --git a/polkadot/runtime/metrics/src/lib.rs b/polkadot/runtime/metrics/src/lib.rs index 6164d71f112a47bce0a91da044aa8d9166c8a8b7..479ec7a69c3aaf8a94b9da2a84f2c04f4fea7165 100644 --- a/polkadot/runtime/metrics/src/lib.rs +++ b/polkadot/runtime/metrics/src/lib.rs @@ -22,6 +22,8 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + #[cfg(feature = "runtime-metrics")] mod with_runtime_metrics; #[cfg(feature = "runtime-metrics")] diff --git a/polkadot/runtime/metrics/src/with_runtime_metrics.rs b/polkadot/runtime/metrics/src/with_runtime_metrics.rs index 1339df9ff6879e6624823fe49cac55eb2854252a..979d5eda9afc645c1b343959a3bf65dc7f3e295c 100644 --- a/polkadot/runtime/metrics/src/with_runtime_metrics.rs +++ b/polkadot/runtime/metrics/src/with_runtime_metrics.rs @@ -22,14 +22,13 @@ const TRACING_TARGET: &'static str = "metrics"; +use alloc::vec::Vec; use codec::Encode; use polkadot_primitives::{ metric_definitions::{CounterDefinition, CounterVecDefinition, HistogramDefinition}, RuntimeMetricLabelValues, RuntimeMetricOp, RuntimeMetricUpdate, }; -use sp_std::prelude::*; - /// Holds a set of counters that have different values for their labels, /// like Prometheus `CounterVec`. pub struct CounterVec { diff --git a/polkadot/runtime/parachains/Cargo.toml b/polkadot/runtime/parachains/Cargo.toml index 82ba22a70f37b0e8fb5049fbcd6ca60c1eb5c8a1..cfe373e8cba2e6c186ea62d7121aff5f3d4cafa7 100644 --- a/polkadot/runtime/parachains/Cargo.toml +++ b/polkadot/runtime/parachains/Cargo.toml @@ -21,7 +21,6 @@ bitflags = { workspace = true } sp-api = { workspace = true } sp-inherents = { workspace = true } -sp-std = { workspace = true } sp-io = { workspace = true } sp-runtime = { features = ["serde"], workspace = true } sp-session = { workspace = true } @@ -31,6 +30,7 @@ sp-keystore = { optional = true, workspace = true } sp-application-crypto = { optional = true, workspace = true } sp-tracing = { optional = true, workspace = true } sp-arithmetic = { workspace = true } +sp-std = { workspace = true, optional = true } pallet-authority-discovery = { workspace = true } pallet-authorship = { workspace = true } @@ -38,6 +38,7 @@ pallet-balances = { workspace = true } pallet-babe = { workspace = true } pallet-broker = { workspace = true } pallet-message-queue = { workspace = true } +pallet-mmr = { workspace = true, optional = true } pallet-session = { workspace = true } pallet-staking = { workspace = true } pallet-timestamp = { workspace = true } @@ -87,6 +88,7 @@ std = [ "pallet-balances/std", "pallet-broker/std", "pallet-message-queue/std", + "pallet-mmr?/std", "pallet-session/std", "pallet-staking/std", "pallet-timestamp/std", @@ -110,7 +112,7 @@ std = [ "sp-runtime/std", "sp-session/std", "sp-staking/std", - "sp-std/std", + "sp-std?/std", "xcm-executor/std", "xcm/std", ] @@ -122,6 +124,7 @@ runtime-benchmarks = [ "pallet-balances/runtime-benchmarks", "pallet-broker/runtime-benchmarks", "pallet-message-queue/runtime-benchmarks", + "pallet-mmr/runtime-benchmarks", "pallet-staking/runtime-benchmarks", "pallet-timestamp/runtime-benchmarks", "pallet-vesting/runtime-benchmarks", @@ -130,6 +133,7 @@ runtime-benchmarks = [ "sp-application-crypto", "sp-runtime/runtime-benchmarks", "sp-staking/runtime-benchmarks", + "sp-std", "static_assertions", "xcm-executor/runtime-benchmarks", ] @@ -143,6 +147,7 @@ try-runtime = [ "pallet-balances/try-runtime", "pallet-broker/try-runtime", "pallet-message-queue/try-runtime", + "pallet-mmr/try-runtime", "pallet-session/try-runtime", "pallet-staking/try-runtime", "pallet-timestamp/try-runtime", diff --git a/polkadot/runtime/parachains/src/assigner_coretime/mod.rs b/polkadot/runtime/parachains/src/assigner_coretime/mod.rs index e68ac2664b898b5594a19fa7a8626c2d3b257160..9ed007919b81be6f1f68e9f35ff6dfbc46bffc81 100644 --- a/polkadot/runtime/parachains/src/assigner_coretime/mod.rs +++ b/polkadot/runtime/parachains/src/assigner_coretime/mod.rs @@ -34,14 +34,13 @@ use crate::{ ParaId, }; +use alloc::{vec, vec::Vec}; use frame_support::{defensive, pallet_prelude::*}; use frame_system::pallet_prelude::*; use pallet_broker::CoreAssignment; use polkadot_primitives::CoreIndex; use sp_runtime::traits::{One, Saturating}; -use sp_std::prelude::*; - pub use pallet::*; /// Fraction expressed as a nominator with an assumed denominator of 57,600. diff --git a/polkadot/runtime/parachains/src/assigner_coretime/tests.rs b/polkadot/runtime/parachains/src/assigner_coretime/tests.rs index bab09eda52c2d630171bb790831152d945b718db..9b0cbcb2d7d698b14f818690b26f767d3a22b431 100644 --- a/polkadot/runtime/parachains/src/assigner_coretime/tests.rs +++ b/polkadot/runtime/parachains/src/assigner_coretime/tests.rs @@ -26,10 +26,10 @@ use crate::{ paras::{ParaGenesisArgs, ParaKind}, scheduler::common::Assignment, }; +use alloc::collections::btree_map::BTreeMap; use frame_support::{assert_noop, assert_ok, pallet_prelude::*, traits::Currency}; use pallet_broker::TaskId; use polkadot_primitives::{BlockNumber, Id as ParaId, SessionIndex, ValidationCode}; -use sp_std::collections::btree_map::BTreeMap; fn schedule_blank_para(id: ParaId, parakind: ParaKind) { let validation_code: ValidationCode = vec![1, 2, 3].into(); diff --git a/polkadot/runtime/parachains/src/assigner_on_demand/benchmarking.rs b/polkadot/runtime/parachains/src/assigner_on_demand/benchmarking.rs index ba6951a146921f7f698c02bb49dcaffea76563e4..b0ebfe77a9665bf08ea62c44b1381866372c54bb 100644 --- a/polkadot/runtime/parachains/src/assigner_on_demand/benchmarking.rs +++ b/polkadot/runtime/parachains/src/assigner_on_demand/benchmarking.rs @@ -25,6 +25,7 @@ use crate::{ shared::Pallet as ParasShared, }; +use alloc::vec; use frame_benchmarking::v2::*; use frame_system::RawOrigin; use sp_runtime::traits::Bounded; diff --git a/polkadot/runtime/parachains/src/assigner_on_demand/migration.rs b/polkadot/runtime/parachains/src/assigner_on_demand/migration.rs index 314be11adbeb79bab4fa0ce2d0b4f52fb5176ceb..03f63d7333b65adddd371168e85cdb19d95b10e2 100644 --- a/polkadot/runtime/parachains/src/assigner_on_demand/migration.rs +++ b/polkadot/runtime/parachains/src/assigner_on_demand/migration.rs @@ -23,7 +23,7 @@ use frame_support::{ mod v0 { use super::*; - use sp_std::collections::vec_deque::VecDeque; + use alloc::collections::vec_deque::VecDeque; #[derive(Encode, Decode, TypeInfo, Debug, PartialEq, Clone)] pub(super) struct EnqueuedOrder { @@ -50,7 +50,7 @@ mod v1 { use crate::assigner_on_demand::LOG_TARGET; /// Migration to V1 - pub struct UncheckedMigrateToV1(sp_std::marker::PhantomData); + pub struct UncheckedMigrateToV1(core::marker::PhantomData); impl UncheckedOnRuntimeUpgrade for UncheckedMigrateToV1 { fn on_runtime_upgrade() -> Weight { let mut weight: Weight = Weight::zero(); @@ -88,7 +88,7 @@ mod v1 { } #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { + fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { let n: u32 = v0::OnDemandQueue::::get().len() as u32; log::info!( @@ -100,7 +100,7 @@ mod v1 { } #[cfg(feature = "try-runtime")] - fn post_upgrade(state: Vec) -> Result<(), sp_runtime::TryRuntimeError> { + fn post_upgrade(state: alloc::vec::Vec) -> Result<(), sp_runtime::TryRuntimeError> { log::info!(target: LOG_TARGET, "Running post_upgrade()"); ensure!( diff --git a/polkadot/runtime/parachains/src/assigner_on_demand/mod.rs b/polkadot/runtime/parachains/src/assigner_on_demand/mod.rs index 03f05842bca498a26518bbeb0e8f957f2fa5783c..f045e957a6907b9e01be4d30c533c324f62fb907 100644 --- a/polkadot/runtime/parachains/src/assigner_on_demand/mod.rs +++ b/polkadot/runtime/parachains/src/assigner_on_demand/mod.rs @@ -61,7 +61,6 @@ use sp_runtime::{ traits::{AccountIdConversion, One, SaturatedConversion}, FixedPointNumber, FixedPointOperand, FixedU128, Perbill, Saturating, }; -use sp_std::prelude::*; use types::{ BalanceOf, CoreAffinityCount, EnqueuedOrder, QueuePushDirection, QueueStatusType, SpotTrafficCalculationErr, diff --git a/polkadot/runtime/parachains/src/assigner_on_demand/tests.rs b/polkadot/runtime/parachains/src/assigner_on_demand/tests.rs index 3d01ba655d3f404ac0e5b09d7ef590b175779534..0bad4346cfd9d8efb42db2bd66c7d64c0213a803 100644 --- a/polkadot/runtime/parachains/src/assigner_on_demand/tests.rs +++ b/polkadot/runtime/parachains/src/assigner_on_demand/tests.rs @@ -30,15 +30,14 @@ use crate::{ }, paras::{ParaGenesisArgs, ParaKind}, }; -use frame_support::{assert_noop, assert_ok, error::BadOrigin}; +use alloc::collections::btree_map::BTreeMap; +use core::cmp::{Ord, Ordering}; +use frame_support::{assert_noop, assert_ok}; use pallet_balances::Error as BalancesError; use polkadot_primitives::{ BlockNumber, SessionIndex, ValidationCode, ON_DEMAND_MAX_QUEUE_MAX_SIZE, }; -use sp_std::{ - cmp::{Ord, Ordering}, - collections::btree_map::BTreeMap, -}; +use sp_runtime::traits::BadOrigin; fn schedule_blank_para(id: ParaId, parakind: ParaKind) { let validation_code: ValidationCode = vec![1, 2, 3].into(); diff --git a/polkadot/runtime/parachains/src/assigner_on_demand/types.rs b/polkadot/runtime/parachains/src/assigner_on_demand/types.rs index 51d586a77a1784c905469dc48ed58fd382a1186b..96367b971fed52c2de43f3f997101b107e11d1ec 100644 --- a/polkadot/runtime/parachains/src/assigner_on_demand/types.rs +++ b/polkadot/runtime/parachains/src/assigner_on_demand/types.rs @@ -18,16 +18,13 @@ use super::{alloc, pallet::Config}; use alloc::collections::BinaryHeap; +use core::cmp::{Ord, Ordering, PartialOrd}; use frame_support::{ pallet_prelude::{Decode, Encode, RuntimeDebug, TypeInfo}, traits::Currency, }; use polkadot_primitives::{CoreIndex, Id as ParaId, ON_DEMAND_MAX_QUEUE_MAX_SIZE}; use sp_runtime::FixedU128; -use sp_std::{ - cmp::{Ord, Ordering, PartialOrd}, - prelude::*, -}; /// Shorthand for the Balance type the runtime is using. pub type BalanceOf = diff --git a/polkadot/runtime/parachains/src/assigner_parachains/tests.rs b/polkadot/runtime/parachains/src/assigner_parachains/tests.rs index 14cb1a8978602b6273243ec463dfa36eb7b7c80c..817e43a7138ddbe121e84ea6c02497e07b323469 100644 --- a/polkadot/runtime/parachains/src/assigner_parachains/tests.rs +++ b/polkadot/runtime/parachains/src/assigner_parachains/tests.rs @@ -23,9 +23,9 @@ use crate::{ }, paras::{ParaGenesisArgs, ParaKind}, }; +use alloc::collections::btree_map::BTreeMap; use frame_support::{assert_ok, pallet_prelude::*}; use polkadot_primitives::{BlockNumber, Id as ParaId, SessionIndex, ValidationCode}; -use sp_std::collections::btree_map::BTreeMap; fn schedule_blank_para(id: ParaId, parakind: ParaKind) { let validation_code: ValidationCode = vec![1, 2, 3].into(); diff --git a/polkadot/runtime/parachains/src/builder.rs b/polkadot/runtime/parachains/src/builder.rs index c046526ba372b537d48fac8d7be65e97a6b846f9..ec07cca2107e9a7ae02f7f45ea1add1b0bf6199c 100644 --- a/polkadot/runtime/parachains/src/builder.rs +++ b/polkadot/runtime/parachains/src/builder.rs @@ -21,6 +21,11 @@ use crate::{ scheduler::{self, common::AssignmentProvider, CoreOccupied, ParasEntry}, session_info, shared, }; +use alloc::{ + collections::{btree_map::BTreeMap, btree_set::BTreeSet, vec_deque::VecDeque}, + vec, + vec::Vec, +}; use bitvec::{order::Lsb0 as BitOrderLsb0, vec::BitVec}; use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; @@ -39,11 +44,6 @@ use sp_runtime::{ traits::{Header as HeaderT, One, TrailingZeroInput, Zero}, RuntimeAppPublic, }; -use sp_std::{ - collections::{btree_map::BTreeMap, btree_set::BTreeSet, vec_deque::VecDeque}, - prelude::Vec, - vec, -}; fn mock_validation_code() -> ValidationCode { ValidationCode(vec![1, 2, 3]) @@ -112,7 +112,7 @@ pub(crate) struct BenchBuilder { fill_claimqueue: bool, /// Cores which should not be available when being populated with pending candidates. unavailable_cores: Vec, - _phantom: sp_std::marker::PhantomData, + _phantom: core::marker::PhantomData, } /// Paras inherent `enter` benchmark scenario. @@ -143,7 +143,7 @@ impl BenchBuilder { code_upgrade: None, fill_claimqueue: true, unavailable_cores: vec![], - _phantom: sp_std::marker::PhantomData::, + _phantom: core::marker::PhantomData::, } } diff --git a/polkadot/runtime/parachains/src/configuration.rs b/polkadot/runtime/parachains/src/configuration.rs index bffeab4a0d21b13d492550eeb0323624cc8c588c..d09962ef2b4412c3e583129c2ab14624062c5dff 100644 --- a/polkadot/runtime/parachains/src/configuration.rs +++ b/polkadot/runtime/parachains/src/configuration.rs @@ -19,6 +19,7 @@ //! Configuration can change only at session boundaries and is buffered until then. use crate::{inclusion::MAX_UPWARD_MESSAGE_SIZE_BOUND, shared}; +use alloc::vec::Vec; use codec::{Decode, Encode}; use frame_support::{pallet_prelude::*, DefaultNoBound}; use frame_system::pallet_prelude::*; @@ -31,7 +32,6 @@ use polkadot_primitives::{ MAX_POV_SIZE, ON_DEMAND_MAX_QUEUE_MAX_SIZE, }; use sp_runtime::{traits::Zero, Perbill, Percent}; -use sp_std::prelude::*; #[cfg(test)] mod tests; @@ -345,7 +345,7 @@ pub enum InconsistentError { impl HostConfiguration where - BlockNumber: Zero + PartialOrd + sp_std::fmt::Debug + Clone + From, + BlockNumber: Zero + PartialOrd + core::fmt::Debug + Clone + From, { /// Checks that this instance is consistent with the requirements on each individual member. /// @@ -1469,7 +1469,7 @@ impl Pallet { /// The implementation of `Get<(u32, u32)>` which reads `ActiveConfig` and returns `P` percent of /// `hrmp_channel_max_message_size` / `hrmp_channel_max_capacity`. -pub struct ActiveConfigHrmpChannelSizeAndCapacityRatio(sp_std::marker::PhantomData<(T, P)>); +pub struct ActiveConfigHrmpChannelSizeAndCapacityRatio(core::marker::PhantomData<(T, P)>); impl> Get<(u32, u32)> for ActiveConfigHrmpChannelSizeAndCapacityRatio { diff --git a/polkadot/runtime/parachains/src/configuration/migration/v10.rs b/polkadot/runtime/parachains/src/configuration/migration/v10.rs index c53f58faaf03a8ca85d2d6ac3272425976e0f177..9375af88306fd804d079be38672f1527f4ccacd2 100644 --- a/polkadot/runtime/parachains/src/configuration/migration/v10.rs +++ b/polkadot/runtime/parachains/src/configuration/migration/v10.rs @@ -17,6 +17,7 @@ //! A module that is responsible for migration of storage. use crate::configuration::{Config, Pallet}; +use alloc::vec::Vec; use frame_support::{ pallet_prelude::*, traits::{Defensive, UncheckedOnRuntimeUpgrade}, @@ -28,7 +29,6 @@ use polkadot_primitives::{ LEGACY_MIN_BACKING_VOTES, ON_DEMAND_DEFAULT_QUEUE_MAX_SIZE, }; use sp_runtime::Perbill; -use sp_std::vec::Vec; use super::v9::V9HostConfiguration; // All configuration of the runtime with respect to paras. @@ -164,7 +164,7 @@ mod v10 { >; } -pub struct VersionUncheckedMigrateToV10(sp_std::marker::PhantomData); +pub struct VersionUncheckedMigrateToV10(core::marker::PhantomData); impl UncheckedOnRuntimeUpgrade for VersionUncheckedMigrateToV10 { #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { diff --git a/polkadot/runtime/parachains/src/configuration/migration/v11.rs b/polkadot/runtime/parachains/src/configuration/migration/v11.rs index 4d1bfc26196ca2ade0b904da2c9be4159b0a099e..4dce48fe52b0e37d954b3006cb69e9e190c8b3aa 100644 --- a/polkadot/runtime/parachains/src/configuration/migration/v11.rs +++ b/polkadot/runtime/parachains/src/configuration/migration/v11.rs @@ -17,6 +17,7 @@ //! A module that is responsible for migration of storage. use crate::configuration::{self, Config, Pallet}; +use alloc::vec::Vec; use frame_support::{ migrations::VersionedMigration, pallet_prelude::*, @@ -28,7 +29,6 @@ use polkadot_primitives::{ ApprovalVotingParams, AsyncBackingParams, ExecutorParams, NodeFeatures, SessionIndex, LEGACY_MIN_BACKING_VOTES, ON_DEMAND_DEFAULT_QUEUE_MAX_SIZE, }; -use sp_std::vec::Vec; use polkadot_core_primitives::Balance; use sp_arithmetic::Perbill; @@ -177,7 +177,7 @@ pub type MigrateToV11 = VersionedMigration< ::DbWeight, >; -pub struct UncheckedMigrateToV11(sp_std::marker::PhantomData); +pub struct UncheckedMigrateToV11(core::marker::PhantomData); impl UncheckedOnRuntimeUpgrade for UncheckedMigrateToV11 { #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { diff --git a/polkadot/runtime/parachains/src/configuration/migration/v12.rs b/polkadot/runtime/parachains/src/configuration/migration/v12.rs index 126597ed845447c059eebb28b230e988db5ac77d..6b77655687f0dfd13bfdf3f425a4d744b9798cd3 100644 --- a/polkadot/runtime/parachains/src/configuration/migration/v12.rs +++ b/polkadot/runtime/parachains/src/configuration/migration/v12.rs @@ -17,6 +17,7 @@ //! A module that is responsible for migration of storage. use crate::configuration::{self, migration::v11::V11HostConfiguration, Config, Pallet}; +use alloc::vec::Vec; use frame_support::{ migrations::VersionedMigration, pallet_prelude::*, @@ -26,7 +27,6 @@ use frame_system::pallet_prelude::BlockNumberFor; use polkadot_primitives::vstaging::SchedulerParams; use sp_core::Get; use sp_staking::SessionIndex; -use sp_std::vec::Vec; type V12HostConfiguration = configuration::HostConfiguration; @@ -68,7 +68,7 @@ pub type MigrateToV12 = VersionedMigration< ::DbWeight, >; -pub struct UncheckedMigrateToV12(sp_std::marker::PhantomData); +pub struct UncheckedMigrateToV12(core::marker::PhantomData); impl UncheckedOnRuntimeUpgrade for UncheckedMigrateToV12 { #[cfg(feature = "try-runtime")] diff --git a/polkadot/runtime/parachains/src/configuration/migration/v6.rs b/polkadot/runtime/parachains/src/configuration/migration/v6.rs index bec41d3ea0dc51ec83ecce67f7373751cd7e2432..468bf78692a12980d322233f51eb625720944e22 100644 --- a/polkadot/runtime/parachains/src/configuration/migration/v6.rs +++ b/polkadot/runtime/parachains/src/configuration/migration/v6.rs @@ -17,13 +17,11 @@ //! Contains the V6 storage definition of the host configuration. use crate::configuration::{Config, Pallet}; +use alloc::vec::Vec; use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::BlockNumberFor; -use sp_std::vec::Vec; use polkadot_primitives::{AsyncBackingParams, Balance, ExecutorParams, SessionIndex}; -#[cfg(feature = "try-runtime")] -use sp_std::prelude::*; #[derive(codec::Encode, codec::Decode, Debug, Clone)] pub struct V6HostConfiguration { diff --git a/polkadot/runtime/parachains/src/configuration/migration/v7.rs b/polkadot/runtime/parachains/src/configuration/migration/v7.rs index 8fe4087cf9b170754e07f07175a3de1eac6ce216..9acd28d0f764e4f966fd48cbfd3e6fc9a5810200 100644 --- a/polkadot/runtime/parachains/src/configuration/migration/v7.rs +++ b/polkadot/runtime/parachains/src/configuration/migration/v7.rs @@ -17,6 +17,7 @@ //! A module that is responsible for migration of storage. use crate::configuration::{self, Config, Pallet}; +use alloc::vec::Vec; use frame_support::{ pallet_prelude::*, traits::{Defensive, StorageVersion}, @@ -24,7 +25,6 @@ use frame_support::{ }; use frame_system::pallet_prelude::BlockNumberFor; use polkadot_primitives::{AsyncBackingParams, Balance, ExecutorParams, SessionIndex}; -use sp_std::vec::Vec; use frame_support::traits::OnRuntimeUpgrade; @@ -154,7 +154,7 @@ mod v7 { >; } -pub struct MigrateToV7(sp_std::marker::PhantomData); +pub struct MigrateToV7(core::marker::PhantomData); impl OnRuntimeUpgrade for MigrateToV7 { #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { diff --git a/polkadot/runtime/parachains/src/configuration/migration/v8.rs b/polkadot/runtime/parachains/src/configuration/migration/v8.rs index 0aa7f550b102afea143c762a70e2056f918d5bc8..81ced74bebb9770ff09fb50b42e9c89f213b6019 100644 --- a/polkadot/runtime/parachains/src/configuration/migration/v8.rs +++ b/polkadot/runtime/parachains/src/configuration/migration/v8.rs @@ -17,6 +17,7 @@ //! A module that is responsible for migration of storage. use crate::configuration::{self, Config, Pallet}; +use alloc::vec::Vec; use frame_support::{ pallet_prelude::*, traits::{Defensive, StorageVersion}, @@ -27,7 +28,6 @@ use polkadot_primitives::{ AsyncBackingParams, Balance, ExecutorParams, SessionIndex, ON_DEMAND_DEFAULT_QUEUE_MAX_SIZE, }; use sp_runtime::Perbill; -use sp_std::vec::Vec; use frame_support::traits::OnRuntimeUpgrade; @@ -161,7 +161,7 @@ mod v8 { >; } -pub struct MigrateToV8(sp_std::marker::PhantomData); +pub struct MigrateToV8(core::marker::PhantomData); impl OnRuntimeUpgrade for MigrateToV8 { #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { diff --git a/polkadot/runtime/parachains/src/configuration/migration/v9.rs b/polkadot/runtime/parachains/src/configuration/migration/v9.rs index 6afdd3cec29efbb8988cfab5a79c712553b7b8aa..dff5fdb17a697cf209ccffa07b808175cfab2f7b 100644 --- a/polkadot/runtime/parachains/src/configuration/migration/v9.rs +++ b/polkadot/runtime/parachains/src/configuration/migration/v9.rs @@ -17,6 +17,7 @@ //! A module that is responsible for migration of storage. use crate::configuration::{self, Config, Pallet}; +use alloc::vec::Vec; use frame_support::{ pallet_prelude::*, traits::{Defensive, StorageVersion}, @@ -28,7 +29,6 @@ use polkadot_primitives::{ ON_DEMAND_DEFAULT_QUEUE_MAX_SIZE, }; use sp_runtime::Perbill; -use sp_std::vec::Vec; use frame_support::traits::OnRuntimeUpgrade; @@ -164,7 +164,7 @@ mod v9 { >; } -pub struct MigrateToV9(sp_std::marker::PhantomData); +pub struct MigrateToV9(core::marker::PhantomData); impl OnRuntimeUpgrade for MigrateToV9 { #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { diff --git a/polkadot/runtime/parachains/src/coretime/migration.rs b/polkadot/runtime/parachains/src/coretime/migration.rs index 3f82472da8aa4ed15d26230693a7ef7d3d586c79..4e75088675590e54fa6d8dc040732cc032cc0732 100644 --- a/polkadot/runtime/parachains/src/coretime/migration.rs +++ b/polkadot/runtime/parachains/src/coretime/migration.rs @@ -26,10 +26,12 @@ mod v_coretime { coretime::{mk_coretime_call, Config, PartsOf57600, WeightInfo}, paras, }; + use alloc::{vec, vec::Vec}; #[cfg(feature = "try-runtime")] use codec::Decode; #[cfg(feature = "try-runtime")] use codec::Encode; + use core::{iter, result}; #[cfg(feature = "try-runtime")] use frame_support::ensure; use frame_support::{ @@ -43,9 +45,6 @@ mod v_coretime { use sp_arithmetic::traits::SaturatedConversion; use sp_core::Get; use sp_runtime::BoundedVec; - #[cfg(feature = "try-runtime")] - use sp_std::vec::Vec; - use sp_std::{iter, prelude::*, result}; use xcm::prelude::{send_xcm, Instruction, Junction, Location, SendError, WeightLimit, Xcm}; /// Return information about a legacy lease of a parachain. @@ -59,7 +58,7 @@ mod v_coretime { /// This assumes that the `Coretime` and the `AssignerCoretime` pallets are added at the same /// time to a runtime. pub struct MigrateToCoretime( - sp_std::marker::PhantomData<(T, SendXcm, LegacyLease)>, + core::marker::PhantomData<(T, SendXcm, LegacyLease)>, ); impl>> diff --git a/polkadot/runtime/parachains/src/coretime/mod.rs b/polkadot/runtime/parachains/src/coretime/mod.rs index fc8a3c7d9d24b217d1de883c6cb3ed8b3f7be6e2..1c38b3989232b754491f9fe00a6eb49b7433b810 100644 --- a/polkadot/runtime/parachains/src/coretime/mod.rs +++ b/polkadot/runtime/parachains/src/coretime/mod.rs @@ -18,6 +18,8 @@ //! //! +use alloc::{vec, vec::Vec}; +use core::result; use frame_support::{ pallet_prelude::*, traits::{defensive_prelude::*, Currency}, @@ -28,7 +30,6 @@ use pallet_broker::{CoreAssignment, CoreIndex as BrokerCoreIndex}; use polkadot_primitives::{Balance, BlockNumber, CoreIndex, Id as ParaId}; use sp_arithmetic::traits::SaturatedConversion; use sp_runtime::traits::TryConvert; -use sp_std::{prelude::*, result}; use xcm::{ prelude::{send_xcm, Instruction, Junction, Location, OriginKind, SendXcm, WeightLimit, Xcm}, v4::{ diff --git a/polkadot/runtime/parachains/src/disputes.rs b/polkadot/runtime/parachains/src/disputes.rs index 4a0f2390b45dc87b1e4eb3425ee430e0499d3895..f86573dadf562fee7b4cb63190399cbe390a4865 100644 --- a/polkadot/runtime/parachains/src/disputes.rs +++ b/polkadot/runtime/parachains/src/disputes.rs @@ -19,8 +19,10 @@ use crate::{ configuration, initializer::SessionChangeNotification, metrics::METRICS, session_info, }; +use alloc::{collections::btree_set::BTreeSet, vec::Vec}; use bitvec::{bitvec, order::Lsb0 as BitOrderLsb0}; use codec::{Decode, Encode}; +use core::cmp::Ordering; use frame_support::{ensure, weights::Weight}; use frame_system::pallet_prelude::*; use polkadot_primitives::{ @@ -36,7 +38,6 @@ use sp_runtime::{ traits::{AppVerify, One, Saturating, Zero}, DispatchError, RuntimeDebug, SaturatedConversion, }; -use sp_std::{cmp::Ordering, collections::btree_set::BTreeSet, prelude::*}; #[cfg(test)] #[allow(unused_imports)] diff --git a/polkadot/runtime/parachains/src/disputes/migration.rs b/polkadot/runtime/parachains/src/disputes/migration.rs index e12edffb51b38d83e016d79dabe62c83ee20a098..dd32340c9f64f357913a99d6a50f166f9a9382f2 100644 --- a/polkadot/runtime/parachains/src/disputes/migration.rs +++ b/polkadot/runtime/parachains/src/disputes/migration.rs @@ -21,16 +21,16 @@ use frame_support::traits::StorageVersion; pub mod v1 { use super::*; use crate::disputes::{Config, Pallet}; + use alloc::vec::Vec; use frame_support::{ pallet_prelude::*, storage_alias, traits::OnRuntimeUpgrade, weights::Weight, }; use polkadot_primitives::SessionIndex; - use sp_std::prelude::*; #[storage_alias] type SpamSlots = StorageMap, Twox64Concat, SessionIndex, Vec>; - pub struct MigrateToV1(sp_std::marker::PhantomData); + pub struct MigrateToV1(core::marker::PhantomData); impl OnRuntimeUpgrade for MigrateToV1 { fn on_runtime_upgrade() -> Weight { let mut weight: Weight = Weight::zero(); diff --git a/polkadot/runtime/parachains/src/disputes/slashing.rs b/polkadot/runtime/parachains/src/disputes/slashing.rs index b50853ecc696c79d5d8b94cda6161f6d912c96f3..4b76fb47e1f8d5fff51e13274931514930ef5de7 100644 --- a/polkadot/runtime/parachains/src/disputes/slashing.rs +++ b/polkadot/runtime/parachains/src/disputes/slashing.rs @@ -50,6 +50,12 @@ use frame_support::{ }; use frame_system::pallet_prelude::BlockNumberFor; +use alloc::{ + boxed::Box, + collections::{btree_map::Entry, btree_set::BTreeSet}, + vec, + vec::Vec, +}; use polkadot_primitives::{ slashing::{DisputeProof, DisputesTimeSlot, PendingSlashes, SlashingOffenceKind}, CandidateHash, SessionIndex, ValidatorId, ValidatorIndex, @@ -65,10 +71,6 @@ use sp_runtime::{ }; use sp_session::{GetSessionNumber, GetValidatorCount}; use sp_staking::offence::{Kind, Offence, OffenceError, ReportOffence}; -use sp_std::{ - collections::{btree_map::Entry, btree_set::BTreeSet}, - prelude::*, -}; const LOG_TARGET: &str = "runtime::parachains::slashing"; @@ -158,7 +160,7 @@ impl SlashingOffence { /// This type implements `SlashingHandler`. pub struct SlashValidatorsForDisputes { - _phantom: sp_std::marker::PhantomData, + _phantom: core::marker::PhantomData, } impl Default for SlashValidatorsForDisputes { @@ -640,7 +642,7 @@ fn is_known_offence( /// When configured properly, should be instantiated with /// `T::KeyOwnerIdentification, Offences, ReportLongevity` parameters. pub struct SlashingReportHandler { - _phantom: sp_std::marker::PhantomData<(I, R, L)>, + _phantom: core::marker::PhantomData<(I, R, L)>, } impl Default for SlashingReportHandler { diff --git a/polkadot/runtime/parachains/src/dmp.rs b/polkadot/runtime/parachains/src/dmp.rs index c0e1635ba1692c3f3d62a13bb686e95d3511bc0a..54e112d1b8b44206b8a121dd082c60718662e14a 100644 --- a/polkadot/runtime/parachains/src/dmp.rs +++ b/polkadot/runtime/parachains/src/dmp.rs @@ -46,6 +46,8 @@ use crate::{ configuration::{self, HostConfiguration}, initializer, FeeTracker, }; +use alloc::vec::Vec; +use core::fmt; use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::BlockNumberFor; use polkadot_primitives::{DownwardMessage, Hash, Id as ParaId, InboundDownwardMessage}; @@ -54,7 +56,6 @@ use sp_runtime::{ traits::{BlakeTwo256, Hash as HashT, SaturatedConversion}, FixedU128, Saturating, }; -use sp_std::{fmt, prelude::*}; use xcm::latest::SendError; pub use pallet::*; diff --git a/polkadot/runtime/parachains/src/hrmp.rs b/polkadot/runtime/parachains/src/hrmp.rs index e34e4a03e711c3592f66a303fb8a2c4d37b64db8..8b01a755c3c7bd75d558989fd593a44334c906b6 100644 --- a/polkadot/runtime/parachains/src/hrmp.rs +++ b/polkadot/runtime/parachains/src/hrmp.rs @@ -18,7 +18,13 @@ use crate::{ configuration::{self, HostConfiguration}, dmp, ensure_parachain, initializer, paras, }; +use alloc::{ + collections::{btree_map::BTreeMap, btree_set::BTreeSet}, + vec, + vec::Vec, +}; use codec::{Decode, Encode}; +use core::{fmt, mem}; use frame_support::{pallet_prelude::*, traits::ReservableCurrency, DefaultNoBound}; use frame_system::pallet_prelude::*; use polkadot_parachain_primitives::primitives::{HorizontalMessages, IsSystem}; @@ -31,11 +37,6 @@ use sp_runtime::{ traits::{AccountIdConversion, BlakeTwo256, Hash as HashT, UniqueSaturatedInto, Zero}, ArithmeticError, }; -use sp_std::{ - collections::{btree_map::BTreeMap, btree_set::BTreeSet}, - fmt, mem, - prelude::*, -}; pub use pallet::*; @@ -487,7 +488,7 @@ pub mod pallet { #[derive(DefaultNoBound)] pub struct GenesisConfig { #[serde(skip)] - _config: sp_std::marker::PhantomData, + _config: core::marker::PhantomData, preopen_hrmp_channels: Vec<(ParaId, ParaId, u32, u32)>, } diff --git a/polkadot/runtime/parachains/src/hrmp/tests.rs b/polkadot/runtime/parachains/src/hrmp/tests.rs index 4fcbc69e98ad8e905afa5b18cd52dc526d6f0c67..52db932c7962b49f0e7f4d99de7527d38882237d 100644 --- a/polkadot/runtime/parachains/src/hrmp/tests.rs +++ b/polkadot/runtime/parachains/src/hrmp/tests.rs @@ -27,8 +27,9 @@ use crate::{ }, shared, }; -use frame_support::{assert_noop, assert_ok, error::BadOrigin}; +use frame_support::{assert_noop, assert_ok}; use polkadot_primitives::{BlockNumber, InboundDownwardMessage}; +use sp_runtime::traits::BadOrigin; use std::collections::BTreeMap; pub(crate) fn run_to_block(to: BlockNumber, new_session: Option>) { diff --git a/polkadot/runtime/parachains/src/inclusion/migration.rs b/polkadot/runtime/parachains/src/inclusion/migration.rs index a340d52643e05df356889a95186170c1e615480e..36a810d341c655cf9309b9b8fec87032a8bc7486 100644 --- a/polkadot/runtime/parachains/src/inclusion/migration.rs +++ b/polkadot/runtime/parachains/src/inclusion/migration.rs @@ -73,9 +73,9 @@ mod v1 { CandidatePendingAvailability as V1CandidatePendingAvailability, Config, Pallet, PendingAvailability as V1PendingAvailability, }; + use alloc::{collections::vec_deque::VecDeque, vec::Vec}; use frame_support::{traits::UncheckedOnRuntimeUpgrade, weights::Weight}; use sp_core::Get; - use sp_std::{collections::vec_deque::VecDeque, vec::Vec}; #[cfg(feature = "try-runtime")] use codec::{Decode, Encode}; @@ -85,7 +85,7 @@ mod v1 { traits::{GetStorageVersion, StorageVersion}, }; - pub struct VersionUncheckedMigrateToV1(sp_std::marker::PhantomData); + pub struct VersionUncheckedMigrateToV1(core::marker::PhantomData); impl UncheckedOnRuntimeUpgrade for VersionUncheckedMigrateToV1 { #[cfg(feature = "try-runtime")] diff --git a/polkadot/runtime/parachains/src/inclusion/mod.rs b/polkadot/runtime/parachains/src/inclusion/mod.rs index a86941a1a0b8e5d4f56eeb50ccf20a6dd81cc62c..281dc5d0c5f47ae56eac005ae8f04d0960e7f204 100644 --- a/polkadot/runtime/parachains/src/inclusion/mod.rs +++ b/polkadot/runtime/parachains/src/inclusion/mod.rs @@ -27,8 +27,15 @@ use crate::{ shared::{self, AllowedRelayParentsTracker}, util::make_persisted_validation_data_with_parent, }; +use alloc::{ + collections::{btree_map::BTreeMap, btree_set::BTreeSet, vec_deque::VecDeque}, + vec, + vec::Vec, +}; use bitvec::{order::Lsb0 as BitOrderLsb0, vec::BitVec}; use codec::{Decode, Encode}; +#[cfg(feature = "std")] +use core::fmt; use frame_support::{ defensive, pallet_prelude::*, @@ -46,12 +53,6 @@ use polkadot_primitives::{ }; use scale_info::TypeInfo; use sp_runtime::{traits::One, DispatchError, SaturatedConversion, Saturating}; -#[cfg(feature = "std")] -use sp_std::fmt; -use sp_std::{ - collections::{btree_map::BTreeMap, btree_set::BTreeSet, vec_deque::VecDeque}, - prelude::*, -}; pub use pallet::*; diff --git a/polkadot/runtime/parachains/src/initializer.rs b/polkadot/runtime/parachains/src/initializer.rs index fd0f1c3c065118f81821b0f8587335537421135d..340f727097b58245d9fa9a2553f9e178544bcea1 100644 --- a/polkadot/runtime/parachains/src/initializer.rs +++ b/polkadot/runtime/parachains/src/initializer.rs @@ -25,6 +25,7 @@ use crate::{ disputes::{self, DisputesHandler as _, SlashingHandler as _}, dmp, hrmp, inclusion, paras, scheduler, session_info, shared, }; +use alloc::vec::Vec; use codec::{Decode, Encode}; use frame_support::{ traits::{OneSessionHandler, Randomness}, @@ -33,7 +34,6 @@ use frame_support::{ use frame_system::limits::BlockWeights; use polkadot_primitives::{BlockNumber, ConsensusLog, SessionIndex, ValidatorId}; use scale_info::TypeInfo; -use sp_std::prelude::*; #[cfg(test)] mod tests; @@ -249,7 +249,7 @@ impl Pallet { // TODO: audit usage of randomness API // https://github.com/paritytech/polkadot/issues/2601 let (random_hash, _) = T::Randomness::random(&b"paras"[..]); - let len = sp_std::cmp::min(32, random_hash.as_ref().len()); + let len = core::cmp::min(32, random_hash.as_ref().len()); buf[..len].copy_from_slice(&random_hash.as_ref()[..len]); buf }; diff --git a/polkadot/runtime/parachains/src/lib.rs b/polkadot/runtime/parachains/src/lib.rs index 51110e89416c373efb1a5226a812ae6ab9f88431..f2995d770e716447a5ada5b816a255b3725b2982 100644 --- a/polkadot/runtime/parachains/src/lib.rs +++ b/polkadot/runtime/parachains/src/lib.rs @@ -53,6 +53,8 @@ mod mock; #[cfg(test)] mod ump_tests; +extern crate alloc; + pub use origin::{ensure_parachain, Origin}; pub use paras::{ParaLifecycle, UpgradeStrategy}; use polkadot_primitives::{HeadData, Id as ParaId, ValidationCode}; diff --git a/polkadot/runtime/parachains/src/mock.rs b/polkadot/runtime/parachains/src/mock.rs index 9c23347ebb58bb93bf72e2d94a1f95defcea27b9..45576668f6d6267e414e656b411fc593e6f5450f 100644 --- a/polkadot/runtime/parachains/src/mock.rs +++ b/polkadot/runtime/parachains/src/mock.rs @@ -51,11 +51,10 @@ use sp_runtime::{ transaction_validity::TransactionPriority, BuildStorage, FixedU128, Perbill, Permill, }; -use sp_std::{ +use std::{ cell::RefCell, - collections::{btree_map::BTreeMap, vec_deque::VecDeque}, + collections::{btree_map::BTreeMap, vec_deque::VecDeque, HashMap}, }; -use std::collections::HashMap; use xcm::{ prelude::XcmVersion, v4::{Assets, InteriorLocation, Location, SendError, SendResult, SendXcm, Xcm, XcmHash}, @@ -677,7 +676,7 @@ impl inclusion::RewardValidators for TestRewardValidators { /// Create a new set of test externalities. pub fn new_test_ext(state: MockGenesisConfig) -> TestExternalities { use sp_keystore::{testing::MemoryKeystore, KeystoreExt, KeystorePtr}; - use sp_std::sync::Arc; + use std::sync::Arc; sp_tracing::try_init_simple(); diff --git a/polkadot/runtime/parachains/src/origin.rs b/polkadot/runtime/parachains/src/origin.rs index 5202cba232d20a9f4303747f55c50ce144a0d68f..fd22929b08ff547398c7f731e9a823a780391a6c 100644 --- a/polkadot/runtime/parachains/src/origin.rs +++ b/polkadot/runtime/parachains/src/origin.rs @@ -16,9 +16,9 @@ //! Declaration of the parachain specific origin and a pallet that hosts it. +use core::result; use polkadot_primitives::Id as ParaId; use sp_runtime::traits::BadOrigin; -use sp_std::result; pub use pallet::*; diff --git a/polkadot/runtime/parachains/src/paras/benchmarking.rs b/polkadot/runtime/parachains/src/paras/benchmarking.rs index 0f3318612a77c7bc2ec831e2c7ac67c08eae0392..7bf8b833ed915df49aabcb9047ec889076836af0 100644 --- a/polkadot/runtime/parachains/src/paras/benchmarking.rs +++ b/polkadot/runtime/parachains/src/paras/benchmarking.rs @@ -16,6 +16,7 @@ use super::*; use crate::configuration::HostConfiguration; +use alloc::vec; use frame_benchmarking::benchmarks; use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; use polkadot_primitives::{ @@ -23,6 +24,7 @@ use polkadot_primitives::{ }; use sp_runtime::traits::{One, Saturating}; +pub mod mmr_setup; mod pvf_check; use self::pvf_check::{VoteCause, VoteOutcome}; diff --git a/polkadot/runtime/parachains/src/paras/benchmarking/mmr_setup.rs b/polkadot/runtime/parachains/src/paras/benchmarking/mmr_setup.rs new file mode 100644 index 0000000000000000000000000000000000000000..ab007692e78dc2e3b56dfdd4ad682accdfa0c037 --- /dev/null +++ b/polkadot/runtime/parachains/src/paras/benchmarking/mmr_setup.rs @@ -0,0 +1,40 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Polkadot is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Polkadot. If not, see . + +//! Implements benchmarking setup for the `merkle-mountain-range` pallet. + +use crate::paras::*; +use pallet_mmr::BenchmarkHelper; +use sp_std::vec; + +/// Struct to setup benchmarks for the `merkle-mountain-range` pallet. +pub struct MmrSetup(core::marker::PhantomData); + +impl BenchmarkHelper for MmrSetup +where + T: Config, +{ + fn setup() { + // Create a head with 1024 bytes of data. + let head = vec![42u8; 1024]; + + for para in 0..MAX_PARA_HEADS { + let id = (para as u32).into(); + let h = head.clone().into(); + Pallet::::heads_insert(&id, h); + } + } +} diff --git a/polkadot/runtime/parachains/src/paras/benchmarking/pvf_check.rs b/polkadot/runtime/parachains/src/paras/benchmarking/pvf_check.rs index 0bf5fe783a0e7bc51e473240f87bcdb7692e5414..80443c7626e2b438ff754d140aa22f91bdc16805 100644 --- a/polkadot/runtime/parachains/src/paras/benchmarking/pvf_check.rs +++ b/polkadot/runtime/parachains/src/paras/benchmarking/pvf_check.rs @@ -17,6 +17,7 @@ //! This module focuses on the benchmarking of the `include_pvf_check_statement` dispatchable. use crate::{configuration, paras::*, shared::Pallet as ParasShared}; +use alloc::{vec, vec::Vec}; use frame_support::assert_ok; use frame_system::RawOrigin; use polkadot_primitives::{HeadData, Id as ParaId, ValidationCode, ValidatorId, ValidatorIndex}; diff --git a/polkadot/runtime/parachains/src/paras/mod.rs b/polkadot/runtime/parachains/src/paras/mod.rs index 8cffcbbbb024fd454f57ed89c7448ffc297e0977..a4c404de2a651d0a4359a59fa9efb66b275defe8 100644 --- a/polkadot/runtime/parachains/src/paras/mod.rs +++ b/polkadot/runtime/parachains/src/paras/mod.rs @@ -113,8 +113,10 @@ use crate::{ initializer::SessionChangeNotification, shared, }; +use alloc::{collections::btree_set::BTreeSet, vec::Vec}; use bitvec::{order::Lsb0 as BitOrderLsb0, vec::BitVec}; use codec::{Decode, Encode}; +use core::{cmp, mem}; use frame_support::{pallet_prelude::*, traits::EstimateNextSessionRotation, DefaultNoBound}; use frame_system::pallet_prelude::*; use polkadot_primitives::{ @@ -127,14 +129,13 @@ use sp_runtime::{ traits::{AppVerify, One, Saturating}, DispatchResult, SaturatedConversion, }; -use sp_std::{cmp, collections::btree_set::BTreeSet, mem, prelude::*}; use serde::{Deserialize, Serialize}; pub use crate::Origin as ParachainOrigin; #[cfg(feature = "runtime-benchmarks")] -pub(crate) mod benchmarking; +pub mod benchmarking; #[cfg(test)] pub(crate) mod tests; @@ -863,7 +864,7 @@ pub mod pallet { #[derive(DefaultNoBound)] pub struct GenesisConfig { #[serde(skip)] - pub _config: sp_std::marker::PhantomData, + pub _config: core::marker::PhantomData, pub paras: Vec<(ParaId, ParaGenesisArgs)>, } @@ -1221,6 +1222,15 @@ const INVALID_TX_BAD_VALIDATOR_IDX: u8 = 1; const INVALID_TX_BAD_SUBJECT: u8 = 2; const INVALID_TX_DOUBLE_VOTE: u8 = 3; +/// This is intermediate "fix" for this issue: +/// +/// +/// It does not actually fix it, but makes the worst case better. Without that limit someone +/// could completely DoS the relay chain by registering a ridiculously high amount of paras. +/// With this limit the same attack could lead to some parachains ceasing to being able to +/// communicate via offchain XCMP. Snowbridge will still work as it only cares about `BridgeHub`. +pub const MAX_PARA_HEADS: usize = 1024; + impl Pallet { /// This is a call to schedule code upgrades for parachains which is safe to be called /// outside of this module. That means this function does all checks necessary to ensure @@ -1290,6 +1300,16 @@ impl Pallet { }) } + /// Get a list of the first [`MAX_PARA_HEADS`] para heads sorted by para_id. + /// This method is likely to be removed in the future. + pub fn sorted_para_heads() -> Vec<(u32, Vec)> { + let mut heads: Vec<(u32, Vec)> = + Heads::::iter().map(|(id, head)| (id.into(), head.0)).collect(); + heads.sort_by_key(|(id, _)| *id); + heads.truncate(MAX_PARA_HEADS); + heads + } + // Apply all para actions queued for the given session index. // // The actions to take are based on the lifecycle of of the paras. diff --git a/polkadot/runtime/parachains/src/paras_inherent/benchmarking.rs b/polkadot/runtime/parachains/src/paras_inherent/benchmarking.rs index 4c8b093451ed5ac1e917ab980539bc8277374d70..c5284ba1dd1f850d5fdabc7bfd782b488ea12cba 100644 --- a/polkadot/runtime/parachains/src/paras_inherent/benchmarking.rs +++ b/polkadot/runtime/parachains/src/paras_inherent/benchmarking.rs @@ -16,9 +16,10 @@ use super::*; use crate::{inclusion, ParaId}; +use alloc::collections::btree_map::BTreeMap; +use core::cmp::min; use frame_benchmarking::{benchmarks, impl_benchmark_test_suite}; use frame_system::RawOrigin; -use sp_std::{cmp::min, collections::btree_map::BTreeMap}; use polkadot_primitives::v7::GroupIndex; diff --git a/polkadot/runtime/parachains/src/paras_inherent/misc.rs b/polkadot/runtime/parachains/src/paras_inherent/misc.rs index dac9e6e256d0ef60c6b18b51d48f44c65e1cae8f..2858c3f95de2602e5020646f69d58ef54a63d97a 100644 --- a/polkadot/runtime/parachains/src/paras_inherent/misc.rs +++ b/polkadot/runtime/parachains/src/paras_inherent/misc.rs @@ -14,7 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -use sp_std::{cmp::Ordering, vec::Vec}; +use alloc::vec::Vec; +use core::cmp::Ordering; /// A helper trait to allow calling retain while getting access /// to the index of the item in the `vec`. diff --git a/polkadot/runtime/parachains/src/paras_inherent/mod.rs b/polkadot/runtime/parachains/src/paras_inherent/mod.rs index 8b527c09490d65c95d268e22d6be4a904d514e02..fe4eef16f02279badc275cd89652ff26435a8dff 100644 --- a/polkadot/runtime/parachains/src/paras_inherent/mod.rs +++ b/polkadot/runtime/parachains/src/paras_inherent/mod.rs @@ -32,6 +32,11 @@ use crate::{ shared::{self, AllowedRelayParentsTracker}, ParaId, }; +use alloc::{ + collections::{btree_map::BTreeMap, btree_set::BTreeSet}, + vec, + vec::Vec, +}; use bitvec::prelude::BitVec; use frame_support::{ defensive, @@ -53,11 +58,6 @@ use polkadot_primitives::{ use rand::{seq::SliceRandom, SeedableRng}; use scale_info::TypeInfo; use sp_runtime::traits::{Header as HeaderT, One}; -use sp_std::{ - collections::{btree_map::BTreeMap, btree_set::BTreeSet}, - prelude::*, - vec::Vec, -}; mod misc; mod weights; @@ -295,7 +295,7 @@ impl Pallet { fn process_inherent_data( data: ParachainsInherentData>, context: ProcessInherentDataContext, - ) -> sp_std::result::Result< + ) -> core::result::Result< (ParachainsInherentData>, PostDispatchInfo), DispatchErrorWithPostInfo, > { @@ -762,7 +762,7 @@ pub(crate) fn apply_weight_limit( let mut chained_candidates: Vec> = Vec::new(); let mut current_para_id = None; - for candidate in sp_std::mem::take(candidates).into_iter() { + for candidate in core::mem::take(candidates).into_iter() { let candidate_para_id = candidate.descriptor().para_id; if Some(candidate_para_id) == current_para_id { let chain = chained_candidates diff --git a/polkadot/runtime/parachains/src/paras_inherent/tests.rs b/polkadot/runtime/parachains/src/paras_inherent/tests.rs index abf1c1a56b24b9ee27db011d4538d5864a10c556..0d5653eb729d6114abf6e3f5dcd334b8506fec0c 100644 --- a/polkadot/runtime/parachains/src/paras_inherent/tests.rs +++ b/polkadot/runtime/parachains/src/paras_inherent/tests.rs @@ -53,13 +53,13 @@ mod enter { }, session_info, }; + use alloc::collections::btree_map::BTreeMap; use assert_matches::assert_matches; use core::panic; use frame_support::assert_ok; use frame_system::limits; use polkadot_primitives::{vstaging::SchedulerParams, AvailabilityBitfield, UncheckedSigned}; use sp_runtime::Perbill; - use sp_std::collections::btree_map::BTreeMap; struct TestConfig { dispute_statements: BTreeMap, @@ -1744,8 +1744,8 @@ mod sanitizers { scheduler::{common::Assignment, ParasEntry}, util::{make_persisted_validation_data, make_persisted_validation_data_with_parent}, }; + use alloc::collections::vec_deque::VecDeque; use polkadot_primitives::ValidationCode; - use sp_std::collections::vec_deque::VecDeque; use super::*; diff --git a/polkadot/runtime/parachains/src/reward_points.rs b/polkadot/runtime/parachains/src/reward_points.rs index 5f45445b0ba2a29cddc3806b84a25cbdcb1ce77d..69ef2db756c217e022cb37b5a0eefeeabb938171 100644 --- a/polkadot/runtime/parachains/src/reward_points.rs +++ b/polkadot/runtime/parachains/src/reward_points.rs @@ -22,9 +22,9 @@ //! for the time being, although we will build schemes to do so in the future. use crate::{session_info, shared}; +use alloc::collections::btree_set::BTreeSet; use frame_support::traits::{Defensive, ValidatorSet}; use polkadot_primitives::{SessionIndex, ValidatorIndex}; -use sp_std::collections::btree_set::BTreeSet; /// The amount of era points given by backing a candidate that is included. pub const BACKING_POINTS: u32 = 20; @@ -32,7 +32,7 @@ pub const BACKING_POINTS: u32 = 20; pub const DISPUTE_STATEMENT_POINTS: u32 = 20; /// Rewards validators for participating in parachains with era points in pallet-staking. -pub struct RewardValidatorsWithEraPoints(sp_std::marker::PhantomData); +pub struct RewardValidatorsWithEraPoints(core::marker::PhantomData); impl RewardValidatorsWithEraPoints where diff --git a/polkadot/runtime/parachains/src/runtime_api_impl/v10.rs b/polkadot/runtime/parachains/src/runtime_api_impl/v10.rs index 4417ec75abd67bb1ba50b616ceb137e42cf6a7f6..697890232211315af749a365c95fa8cc23425450 100644 --- a/polkadot/runtime/parachains/src/runtime_api_impl/v10.rs +++ b/polkadot/runtime/parachains/src/runtime_api_impl/v10.rs @@ -22,6 +22,7 @@ use crate::{ scheduler::{self, CoreOccupied}, session_info, shared, }; +use alloc::{collections::btree_map::BTreeMap, vec, vec::Vec}; use frame_support::traits::{GetStorageVersion, StorageVersion}; use frame_system::pallet_prelude::*; use polkadot_primitives::{ @@ -37,7 +38,6 @@ use polkadot_primitives::{ ValidatorId, ValidatorIndex, ValidatorSignature, }; use sp_runtime::traits::One; -use sp_std::{collections::btree_map::BTreeMap, prelude::*}; /// Implementation for the `validators` function of the runtime API. pub fn validators() -> Vec { diff --git a/polkadot/runtime/parachains/src/runtime_api_impl/vstaging.rs b/polkadot/runtime/parachains/src/runtime_api_impl/vstaging.rs index f4e3db185fead7144e6cb0ae3455af98229d59f7..4aa381e33b1bc2246abd3c16044cc56290597b12 100644 --- a/polkadot/runtime/parachains/src/runtime_api_impl/vstaging.rs +++ b/polkadot/runtime/parachains/src/runtime_api_impl/vstaging.rs @@ -17,12 +17,12 @@ //! Put implementations of functions from staging APIs here. use crate::{configuration, inclusion, initializer, scheduler}; -use polkadot_primitives::{CommittedCandidateReceipt, CoreIndex, Id as ParaId}; -use sp_runtime::traits::One; -use sp_std::{ +use alloc::{ collections::{btree_map::BTreeMap, vec_deque::VecDeque}, vec::Vec, }; +use polkadot_primitives::{CommittedCandidateReceipt, CoreIndex, Id as ParaId}; +use sp_runtime::traits::One; /// Returns the claimqueue from the scheduler pub fn claim_queue() -> BTreeMap> { diff --git a/polkadot/runtime/parachains/src/scheduler.rs b/polkadot/runtime/parachains/src/scheduler.rs index d7fe5c06863c87413f988a972790c5d3482b513f..445583d929aba9a82322f8fb94a70d38632a4f8f 100644 --- a/polkadot/runtime/parachains/src/scheduler.rs +++ b/polkadot/runtime/parachains/src/scheduler.rs @@ -39,6 +39,13 @@ use core::iter::Peekable; use crate::{configuration, initializer::SessionChangeNotification, paras}; +use alloc::{ + collections::{ + btree_map::{self, BTreeMap}, + vec_deque::VecDeque, + }, + vec::Vec, +}; use frame_support::{pallet_prelude::*, traits::Defensive}; use frame_system::pallet_prelude::BlockNumberFor; pub use polkadot_core_primitives::v2::BlockNumber; @@ -46,13 +53,6 @@ use polkadot_primitives::{ CoreIndex, GroupIndex, GroupRotationInfo, Id as ParaId, ScheduledCore, ValidatorIndex, }; use sp_runtime::traits::One; -use sp_std::{ - collections::{ - btree_map::{self, BTreeMap}, - vec_deque::VecDeque, - }, - prelude::*, -}; pub mod common; @@ -314,10 +314,8 @@ impl Pallet { .into_iter() .filter(|(freed_index, _)| (freed_index.0 as usize) < c_len) .for_each(|(freed_index, freed_reason)| { - match sp_std::mem::replace( - &mut cores[freed_index.0 as usize], - CoreOccupied::Free, - ) { + match core::mem::replace(&mut cores[freed_index.0 as usize], CoreOccupied::Free) + { CoreOccupied::Free => {}, CoreOccupied::Paras(entry) => { match freed_reason { @@ -569,7 +567,7 @@ impl Pallet { fn push_occupied_cores_to_assignment_provider() { AvailabilityCores::::mutate(|cores| { for core in cores.iter_mut() { - match sp_std::mem::replace(core, CoreOccupied::Free) { + match core::mem::replace(core, CoreOccupied::Free) { CoreOccupied::Free => continue, CoreOccupied::Paras(entry) => { Self::maybe_push_assignment(entry); diff --git a/polkadot/runtime/parachains/src/scheduler/migration.rs b/polkadot/runtime/parachains/src/scheduler/migration.rs index 84d7d4b567102f6757409d88018f2d4e3072644b..125f105ef70668c8ebacfdb9e2b267b9d00bfcbf 100644 --- a/polkadot/runtime/parachains/src/scheduler/migration.rs +++ b/polkadot/runtime/parachains/src/scheduler/migration.rs @@ -17,6 +17,7 @@ //! A module that is responsible for migration of storage. use super::*; +use alloc::vec::Vec; use frame_support::{ migrations::VersionedMigration, pallet_prelude::ValueQuery, storage_alias, traits::UncheckedOnRuntimeUpgrade, weights::Weight, @@ -164,7 +165,7 @@ mod v1 { } /// Migration to V1 - pub struct UncheckedMigrateToV1(sp_std::marker::PhantomData); + pub struct UncheckedMigrateToV1(core::marker::PhantomData); impl UncheckedOnRuntimeUpgrade for UncheckedMigrateToV1 { fn on_runtime_upgrade() -> Weight { let mut weight: Weight = Weight::zero(); @@ -301,7 +302,7 @@ mod v2 { } /// Migration to V2 - pub struct UncheckedMigrateToV2(sp_std::marker::PhantomData); + pub struct UncheckedMigrateToV2(core::marker::PhantomData); impl UncheckedOnRuntimeUpgrade for UncheckedMigrateToV2 { fn on_runtime_upgrade() -> Weight { diff --git a/polkadot/runtime/parachains/src/scheduler/tests.rs b/polkadot/runtime/parachains/src/scheduler/tests.rs index 32811241e171cfd07af586bdf6b06b37df644603..f3866146e81121e7fe1ad85e09719df00a89a212 100644 --- a/polkadot/runtime/parachains/src/scheduler/tests.rs +++ b/polkadot/runtime/parachains/src/scheduler/tests.rs @@ -16,12 +16,12 @@ use super::*; +use alloc::collections::{btree_map::BTreeMap, btree_set::BTreeSet}; use frame_support::assert_ok; use polkadot_primitives::{ vstaging::SchedulerParams, BlockNumber, SessionIndex, ValidationCode, ValidatorId, }; use sp_keyring::Sr25519Keyring; -use sp_std::collections::{btree_map::BTreeMap, btree_set::BTreeSet}; use crate::{ configuration::HostConfiguration, diff --git a/polkadot/runtime/parachains/src/session_info.rs b/polkadot/runtime/parachains/src/session_info.rs index ff032f7e34d5efc130b5ce0859fd3160b6039d39..ea05c1aacaa946aa50bcb68e69930acbd60d79eb 100644 --- a/polkadot/runtime/parachains/src/session_info.rs +++ b/polkadot/runtime/parachains/src/session_info.rs @@ -24,6 +24,7 @@ use crate::{ configuration, paras, scheduler, shared, util::{take_active_subset, take_active_subset_and_inactive}, }; +use alloc::vec::Vec; use frame_support::{ pallet_prelude::*, traits::{OneSessionHandler, ValidatorSet, ValidatorSetWithIdentification}, @@ -32,7 +33,6 @@ use frame_system::pallet_prelude::BlockNumberFor; use polkadot_primitives::{ AssignmentId, AuthorityDiscoveryId, ExecutorParams, SessionIndex, SessionInfo, }; -use sp_std::vec::Vec; pub use pallet::*; diff --git a/polkadot/runtime/parachains/src/shared.rs b/polkadot/runtime/parachains/src/shared.rs index 417de1fa3fb0debeb8099d167859dc21e20329ca..154b7cfefc3aca68b3773b49194dba7038feccc5 100644 --- a/polkadot/runtime/parachains/src/shared.rs +++ b/polkadot/runtime/parachains/src/shared.rs @@ -19,14 +19,14 @@ //! To avoid cyclic dependencies, it is important that this pallet is not //! dependent on any of the other pallets. +use alloc::{ + collections::{btree_map::BTreeMap, vec_deque::VecDeque}, + vec::Vec, +}; use frame_support::{pallet_prelude::*, traits::DisabledValidators}; use frame_system::pallet_prelude::BlockNumberFor; use polkadot_primitives::{SessionIndex, ValidatorId, ValidatorIndex}; use sp_runtime::traits::AtLeast32BitUnsigned; -use sp_std::{ - collections::{btree_map::BTreeMap, vec_deque::VecDeque}, - vec::Vec, -}; use rand::{seq::SliceRandom, SeedableRng}; use rand_chacha::ChaCha20Rng; diff --git a/polkadot/runtime/parachains/src/ump_tests.rs b/polkadot/runtime/parachains/src/ump_tests.rs index 4d6da8c9e3c1ba9047ebba784138869733f33ec7..d914bf8b666120fba1c3db2f85f3420427fb9186 100644 --- a/polkadot/runtime/parachains/src/ump_tests.rs +++ b/polkadot/runtime/parachains/src/ump_tests.rs @@ -34,7 +34,6 @@ use frame_support::{ use polkadot_primitives::{well_known_keys, Id as ParaId, UpwardMessage}; use sp_crypto_hashing::{blake2_256, twox_64}; use sp_runtime::traits::Bounded; -use sp_std::prelude::*; pub(super) struct GenesisConfigBuilder { max_upward_message_size: u32, diff --git a/polkadot/runtime/parachains/src/util.rs b/polkadot/runtime/parachains/src/util.rs index cb2deffd7f6593ac69ea1fd7f10d5dfee9dc4577..3588e494438d066ffd925b2b2cc486431b8feab8 100644 --- a/polkadot/runtime/parachains/src/util.rs +++ b/polkadot/runtime/parachains/src/util.rs @@ -17,9 +17,9 @@ //! Utilities that don't belong to any particular module but may draw //! on all modules. +use alloc::{collections::btree_set::BTreeSet, vec::Vec}; use frame_system::pallet_prelude::BlockNumberFor; use polkadot_primitives::{HeadData, Id as ParaId, PersistedValidationData, ValidatorIndex}; -use sp_std::{collections::btree_set::BTreeSet, vec::Vec}; use crate::{configuration, hrmp, paras}; @@ -118,7 +118,7 @@ pub fn take_active_subset(active: &[ValidatorIndex], set: &[T]) -> Vec #[cfg(test)] mod tests { - use sp_std::vec::Vec; + use alloc::vec::Vec; use crate::util::{split_active_subset, take_active_subset}; use polkadot_primitives::ValidatorIndex; diff --git a/polkadot/runtime/rococo/Cargo.toml b/polkadot/runtime/rococo/Cargo.toml index c4fbd461a631849010e4d3de7ab98a7b743432fb..50970965e11e6ebbd4f984ed16c21be44cd978c6 100644 --- a/polkadot/runtime/rococo/Cargo.toml +++ b/polkadot/runtime/rococo/Cargo.toml @@ -32,7 +32,6 @@ sp-genesis-builder = { workspace = true } sp-inherents = { workspace = true } sp-offchain = { workspace = true } sp-arithmetic = { workspace = true } -sp-std = { workspace = true } sp-io = { workspace = true } sp-mmr-primitives = { workspace = true } sp-runtime = { workspace = true } @@ -209,7 +208,6 @@ std = [ "sp-runtime/std", "sp-session/std", "sp-staking/std", - "sp-std/std", "sp-storage/std", "sp-tracing/std", "sp-transaction-pool/std", @@ -228,6 +226,7 @@ runtime-benchmarks = [ "pallet-asset-rate/runtime-benchmarks", "pallet-babe/runtime-benchmarks", "pallet-balances/runtime-benchmarks", + "pallet-beefy-mmr/runtime-benchmarks", "pallet-bounties/runtime-benchmarks", "pallet-child-bounties/runtime-benchmarks", "pallet-collective/runtime-benchmarks", @@ -332,7 +331,10 @@ metadata-hash = ["substrate-wasm-builder/metadata-hash"] # Set timing constants (e.g. session period) to faster versions to speed up testing. fast-runtime = ["rococo-runtime-constants/fast-runtime"] -runtime-metrics = ["polkadot-runtime-parachains/runtime-metrics", "sp-io/with-tracing"] +runtime-metrics = [ + "polkadot-runtime-parachains/runtime-metrics", + "sp-io/with-tracing", +] # A feature that should be enabled when the runtime should be built for on-chain # deployment. This will disable stuff that shouldn't be part of the on-chain wasm diff --git a/polkadot/runtime/rococo/src/genesis_config_presets.rs b/polkadot/runtime/rococo/src/genesis_config_presets.rs index 1c70c94ce04840db1c25f525cca32fff8d99ffeb..67dcd6cd7a510d117eab9299793c7842db1b036e 100644 --- a/polkadot/runtime/rococo/src/genesis_config_presets.rs +++ b/polkadot/runtime/rococo/src/genesis_config_presets.rs @@ -17,6 +17,9 @@ //! Genesis configs presets for the Rococo runtime use crate::{SessionKeys, BABE_GENESIS_EPOCH_CONFIG}; +#[cfg(not(feature = "std"))] +use alloc::format; +use alloc::vec::Vec; use polkadot_primitives::{ vstaging::SchedulerParams, AccountId, AccountPublic, AssignmentId, ValidatorId, }; @@ -27,9 +30,6 @@ use sp_consensus_beefy::ecdsa_crypto::AuthorityId as BeefyId; use sp_consensus_grandpa::AuthorityId as GrandpaId; use sp_core::{sr25519, Pair, Public}; use sp_runtime::traits::IdentifyAccount; -#[cfg(not(feature = "std"))] -use sp_std::alloc::format; -use sp_std::vec::Vec; /// Helper function to generate a crypto pair from seed fn get_from_seed(seed: &str) -> ::Public { @@ -530,7 +530,7 @@ fn wococo_local_testnet_genesis() -> serde_json::Value { } /// Provides the JSON representation of predefined genesis config for given `id`. -pub fn get_preset(id: &sp_genesis_builder::PresetId) -> Option> { +pub fn get_preset(id: &sp_genesis_builder::PresetId) -> Option> { let patch = match id.try_into() { Ok("local_testnet") => rococo_local_testnet_genesis(), Ok("development") => rococo_development_config_genesis(), diff --git a/polkadot/runtime/rococo/src/impls.rs b/polkadot/runtime/rococo/src/impls.rs index 7b5c7b1fb4aca8b9e574734ca9bf21cf0bc5e527..a4440a1c6e0b986780454d6aaa1bce19ff5a85ad 100644 --- a/polkadot/runtime/rococo/src/impls.rs +++ b/polkadot/runtime/rococo/src/impls.rs @@ -15,13 +15,14 @@ // along with Polkadot. If not, see . use crate::xcm_config; +use alloc::{boxed::Box, vec}; use codec::{Decode, Encode}; +use core::marker::PhantomData; use frame_support::pallet_prelude::DispatchResult; use frame_system::RawOrigin; use polkadot_primitives::Balance; use polkadot_runtime_common::identity_migrator::{OnReapIdentity, WeightInfo}; use rococo_runtime_constants::currency::*; -use sp_std::{marker::PhantomData, prelude::*}; use xcm::{latest::prelude::*, VersionedLocation, VersionedXcm}; use xcm_executor::traits::TransactAsset; diff --git a/polkadot/runtime/rococo/src/lib.rs b/polkadot/runtime/rococo/src/lib.rs index ef629c7dad155b5b01426aca89631c13c75b1cad..c7da339b981544823ac7ac97f43a12d719061cb4 100644 --- a/polkadot/runtime/rococo/src/lib.rs +++ b/polkadot/runtime/rococo/src/lib.rs @@ -20,7 +20,15 @@ // `construct_runtime!` does a lot of recursion and requires us to increase the limit. #![recursion_limit = "512"] +extern crate alloc; + +use alloc::{ + collections::{btree_map::BTreeMap, vec_deque::VecDeque}, + vec, + vec::Vec, +}; use codec::{Decode, Encode, MaxEncodedLen}; +use core::cmp::Ordering; use frame_support::{ dynamic_params::{dynamic_pallet_params, dynamic_params}, traits::FromContains, @@ -68,11 +76,6 @@ use sp_consensus_beefy::{ mmr::{BeefyDataProvider, MmrLeafVersion}, }; use sp_genesis_builder::PresetId; -use sp_std::{ - cmp::Ordering, - collections::{btree_map::BTreeMap, vec_deque::VecDeque}, - prelude::*, -}; use frame_support::{ construct_runtime, derive_impl, @@ -1304,9 +1307,11 @@ impl pallet_mmr::Config for Runtime { const INDEXING_PREFIX: &'static [u8] = mmr::INDEXING_PREFIX; type Hashing = Keccak256; type OnNewRoot = pallet_beefy_mmr::DepositBeefyDigest; - type WeightInfo = (); type LeafData = pallet_beefy_mmr::Pallet; type BlockHashProvider = pallet_mmr::DefaultBlockHashProvider; + type WeightInfo = weights::pallet_mmr::WeightInfo; + #[cfg(feature = "runtime-benchmarks")] + type BenchmarkHelper = parachains_paras::benchmarking::mmr_setup::MmrSetup; } parameter_types! { @@ -1316,13 +1321,8 @@ parameter_types! { pub struct ParaHeadsRootProvider; impl BeefyDataProvider for ParaHeadsRootProvider { fn extra_data() -> H256 { - let mut para_heads: Vec<(u32, Vec)> = parachains_paras::Parachains::::get() - .into_iter() - .filter_map(|id| { - parachains_paras::Heads::::get(&id).map(|head| (id.into(), head.0)) - }) - .collect(); - para_heads.sort(); + let para_heads: Vec<(u32, Vec)> = + parachains_paras::Pallet::::sorted_para_heads(); binary_merkle_tree::merkle_root::( para_heads.into_iter().map(|pair| pair.encode()), ) @@ -1743,6 +1743,7 @@ mod benches { [pallet_identity, Identity] [pallet_indices, Indices] [pallet_message_queue, MessageQueue] + [pallet_mmr, Mmr] [pallet_multisig, Multisig] [pallet_parameters, Parameters] [pallet_preimage, Preimage] @@ -1845,7 +1846,7 @@ sp_api::impl_runtime_apis! { Runtime::metadata_at_version(version) } - fn metadata_versions() -> sp_std::vec::Vec { + fn metadata_versions() -> alloc::vec::Vec { Runtime::metadata_versions() } } @@ -2389,7 +2390,7 @@ sp_api::impl_runtime_apis! { } fn set_up_complex_asset_transfer( - ) -> Option<(Assets, u32, Location, Box)> { + ) -> Option<(Assets, u32, Location, alloc::boxed::Box)> { // Relay supports only native token, either reserve transfer it to non-system parachains, // or teleport it to system parachain. Use the teleport case for benchmarking as it's // slightly heavier. diff --git a/polkadot/runtime/rococo/src/validator_manager.rs b/polkadot/runtime/rococo/src/validator_manager.rs index 0677ba7fbb2b29afda7039ba8b396cb2d66131d8..ecfbff4fa0688486acebe0313d149d1d87cbab42 100644 --- a/polkadot/runtime/rococo/src/validator_manager.rs +++ b/polkadot/runtime/rococo/src/validator_manager.rs @@ -16,8 +16,8 @@ //! A pallet for managing validators on Rococo. +use alloc::vec::Vec; use sp_staking::SessionIndex; -use sp_std::vec::Vec; pub use pallet::*; diff --git a/polkadot/runtime/rococo/src/weights/mod.rs b/polkadot/runtime/rococo/src/weights/mod.rs index 3c6845dfb43e65e85dc33b2e288f35a9a8742e1e..c9204cc944fa47e3863285705395d4c7b0e63a47 100644 --- a/polkadot/runtime/rococo/src/weights/mod.rs +++ b/polkadot/runtime/rococo/src/weights/mod.rs @@ -25,6 +25,7 @@ pub mod pallet_conviction_voting; pub mod pallet_identity; pub mod pallet_indices; pub mod pallet_message_queue; +pub mod pallet_mmr; pub mod pallet_multisig; pub mod pallet_nis; pub mod pallet_parameters; diff --git a/polkadot/runtime/rococo/src/weights/pallet_mmr.rs b/polkadot/runtime/rococo/src/weights/pallet_mmr.rs new file mode 100644 index 0000000000000000000000000000000000000000..361bfc7a661b0737c936a95d20f1b6751db76aec --- /dev/null +++ b/polkadot/runtime/rococo/src/weights/pallet_mmr.rs @@ -0,0 +1,77 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Polkadot is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Polkadot. If not, see . + +//! Autogenerated weights for `pallet_mmr` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 +//! DATE: 2024-07-15, STEPS: `5`, REPEAT: `1`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("westend-dev")`, DB CACHE: 1024 + +// Executed Command: +// target/testnet/polkadot +// benchmark +// pallet +// --steps=5 +// --repeat=1 +// --extrinsic=* +// --wasm-execution=compiled +// --heap-pages=4096 +// --pallet=pallet_mmr +// --chain=westend-dev +// --header=./polkadot/file_header.txt +// --output=./polkadot/runtime/westend/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_mmr`. +pub struct WeightInfo(PhantomData); +impl pallet_mmr::WeightInfo for WeightInfo { + /// Storage: `Mmr::NumberOfLeaves` (r:1 w:1) + /// Proof: `Mmr::NumberOfLeaves` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) + /// Storage: `System::ParentHash` (r:1 w:0) + /// Proof: `System::ParentHash` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) + /// Storage: `Paras::Heads` (r:2049 w:0) + /// Proof: `Paras::Heads` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `BeefyMmrLeaf::BeefyNextAuthorities` (r:1 w:0) + /// Proof: `BeefyMmrLeaf::BeefyNextAuthorities` (`max_values`: Some(1), `max_size`: Some(44), added: 539, mode: `MaxEncodedLen`) + /// Storage: `System::Digest` (r:1 w:1) + /// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `Mmr::Nodes` (r:0 w:1000) + /// Proof: `Mmr::Nodes` (`max_values`: None, `max_size`: Some(40), added: 2515, mode: `MaxEncodedLen`) + /// Storage: `Mmr::RootHash` (r:0 w:1) + /// Proof: `Mmr::RootHash` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) + /// The range of component `x` is `[1, 1000]`. + fn on_initialize(x: u32) -> Weight { + // Proof Size summary in bytes: + // Measured: `2140817` + // Estimated: `7213082` + // Minimum execution time: 20_387_000_000 picoseconds. + Weight::from_parts(223_625_477_528, 0) + .saturating_add(Weight::from_parts(0, 7213082)) + // Standard Error: 310_550_970 + .saturating_add(Weight::from_parts(16_906_397_286, 0).saturating_mul(x.into())) + .saturating_add(T::DbWeight::get().reads(2053)) + .saturating_add(T::DbWeight::get().writes(3)) + .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(x.into()))) + } +} diff --git a/polkadot/runtime/rococo/src/weights/pallet_session.rs b/polkadot/runtime/rococo/src/weights/pallet_session.rs index dbeca534add8259fdf77010296d0c6d557365204..7f573d4e3952e8b0cdfbd1253d8c02bf389d5bb5 100644 --- a/polkadot/runtime/rococo/src/weights/pallet_session.rs +++ b/polkadot/runtime/rococo/src/weights/pallet_session.rs @@ -38,7 +38,7 @@ #![allow(unused_imports)] use frame_support::{traits::Get, weights::Weight}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Weight functions for `pallet_session`. pub struct WeightInfo(PhantomData); diff --git a/polkadot/runtime/rococo/src/weights/xcm/mod.rs b/polkadot/runtime/rococo/src/weights/xcm/mod.rs index 12f3df897b1eedb6e722e8f4871eb631bd35aaa3..bd2b0fbb8c061519f99ac1b33b53bb3a387ece74 100644 --- a/polkadot/runtime/rococo/src/weights/xcm/mod.rs +++ b/polkadot/runtime/rococo/src/weights/xcm/mod.rs @@ -18,8 +18,8 @@ mod pallet_xcm_benchmarks_fungible; mod pallet_xcm_benchmarks_generic; use crate::Runtime; +use alloc::vec::Vec; use frame_support::weights::Weight; -use sp_std::prelude::*; use xcm::{latest::prelude::*, DoubleEncoded}; use pallet_xcm_benchmarks_fungible::WeightInfo as XcmBalancesWeight; diff --git a/polkadot/runtime/rococo/src/xcm_config.rs b/polkadot/runtime/rococo/src/xcm_config.rs index 96416821e4c8396c20c45409fe3ec524ebee066b..05e0ee64820a421eb4a8bdb6d8bd7624edcf611e 100644 --- a/polkadot/runtime/rococo/src/xcm_config.rs +++ b/polkadot/runtime/rococo/src/xcm_config.rs @@ -41,10 +41,10 @@ use xcm_builder::{ AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, ChildParachainAsNative, ChildParachainConvertsVia, DescribeAllTerminal, DescribeFamily, FixedWeightBounds, FrameTransactionalProcessor, FungibleAdapter, HashedDescription, IsChildSystemParachain, - IsConcrete, MintLocation, OriginToPluralityVoice, SignedAccountId32AsNative, - SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, - UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, - XcmFeeManagerFromComponents, XcmFeeToAccount, + IsConcrete, MintLocation, OriginToPluralityVoice, SendXcmFeeToAccount, + SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, + TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, + XcmFeeManagerFromComponents, }; use xcm_executor::XcmExecutor; @@ -213,7 +213,7 @@ impl xcm_executor::Config for XcmConfig { type MaxAssetsIntoHolding = MaxAssetsIntoHolding; type FeeManager = XcmFeeManagerFromComponents< WaivedLocations, - XcmFeeToAccount, + SendXcmFeeToAccount, >; type MessageExporter = (); type UniversalAliases = Nothing; diff --git a/polkadot/runtime/test-runtime/Cargo.toml b/polkadot/runtime/test-runtime/Cargo.toml index a66fceedae34158e70be869c1b4262fcde3d7a43..ac379b69e3f2ca99f22a7ed336b09b6193342fec 100644 --- a/polkadot/runtime/test-runtime/Cargo.toml +++ b/polkadot/runtime/test-runtime/Cargo.toml @@ -22,7 +22,6 @@ sp-consensus-beefy = { workspace = true } sp-api = { workspace = true } sp-inherents = { workspace = true } sp-offchain = { workspace = true } -sp-std = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } sp-staking = { workspace = true } @@ -125,7 +124,6 @@ std = [ "sp-runtime/std", "sp-session/std", "sp-staking/std", - "sp-std/std", "sp-transaction-pool/std", "sp-version/std", "test-runtime-constants/std", diff --git a/polkadot/runtime/test-runtime/src/lib.rs b/polkadot/runtime/test-runtime/src/lib.rs index 96392c026d5c9059ad55ff4a739f50c021eacbd7..a8a369a68e6691e88f05987986d27229843aef9d 100644 --- a/polkadot/runtime/test-runtime/src/lib.rs +++ b/polkadot/runtime/test-runtime/src/lib.rs @@ -20,12 +20,15 @@ // `construct_runtime!` does a lot of recursion and requires us to increase the limit to 256. #![recursion_limit = "256"] -use codec::Encode; -use pallet_transaction_payment::FungibleAdapter; -use sp_std::{ +extern crate alloc; + +use alloc::{ collections::{btree_map::BTreeMap, vec_deque::VecDeque}, - prelude::*, + vec, + vec::Vec, }; +use codec::Encode; +use pallet_transaction_payment::FungibleAdapter; use polkadot_runtime_parachains::{ assigner_parachains as parachains_assigner_parachains, @@ -793,7 +796,7 @@ sp_api::impl_runtime_apis! { Runtime::metadata_at_version(version) } - fn metadata_versions() -> sp_std::vec::Vec { + fn metadata_versions() -> Vec { Runtime::metadata_versions() } } diff --git a/polkadot/runtime/test-runtime/src/xcm_config.rs b/polkadot/runtime/test-runtime/src/xcm_config.rs index b1d86ff9a85e9fc6a9a5f361b933d78898715d49..b424b9a3ee55b4f3504cf3a72849cd5ad5dd09e4 100644 --- a/polkadot/runtime/test-runtime/src/xcm_config.rs +++ b/polkadot/runtime/test-runtime/src/xcm_config.rs @@ -54,7 +54,7 @@ pub type LocalOriginToLocation = ( /// This implementation ensures that messages with non-reanchored assets return higher /// prices than messages with reanchored assets. /// Useful for `deposit_reserve_asset_works_for_any_xcm_sender` integration test. -pub struct TestDeliveryPrice(sp_std::marker::PhantomData<(A, F)>); +pub struct TestDeliveryPrice(core::marker::PhantomData<(A, F)>); impl, F: FeeTracker> PriceForMessageDelivery for TestDeliveryPrice { type Id = F::Id; diff --git a/polkadot/runtime/westend/Cargo.toml b/polkadot/runtime/westend/Cargo.toml index 5a7805c05161be49ae94986b60101594422d4d89..d2bafb33d2cb429fc5661d8a2d6576c2102ba325 100644 --- a/polkadot/runtime/westend/Cargo.toml +++ b/polkadot/runtime/westend/Cargo.toml @@ -28,7 +28,6 @@ sp-offchain = { workspace = true } sp-api = { workspace = true } sp-application-crypto = { workspace = true } sp-arithmetic = { workspace = true } -sp-std = { workspace = true } sp-genesis-builder = { workspace = true } sp-io = { workspace = true } sp-mmr-primitives = { workspace = true } @@ -220,7 +219,6 @@ std = [ "sp-runtime/std", "sp-session/std", "sp-staking/std", - "sp-std/std", "sp-storage/std", "sp-tracing/std", "sp-transaction-pool/std", @@ -242,6 +240,7 @@ runtime-benchmarks = [ "pallet-babe/runtime-benchmarks", "pallet-bags-list/runtime-benchmarks", "pallet-balances/runtime-benchmarks", + "pallet-beefy-mmr/runtime-benchmarks", "pallet-collective/runtime-benchmarks", "pallet-conviction-voting/runtime-benchmarks", "pallet-delegated-staking/runtime-benchmarks", @@ -348,7 +347,10 @@ metadata-hash = ["substrate-wasm-builder/metadata-hash"] # Set timing constants (e.g. session period) to faster versions to speed up testing. fast-runtime = [] -runtime-metrics = ["polkadot-runtime-parachains/runtime-metrics", "sp-io/with-tracing"] +runtime-metrics = [ + "polkadot-runtime-parachains/runtime-metrics", + "sp-io/with-tracing", +] # A feature that should be enabled when the runtime should be built for on-chain # deployment. This will disable stuff that shouldn't be part of the on-chain wasm diff --git a/polkadot/runtime/westend/src/impls.rs b/polkadot/runtime/westend/src/impls.rs index d7ca677a7620e26aeb2f00e35ec23e67057c8293..11665953bd8e17b2f0368602b176a19046d44be9 100644 --- a/polkadot/runtime/westend/src/impls.rs +++ b/polkadot/runtime/westend/src/impls.rs @@ -15,12 +15,13 @@ // along with Polkadot. If not, see . use crate::xcm_config; +use alloc::{boxed::Box, vec}; use codec::{Decode, Encode}; +use core::marker::PhantomData; use frame_support::pallet_prelude::DispatchResult; use frame_system::RawOrigin; use polkadot_primitives::Balance; use polkadot_runtime_common::identity_migrator::{OnReapIdentity, WeightInfo}; -use sp_std::{marker::PhantomData, prelude::*}; use westend_runtime_constants::currency::*; use xcm::{latest::prelude::*, VersionedLocation, VersionedXcm}; use xcm_executor::traits::TransactAsset; diff --git a/polkadot/runtime/westend/src/lib.rs b/polkadot/runtime/westend/src/lib.rs index 0d7a8a6a4ac222e77886e5f7a939d23ca307a234..acd6f96878c9e5f812a0a6bf441b2b88859245e9 100644 --- a/polkadot/runtime/westend/src/lib.rs +++ b/polkadot/runtime/westend/src/lib.rs @@ -20,6 +20,13 @@ // `#[frame_support::runtime]!` does a lot of recursion and requires us to increase the limit. #![recursion_limit = "512"] +extern crate alloc; + +use alloc::{ + collections::{btree_map::BTreeMap, vec_deque::VecDeque}, + vec, + vec::Vec, +}; use codec::{Decode, Encode, MaxEncodedLen}; use frame_election_provider_support::{bounds::ElectionBoundsBuilder, onchain, SequentialPhragmen}; use frame_support::{ @@ -95,10 +102,6 @@ use sp_runtime::{ ApplyExtrinsicResult, FixedU128, KeyTypeId, Perbill, Percent, Permill, }; use sp_staking::SessionIndex; -use sp_std::{ - collections::{btree_map::BTreeMap, vec_deque::VecDeque}, - prelude::*, -}; #[cfg(any(feature = "std", test))] use sp_version::NativeVersion; use sp_version::RuntimeVersion; @@ -339,9 +342,11 @@ impl pallet_mmr::Config for Runtime { const INDEXING_PREFIX: &'static [u8] = mmr::INDEXING_PREFIX; type Hashing = Keccak256; type OnNewRoot = pallet_beefy_mmr::DepositBeefyDigest; - type WeightInfo = (); type LeafData = pallet_beefy_mmr::Pallet; type BlockHashProvider = pallet_mmr::DefaultBlockHashProvider; + type WeightInfo = weights::pallet_mmr::WeightInfo; + #[cfg(feature = "runtime-benchmarks")] + type BenchmarkHelper = parachains_paras::benchmarking::mmr_setup::MmrSetup; } /// MMR helper types. @@ -363,13 +368,8 @@ parameter_types! { pub struct ParaHeadsRootProvider; impl BeefyDataProvider for ParaHeadsRootProvider { fn extra_data() -> H256 { - let mut para_heads: Vec<(u32, Vec)> = parachains_paras::Parachains::::get() - .into_iter() - .filter_map(|id| { - parachains_paras::Heads::::get(&id).map(|head| (id.into(), head.0)) - }) - .collect(); - para_heads.sort_by_key(|k| k.0); + let para_heads: Vec<(u32, Vec)> = + parachains_paras::Pallet::::sorted_para_heads(); binary_merkle_tree::merkle_root::( para_heads.into_iter().map(|pair| pair.encode()), ) @@ -1752,6 +1752,7 @@ mod benches { [pallet_identity, Identity] [pallet_indices, Indices] [pallet_message_queue, MessageQueue] + [pallet_mmr, Mmr] [pallet_multisig, Multisig] [pallet_nomination_pools, NominationPoolsBench::] [pallet_offences, OffencesBench::] @@ -1802,7 +1803,7 @@ sp_api::impl_runtime_apis! { Runtime::metadata_at_version(version) } - fn metadata_versions() -> sp_std::vec::Vec { + fn metadata_versions() -> alloc::vec::Vec { Runtime::metadata_versions() } } @@ -2420,6 +2421,8 @@ sp_api::impl_runtime_apis! { use xcm_config::{AssetHub, TokenLocation}; + use alloc::boxed::Box; + parameter_types! { pub ExistentialDepositAsset: Option = Some(( TokenLocation::get(), diff --git a/polkadot/runtime/westend/src/weights/mod.rs b/polkadot/runtime/westend/src/weights/mod.rs index f6a9008d71876726dda2ad240ecdb4588a1f82a3..c3ed2b5a75ec59f0c2e4d0b4156899bb9599c65e 100644 --- a/polkadot/runtime/westend/src/weights/mod.rs +++ b/polkadot/runtime/westend/src/weights/mod.rs @@ -26,6 +26,7 @@ pub mod pallet_fast_unstake; pub mod pallet_identity; pub mod pallet_indices; pub mod pallet_message_queue; +pub mod pallet_mmr; pub mod pallet_multisig; pub mod pallet_nomination_pools; pub mod pallet_preimage; diff --git a/polkadot/runtime/westend/src/weights/pallet_mmr.rs b/polkadot/runtime/westend/src/weights/pallet_mmr.rs new file mode 100644 index 0000000000000000000000000000000000000000..1a410e7fc46ea4aa3944765ef662f4419c4cd16a --- /dev/null +++ b/polkadot/runtime/westend/src/weights/pallet_mmr.rs @@ -0,0 +1,76 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Polkadot is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. + +// Polkadot is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +// You should have received a copy of the GNU General Public License +// along with Polkadot. If not, see . + +//! Autogenerated weights for `pallet_mmr` +//! +//! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 +//! DATE: 2024-07-17, STEPS: `5`, REPEAT: `1`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! WORST CASE MAP SIZE: `1000000` +//! HOSTNAME: `am1max.local`, CPU: `` +//! WASM-EXECUTION: `Compiled`, CHAIN: `Some("westend-dev")`, DB CACHE: 1024 + +// Executed Command: +// target/testnet/polkadot +// benchmark +// pallet +// --steps=5 +// --repeat=1 +// --extrinsic=* +// --wasm-execution=compiled +// --heap-pages=4096 +// --pallet=pallet_mmr +// --chain=westend-dev +// --header=./polkadot/file_header.txt +// --output=./polkadot/runtime/westend/src/weights/ + +#![cfg_attr(rustfmt, rustfmt_skip)] +#![allow(unused_parens)] +#![allow(unused_imports)] +#![allow(missing_docs)] + +use frame_support::{traits::Get, weights::Weight}; +use core::marker::PhantomData; + +/// Weight functions for `pallet_mmr`. +pub struct WeightInfo(PhantomData); +impl pallet_mmr::WeightInfo for WeightInfo { + /// Storage: `Mmr::NumberOfLeaves` (r:1 w:1) + /// Proof: `Mmr::NumberOfLeaves` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `MaxEncodedLen`) + /// Storage: `System::ParentHash` (r:1 w:0) + /// Proof: `System::ParentHash` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) + /// Storage: `Paras::Heads` (r:1025 w:0) + /// Proof: `Paras::Heads` (`max_values`: None, `max_size`: None, mode: `Measured`) + /// Storage: `BeefyMmrLeaf::BeefyNextAuthorities` (r:1 w:0) + /// Proof: `BeefyMmrLeaf::BeefyNextAuthorities` (`max_values`: Some(1), `max_size`: Some(44), added: 539, mode: `MaxEncodedLen`) + /// Storage: `Mmr::Nodes` (r:8 w:4) + /// Proof: `Mmr::Nodes` (`max_values`: None, `max_size`: Some(40), added: 2515, mode: `MaxEncodedLen`) + /// Storage: `System::Digest` (r:1 w:1) + /// Proof: `System::Digest` (`max_values`: Some(1), `max_size`: None, mode: `Measured`) + /// Storage: `Mmr::RootHash` (r:0 w:1) + /// Proof: `Mmr::RootHash` (`max_values`: Some(1), `max_size`: Some(32), added: 527, mode: `MaxEncodedLen`) + /// The range of component `x` is `[1, 1000]`. + fn on_initialize(x: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `1071043 + x * (39 ±0)` + // Estimated: `3608787 + x * (39 ±6)` + // Minimum execution time: 11_102_000_000 picoseconds. + Weight::from_parts(21_772_042_215, 0) + .saturating_add(Weight::from_parts(0, 3608787)) + .saturating_add(T::DbWeight::get().reads(1031)) + .saturating_add(T::DbWeight::get().writes(4)) + .saturating_add(Weight::from_parts(0, 39).saturating_mul(x.into())) + } +} diff --git a/polkadot/runtime/westend/src/weights/xcm/mod.rs b/polkadot/runtime/westend/src/weights/xcm/mod.rs index 09e883a9f7af5820832e7db52a8eeba5148d3a48..cb5894ea51e3c5106e75e86bc35249f24e8a03b4 100644 --- a/polkadot/runtime/westend/src/weights/xcm/mod.rs +++ b/polkadot/runtime/westend/src/weights/xcm/mod.rs @@ -18,8 +18,8 @@ mod pallet_xcm_benchmarks_fungible; mod pallet_xcm_benchmarks_generic; use crate::Runtime; +use alloc::vec::Vec; use frame_support::weights::Weight; -use sp_std::prelude::*; use xcm::{ latest::{prelude::*, QueryResponseInfo}, DoubleEncoded, diff --git a/polkadot/runtime/westend/src/xcm_config.rs b/polkadot/runtime/westend/src/xcm_config.rs index 9d7143c96bb5eecda25309634d395ba24b6a8b11..d75083929a04511e104d8c36d7628fa5e329ec84 100644 --- a/polkadot/runtime/westend/src/xcm_config.rs +++ b/polkadot/runtime/westend/src/xcm_config.rs @@ -42,10 +42,9 @@ use xcm_builder::{ AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, ChildParachainAsNative, ChildParachainConvertsVia, DescribeAllTerminal, DescribeFamily, FrameTransactionalProcessor, FungibleAdapter, HashedDescription, IsChildSystemParachain, IsConcrete, MintLocation, - OriginToPluralityVoice, SignedAccountId32AsNative, SignedToAccountId32, + OriginToPluralityVoice, SendXcmFeeToAccount, SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic, XcmFeeManagerFromComponents, - XcmFeeToAccount, }; use xcm_executor::XcmExecutor; @@ -211,7 +210,7 @@ impl xcm_executor::Config for XcmConfig { type MaxAssetsIntoHolding = MaxAssetsIntoHolding; type FeeManager = XcmFeeManagerFromComponents< WaivedLocations, - XcmFeeToAccount, + SendXcmFeeToAccount, >; type MessageExporter = (); type UniversalAliases = Nothing; diff --git a/polkadot/xcm/Cargo.toml b/polkadot/xcm/Cargo.toml index 72174bda2340c46c7769c320c646c11556daf74c..862f5557a012a9bd1953607e774b36009c87d9e5 100644 --- a/polkadot/xcm/Cargo.toml +++ b/polkadot/xcm/Cargo.toml @@ -17,6 +17,7 @@ impl-trait-for-tuples = { workspace = true } log = { workspace = true } codec = { features = ["derive", "max-encoded-len"], workspace = true } scale-info = { features = ["derive", "serde"], workspace = true } +sp-runtime = { workspace = true } sp-weights = { features = ["serde"], workspace = true } serde = { features = ["alloc", "derive", "rc"], workspace = true } schemars = { default-features = true, optional = true, workspace = true } @@ -38,6 +39,11 @@ std = [ "log/std", "scale-info/std", "serde/std", + "sp-runtime/std", "sp-weights/std", ] -json-schema = ["bounded-collections/json-schema", "dep:schemars", "sp-weights/json-schema"] +json-schema = [ + "bounded-collections/json-schema", + "dep:schemars", + "sp-weights/json-schema", +] diff --git a/polkadot/xcm/docs/src/cookbook/relay_token_transactor/parachain/mod.rs b/polkadot/xcm/docs/src/cookbook/relay_token_transactor/parachain/mod.rs index e7d00ac71038b4f02d5172584a398f185864f46c..23d6664bdafcbc147f63c3a99ce2d788277679b5 100644 --- a/polkadot/xcm/docs/src/cookbook/relay_token_transactor/parachain/mod.rs +++ b/polkadot/xcm/docs/src/cookbook/relay_token_transactor/parachain/mod.rs @@ -16,7 +16,7 @@ //! # Runtime -use frame::{deps::frame_system, prelude::*, runtime::prelude::*, traits::IdentityLookup}; +use frame::{deps::frame_system, runtime::prelude::*, traits::IdentityLookup}; use xcm_executor::XcmExecutor; use xcm_simulator::mock_message_queue; diff --git a/polkadot/xcm/pallet-xcm-benchmarks/Cargo.toml b/polkadot/xcm/pallet-xcm-benchmarks/Cargo.toml index 1177d094c6c38a1a3efe4f7bd76bde715d1a2ffd..b07bdfdca3d196095a45370a9b2d622dd2a1636a 100644 --- a/polkadot/xcm/pallet-xcm-benchmarks/Cargo.toml +++ b/polkadot/xcm/pallet-xcm-benchmarks/Cargo.toml @@ -18,7 +18,6 @@ scale-info = { features = ["derive"], workspace = true } frame-support = { workspace = true } frame-system = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } sp-io = { workspace = true } xcm-executor = { workspace = true } frame-benchmarking = { workspace = true } @@ -48,7 +47,6 @@ std = [ "scale-info/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", "xcm-builder/std", "xcm-executor/std", ] diff --git a/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/benchmarking.rs b/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/benchmarking.rs index d99da9184b5d8c7f2680b23140df1083d487b452..6ce49074a6e2b1fa02dd0f1fbe4f90db1058e560 100644 --- a/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/benchmarking.rs +++ b/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/benchmarking.rs @@ -16,6 +16,7 @@ use super::*; use crate::{account_and_location, new_executor, AssetTransactorOf, EnsureDelivery, XcmCallOf}; +use alloc::{vec, vec::Vec}; use frame_benchmarking::{benchmarks_instance_pallet, BenchmarkError, BenchmarkResult}; use frame_support::{ pallet_prelude::Get, @@ -23,7 +24,6 @@ use frame_support::{ weights::Weight, }; use sp_runtime::traits::{Bounded, Zero}; -use sp_std::{prelude::*, vec}; use xcm::latest::{prelude::*, MAX_ITEMS_IN_ASSETS}; use xcm_executor::traits::{ConvertLocation, FeeReason, TransactAsset}; @@ -37,7 +37,7 @@ benchmarks_instance_pallet! { >::Balance as TryInto - >::Error: sp_std::fmt::Debug, + >::Error: core::fmt::Debug, } withdraw_asset { diff --git a/polkadot/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs b/polkadot/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs index 760b21f93566e12b77a00f2c7b9b744f6db91d68..40a7da58a687c186664404e0a00734b457b60e51 100644 --- a/polkadot/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs +++ b/polkadot/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs @@ -16,10 +16,10 @@ use super::*; use crate::{account_and_location, new_executor, EnsureDelivery, XcmCallOf}; +use alloc::{vec, vec::Vec}; use codec::Encode; use frame_benchmarking::{benchmarks, BenchmarkError}; use frame_support::{dispatch::GetDispatchInfo, traits::fungible::Inspect}; -use sp_std::{prelude::*, vec}; use xcm::{ latest::{prelude::*, MaxDispatchErrorLen, MaybeErrorCode, Weight, MAX_ITEMS_IN_ASSETS}, DoubleEncoded, diff --git a/polkadot/xcm/pallet-xcm-benchmarks/src/lib.rs b/polkadot/xcm/pallet-xcm-benchmarks/src/lib.rs index a43f27bf47e7242308adc1b53d146508f14e36b2..4a12bb7f47c665ed6f302d5e665cf9c2b0e911a2 100644 --- a/polkadot/xcm/pallet-xcm-benchmarks/src/lib.rs +++ b/polkadot/xcm/pallet-xcm-benchmarks/src/lib.rs @@ -18,9 +18,11 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + +use alloc::vec::Vec; use codec::Encode; use frame_benchmarking::{account, BenchmarkError}; -use sp_std::prelude::*; use xcm::latest::prelude::*; use xcm_builder::EnsureDelivery; use xcm_executor::{traits::ConvertLocation, Config as XcmConfig}; diff --git a/polkadot/xcm/pallet-xcm/Cargo.toml b/polkadot/xcm/pallet-xcm/Cargo.toml index 0cce7a3449389875a7658f20e4012640e13cd394..ed4b441d7c33c347cccda054b8bc7019b3d11388 100644 --- a/polkadot/xcm/pallet-xcm/Cargo.toml +++ b/polkadot/xcm/pallet-xcm/Cargo.toml @@ -21,7 +21,6 @@ frame-system = { workspace = true } sp-core = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } xcm = { workspace = true } xcm-executor = { workspace = true } @@ -52,7 +51,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", "xcm-builder/std", "xcm-executor/std", "xcm-runtime-apis/std", diff --git a/polkadot/xcm/pallet-xcm/src/benchmarking.rs b/polkadot/xcm/pallet-xcm/src/benchmarking.rs index da46a6a37c0654f6ef34daf7bbd37cd5b655ac45..d09c81bf434e2ce843b55fc5b05baee121e562c8 100644 --- a/polkadot/xcm/pallet-xcm/src/benchmarking.rs +++ b/polkadot/xcm/pallet-xcm/src/benchmarking.rs @@ -18,7 +18,6 @@ use super::*; use frame_benchmarking::{benchmarks, whitelisted_caller, BenchmarkError, BenchmarkResult}; use frame_support::{assert_ok, weights::Weight}; use frame_system::RawOrigin; -use sp_std::prelude::*; use xcm::latest::prelude::*; use xcm_builder::EnsureDelivery; use xcm_executor::traits::FeeReason; diff --git a/polkadot/xcm/pallet-xcm/src/lib.rs b/polkadot/xcm/pallet-xcm/src/lib.rs index 668f07c52ce35e8009d33abc3f1d021e07f85394..6451901279b166e116dd8dcf1d204da74db98d35 100644 --- a/polkadot/xcm/pallet-xcm/src/lib.rs +++ b/polkadot/xcm/pallet-xcm/src/lib.rs @@ -27,7 +27,11 @@ mod tests; pub mod migration; +extern crate alloc; + +use alloc::{boxed::Box, vec, vec::Vec}; use codec::{Decode, Encode, EncodeLike, MaxEncodedLen}; +use core::{marker::PhantomData, result::Result}; use frame_support::{ dispatch::{ DispatchErrorWithPostInfo, GetDispatchInfo, PostDispatchInfo, WithPostDispatchInfo, @@ -49,7 +53,6 @@ use sp_runtime::{ }, Either, RuntimeDebug, }; -use sp_std::{boxed::Box, marker::PhantomData, prelude::*, result::Result, vec}; use xcm::{latest::QueryResponseInfo, prelude::*}; use xcm_builder::{ ExecuteController, ExecuteControllerWeightInfo, InspectMessageQueues, QueryController, @@ -792,7 +795,7 @@ pub mod pallet { #[pallet::genesis_config] pub struct GenesisConfig { #[serde(skip)] - pub _config: sp_std::marker::PhantomData, + pub _config: core::marker::PhantomData, /// The default version to encode outgoing XCM messages with. pub safe_xcm_version: Option, } @@ -1438,8 +1441,8 @@ enum FeesHandling { Separate { local_xcm: Xcm<::RuntimeCall>, remote_xcm: Xcm<()> }, } -impl sp_std::fmt::Debug for FeesHandling { - fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { +impl core::fmt::Debug for FeesHandling { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { Self::Batched { fees } => write!(f, "FeesHandling::Batched({:?})", fees), Self::Separate { local_xcm, remote_xcm } => write!( @@ -1840,8 +1843,8 @@ impl Pallet { FeesHandling::Separate { local_xcm: mut local_fees, remote_xcm: mut remote_fees } => { // fees are handled by separate XCM instructions, prepend fees instructions (for // remote XCM they have to be prepended instead of appended to pass barriers). - sp_std::mem::swap(local, &mut local_fees); - sp_std::mem::swap(remote, &mut remote_fees); + core::mem::swap(local, &mut local_fees); + core::mem::swap(remote, &mut remote_fees); // these are now swapped so fees actually go first local.inner_mut().append(&mut local_fees.into_inner()); remote.inner_mut().append(&mut remote_fees.into_inner()); diff --git a/polkadot/xcm/pallet-xcm/src/migration.rs b/polkadot/xcm/pallet-xcm/src/migration.rs index b157e6b5c3d5f27d206b73a1b040ca5d7944b8f2..0aec97ab410516c35860f397d41ede599768c5c6 100644 --- a/polkadot/xcm/pallet-xcm/src/migration.rs +++ b/polkadot/xcm/pallet-xcm/src/migration.rs @@ -34,7 +34,7 @@ pub mod v1 { /// enacted on-chain. /// /// Use experimental [`MigrateToV1`] instead. - pub struct VersionUncheckedMigrateToV1(sp_std::marker::PhantomData); + pub struct VersionUncheckedMigrateToV1(core::marker::PhantomData); impl UncheckedOnRuntimeUpgrade for VersionUncheckedMigrateToV1 { fn on_runtime_upgrade() -> Weight { let mut weight = T::DbWeight::get().reads(1); @@ -81,7 +81,7 @@ pub mod v1 { /// `XCM_VERSION`. /// /// NOTE: This migration can be permanently added to the runtime migrations. -pub struct MigrateToLatestXcmVersion(sp_std::marker::PhantomData); +pub struct MigrateToLatestXcmVersion(core::marker::PhantomData); impl OnRuntimeUpgrade for MigrateToLatestXcmVersion { fn on_runtime_upgrade() -> Weight { CurrentMigration::::put(VersionMigrationStage::default()); diff --git a/polkadot/xcm/pallet-xcm/src/mock.rs b/polkadot/xcm/pallet-xcm/src/mock.rs index 2be6f301f85621489ab6986aaf300251fd239fbc..8d0476b0e70d77f7cc1d63033392eb274dbb337c 100644 --- a/polkadot/xcm/pallet-xcm/src/mock.rs +++ b/polkadot/xcm/pallet-xcm/src/mock.rs @@ -15,6 +15,7 @@ // along with Polkadot. If not, see . use codec::Encode; +pub use core::cell::RefCell; use frame_support::{ construct_runtime, derive_impl, parameter_types, traits::{ @@ -28,16 +29,15 @@ use polkadot_parachain_primitives::primitives::Id as ParaId; use polkadot_runtime_parachains::origin; use sp_core::H256; use sp_runtime::{traits::IdentityLookup, AccountId32, BuildStorage}; -pub use sp_std::cell::RefCell; use xcm::prelude::*; use xcm_builder::{ AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom, AllowTopLevelPaidExecutionFrom, Case, ChildParachainAsNative, ChildParachainConvertsVia, ChildSystemParachainAsSuperuser, DescribeAllTerminal, EnsureDecodableXcm, FixedRateOfFungible, FixedWeightBounds, FrameTransactionalProcessor, FungibleAdapter, FungiblesAdapter, - HashedDescription, IsConcrete, MatchedConvertedConcreteId, NoChecking, + HashedDescription, IsConcrete, MatchedConvertedConcreteId, NoChecking, SendXcmFeeToAccount, SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit, - XcmFeeManagerFromComponents, XcmFeeToAccount, + XcmFeeManagerFromComponents, }; use xcm_executor::{ traits::{Identity, JustTry}, @@ -504,7 +504,7 @@ impl xcm_executor::Config for XcmConfig { type MaxAssetsIntoHolding = MaxAssetsIntoHolding; type FeeManager = XcmFeeManagerFromComponents< EverythingBut, - XcmFeeToAccount, + SendXcmFeeToAccount, >; type MessageExporter = (); type UniversalAliases = Nothing; diff --git a/polkadot/xcm/src/v4/location.rs b/polkadot/xcm/src/v4/location.rs index 9e94d13626d619b2d4db5593561abacb7bad2e8f..f2c302495c73d2ebb96c53774c6cd98387242504 100644 --- a/polkadot/xcm/src/v4/location.rs +++ b/polkadot/xcm/src/v4/location.rs @@ -534,6 +534,12 @@ impl From<[u8; 32]> for Location { } } +impl From for Location { + fn from(id: sp_runtime::AccountId32) -> Self { + Junction::AccountId32 { network: None, id: id.into() }.into() + } +} + xcm_procedural::impl_conversion_functions_for_location_v4!(); #[cfg(test)] diff --git a/polkadot/xcm/src/v4/mod.rs b/polkadot/xcm/src/v4/mod.rs index 57840562ba3e4754efea5eb6185f86691bd3c326..2a279f989e9b23084925c1484f7f366c08325080 100644 --- a/polkadot/xcm/src/v4/mod.rs +++ b/polkadot/xcm/src/v4/mod.rs @@ -231,15 +231,15 @@ parameter_types! { #[derive(Clone, Eq, PartialEq, Encode, Decode, Debug, TypeInfo, MaxEncodedLen)] pub struct PalletInfo { #[codec(compact)] - index: u32, - name: BoundedVec, - module_name: BoundedVec, + pub index: u32, + pub name: BoundedVec, + pub module_name: BoundedVec, #[codec(compact)] - major: u32, + pub major: u32, #[codec(compact)] - minor: u32, + pub minor: u32, #[codec(compact)] - patch: u32, + pub patch: u32, } impl TryInto for PalletInfo { diff --git a/polkadot/xcm/xcm-builder/Cargo.toml b/polkadot/xcm/xcm-builder/Cargo.toml index d43506aa651b4d719c42b8633649936036b04741..7702e2f9be07db04aafcd911a7fbb9fb2cdfb957 100644 --- a/polkadot/xcm/xcm-builder/Cargo.toml +++ b/polkadot/xcm/xcm-builder/Cargo.toml @@ -15,7 +15,6 @@ codec = { features = ["derive"], workspace = true } scale-info = { features = ["derive"], workspace = true } xcm = { workspace = true } xcm-executor = { workspace = true } -sp-std = { workspace = true } sp-arithmetic = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } @@ -66,7 +65,6 @@ std = [ "sp-arithmetic/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", "sp-weights/std", "xcm-executor/std", "xcm/std", diff --git a/polkadot/xcm/xcm-builder/src/asset_conversion.rs b/polkadot/xcm/xcm-builder/src/asset_conversion.rs index 520ce87448ea4f868fbb62130a7da45353d220b6..16ae05c20795e27a9aa6b4d2ec78d47b7665bbb2 100644 --- a/polkadot/xcm/xcm-builder/src/asset_conversion.rs +++ b/polkadot/xcm/xcm-builder/src/asset_conversion.rs @@ -16,9 +16,9 @@ //! Adapters to work with [`frame_support::traits::fungibles`] through XCM. +use core::{marker::PhantomData, result}; use frame_support::traits::{Contains, Get}; use sp_runtime::traits::MaybeEquivalence; -use sp_std::{marker::PhantomData, prelude::*, result}; use xcm::latest::prelude::*; use xcm_executor::traits::{Error as MatchError, MatchesFungibles, MatchesNonFungibles}; diff --git a/polkadot/xcm/xcm-builder/src/barriers.rs b/polkadot/xcm/xcm-builder/src/barriers.rs index 11e9122f9a121b1b08db7a5aec2fd423d63c98cf..5d95005eb663097b8130cd01640d6dd29a4f2307 100644 --- a/polkadot/xcm/xcm-builder/src/barriers.rs +++ b/polkadot/xcm/xcm-builder/src/barriers.rs @@ -17,12 +17,12 @@ //! Various implementations for `ShouldExecute`. use crate::{CreateMatcher, MatchXcm}; +use core::{cell::Cell, marker::PhantomData, ops::ControlFlow, result::Result}; use frame_support::{ ensure, traits::{Contains, Get, ProcessMessageError}, }; use polkadot_parachain_primitives::primitives::IsSystem; -use sp_std::{cell::Cell, marker::PhantomData, ops::ControlFlow, result::Result}; use xcm::prelude::*; use xcm_executor::traits::{CheckSuspension, OnResponse, Properties, ShouldExecute}; diff --git a/polkadot/xcm/xcm-builder/src/controller.rs b/polkadot/xcm/xcm-builder/src/controller.rs index 04b19eaa587009aa118e7c7d51ce69b159e4d948..d4ce2ca5b353c94b8d4e512236008eae9a6dd28e 100644 --- a/polkadot/xcm/xcm-builder/src/controller.rs +++ b/polkadot/xcm/xcm-builder/src/controller.rs @@ -18,11 +18,11 @@ //! Controller traits defined in this module are high-level traits that will rely on other traits //! from `xcm-executor` to perform their tasks. +use alloc::boxed::Box; use frame_support::{ dispatch::{DispatchErrorWithPostInfo, WithPostDispatchInfo}, pallet_prelude::DispatchError, }; -use sp_std::boxed::Box; use xcm::prelude::*; pub use xcm_executor::traits::QueryHandler; diff --git a/polkadot/xcm/xcm-builder/src/currency_adapter.rs b/polkadot/xcm/xcm-builder/src/currency_adapter.rs index 99a736d6ac1f9dd197a6813cf377f35991638e9a..355d6ad85388cb1709139112384890354eb8da7a 100644 --- a/polkadot/xcm/xcm-builder/src/currency_adapter.rs +++ b/polkadot/xcm/xcm-builder/src/currency_adapter.rs @@ -19,9 +19,9 @@ #![allow(deprecated)] use super::MintLocation; +use core::{marker::PhantomData, result}; use frame_support::traits::{ExistenceRequirement::AllowDeath, Get, WithdrawReasons}; use sp_runtime::traits::CheckedSub; -use sp_std::{marker::PhantomData, result}; use xcm::latest::{Asset, Error as XcmError, Location, Result, XcmContext}; use xcm_executor::{ traits::{ConvertLocation, MatchesFungible, TransactAsset}, diff --git a/polkadot/xcm/xcm-builder/src/fee_handling.rs b/polkadot/xcm/xcm-builder/src/fee_handling.rs index e114b3601c84a45cc0400114b7aaff2bfdae4bb8..17e9e64e00c9d2aa2cecb73c7355416b2d6ce6ac 100644 --- a/polkadot/xcm/xcm-builder/src/fee_handling.rs +++ b/polkadot/xcm/xcm-builder/src/fee_handling.rs @@ -68,36 +68,20 @@ impl, FeeHandler: HandleFee> FeeManager } } -/// Try to deposit the given fee in the specified account. -/// Burns the fee in case of a failure. -pub fn deposit_or_burn_fee>( - fee: Assets, - context: Option<&XcmContext>, - receiver: AccountId, -) { - let dest = AccountId32 { network: None, id: receiver.into() }.into(); - for asset in fee.into_inner() { - if let Err(e) = AssetTransactor::deposit_asset(&asset, &dest, context) { - log::trace!( - target: "xcm::fees", - "`AssetTransactor::deposit_asset` returned error: {:?}. Burning fee: {:?}. \ - They might be burned.", - e, asset, - ); - } - } -} - /// A `HandleFee` implementation that simply deposits the fees into a specific on-chain /// `ReceiverAccount`. /// /// It reuses the `AssetTransactor` configured on the XCM executor to deposit fee assets. If /// the `AssetTransactor` returns an error while calling `deposit_asset`, then a warning will be /// logged and the fee burned. +#[deprecated( + note = "`XcmFeeToAccount` will be removed in January 2025. Use `SendXcmFeeToAccount` instead." +)] pub struct XcmFeeToAccount( PhantomData<(AssetTransactor, AccountId, ReceiverAccount)>, ); +#[allow(deprecated)] impl< AssetTransactor: TransactAsset, AccountId: Clone + Into<[u8; 32]>, @@ -105,8 +89,49 @@ impl< > HandleFee for XcmFeeToAccount { fn handle_fee(fee: Assets, context: Option<&XcmContext>, _reason: FeeReason) -> Assets { - deposit_or_burn_fee::(fee, context, ReceiverAccount::get()); + let dest = AccountId32 { network: None, id: ReceiverAccount::get().into() }.into(); + deposit_or_burn_fee::(fee, context, dest); + + Assets::new() + } +} + +/// A `HandleFee` implementation that simply deposits the fees into a specific on-chain +/// `ReceiverAccount`. +/// +/// It reuses the `AssetTransactor` configured on the XCM executor to deposit fee assets. If +/// the `AssetTransactor` returns an error while calling `deposit_asset`, then a warning will be +/// logged and the fee burned. +/// +/// `ReceiverAccount` should implement `Get`. +pub struct SendXcmFeeToAccount( + PhantomData<(AssetTransactor, ReceiverAccount)>, +); + +impl> HandleFee + for SendXcmFeeToAccount +{ + fn handle_fee(fee: Assets, context: Option<&XcmContext>, _reason: FeeReason) -> Assets { + deposit_or_burn_fee::(fee, context, ReceiverAccount::get()); Assets::new() } } + +/// Try to deposit the given fee in the specified account. +/// Burns the fee in case of a failure. +pub fn deposit_or_burn_fee( + fee: Assets, + context: Option<&XcmContext>, + dest: Location, +) { + for asset in fee.into_inner() { + if let Err(e) = AssetTransactor::deposit_asset(&asset, &dest, context) { + log::trace!( + target: "xcm::fees", + "`AssetTransactor::deposit_asset` returned error: {e:?}. Burning fee: {asset:?}. \ + They might be burned.", + ); + } + } +} diff --git a/polkadot/xcm/xcm-builder/src/filter_asset_location.rs b/polkadot/xcm/xcm-builder/src/filter_asset_location.rs index d80c5d70deea8c00fbe32af758e8986cc8c6fa7a..16b7be7f3ba98432b75035e99dbc674dc9a26201 100644 --- a/polkadot/xcm/xcm-builder/src/filter_asset_location.rs +++ b/polkadot/xcm/xcm-builder/src/filter_asset_location.rs @@ -17,8 +17,9 @@ //! Various implementations of `ContainsPair` or //! `Contains<(Location, Vec)>`. +use alloc::vec::Vec; +use core::marker::PhantomData; use frame_support::traits::{Contains, ContainsPair, Get}; -use sp_std::{marker::PhantomData, vec::Vec}; use xcm::latest::{Asset, AssetFilter, AssetId, Location, WildAsset}; /// Accepts an asset iff it is a native asset. @@ -44,7 +45,7 @@ impl> ContainsPair for Case /// implementation of the given `Location` and if every asset from `assets` matches at least one of /// the `AssetFilter` instances provided by the `Get` implementation of `AssetFilters`. pub struct LocationWithAssetFilters( - sp_std::marker::PhantomData<(LocationFilter, AssetFilters)>, + core::marker::PhantomData<(LocationFilter, AssetFilters)>, ); impl, AssetFilters: Get>> Contains<(Location, Vec)> for LocationWithAssetFilters @@ -75,7 +76,7 @@ impl, AssetFilters: Get>> pub struct AllAssets; impl Get> for AllAssets { fn get() -> Vec { - sp_std::vec![AssetFilter::Wild(WildAsset::All)] + alloc::vec![AssetFilter::Wild(WildAsset::All)] } } @@ -96,11 +97,11 @@ mod tests { pub AssetYLocation: Location = Location::new(1, [GeneralIndex(2222)]); pub AssetZLocation: Location = Location::new(1, [GeneralIndex(3333)]); - pub OnlyAssetXOrAssetY: sp_std::vec::Vec = sp_std::vec![ + pub OnlyAssetXOrAssetY: alloc::vec::Vec = alloc::vec![ Wild(AllOf { fun: WildFungible, id: AssetId(AssetXLocation::get()) }), Wild(AllOf { fun: WildFungible, id: AssetId(AssetYLocation::get()) }), ]; - pub OnlyAssetZ: sp_std::vec::Vec = sp_std::vec![ + pub OnlyAssetZ: alloc::vec::Vec = alloc::vec![ Wild(AllOf { fun: WildFungible, id: AssetId(AssetZLocation::get()) }) ]; } diff --git a/polkadot/xcm/xcm-builder/src/fungible_adapter.rs b/polkadot/xcm/xcm-builder/src/fungible_adapter.rs index 45a0e2bdca2862c2142f3ecae17ae19ac6ec1839..25a705a39eb73906ca4c7ececfe4526e7450d712 100644 --- a/polkadot/xcm/xcm-builder/src/fungible_adapter.rs +++ b/polkadot/xcm/xcm-builder/src/fungible_adapter.rs @@ -17,6 +17,7 @@ //! Adapters to work with [`frame_support::traits::fungible`] through XCM. use super::MintLocation; +use core::{marker::PhantomData, result}; use frame_support::traits::{ tokens::{ fungible, @@ -27,7 +28,6 @@ use frame_support::traits::{ }, Get, }; -use sp_std::{marker::PhantomData, prelude::*, result}; use xcm::latest::prelude::*; use xcm_executor::{ traits::{ConvertLocation, Error as MatchError, MatchesFungible, TransactAsset}, diff --git a/polkadot/xcm/xcm-builder/src/fungibles_adapter.rs b/polkadot/xcm/xcm-builder/src/fungibles_adapter.rs index 88bbf01d9e1f8c35d2b884be6a0c5a43f24c1073..a259afc6e682565718b86210a746e39928b140ab 100644 --- a/polkadot/xcm/xcm-builder/src/fungibles_adapter.rs +++ b/polkadot/xcm/xcm-builder/src/fungibles_adapter.rs @@ -16,6 +16,7 @@ //! Adapters to work with [`frame_support::traits::fungibles`] through XCM. +use core::{marker::PhantomData, result}; use frame_support::traits::{ tokens::{ fungibles, @@ -26,7 +27,6 @@ use frame_support::traits::{ }, Contains, Get, }; -use sp_std::{marker::PhantomData, prelude::*, result}; use xcm::latest::prelude::*; use xcm_executor::traits::{ConvertLocation, Error as MatchError, MatchesFungibles, TransactAsset}; @@ -101,7 +101,7 @@ impl AssetChecking for NoChecking { /// Implementation of `AssetChecking` which subjects a given set of assets `T` to having their /// teleportations recorded with a `MintLocation::Local`. -pub struct LocalMint(sp_std::marker::PhantomData); +pub struct LocalMint(core::marker::PhantomData); impl> AssetChecking for LocalMint { fn asset_checking(asset: &AssetId) -> Option { match T::contains(asset) { @@ -113,7 +113,7 @@ impl> AssetChecking for LocalMint { /// Implementation of `AssetChecking` which subjects a given set of assets `T` to having their /// teleportations recorded with a `MintLocation::NonLocal`. -pub struct NonLocalMint(sp_std::marker::PhantomData); +pub struct NonLocalMint(core::marker::PhantomData); impl> AssetChecking for NonLocalMint { fn asset_checking(asset: &AssetId) -> Option { match T::contains(asset) { @@ -126,7 +126,7 @@ impl> AssetChecking for NonLocalMint { /// Implementation of `AssetChecking` which subjects a given set of assets `L` to having their /// teleportations recorded with a `MintLocation::Local` and a second set of assets `R` to having /// their teleportations recorded with a `MintLocation::NonLocal`. -pub struct DualMint(sp_std::marker::PhantomData<(L, R)>); +pub struct DualMint(core::marker::PhantomData<(L, R)>); impl, R: Contains> AssetChecking for DualMint { diff --git a/polkadot/xcm/xcm-builder/src/lib.rs b/polkadot/xcm/xcm-builder/src/lib.rs index cc06c298a418d56f6a70d58b5f24bf8ccb14db5d..4cf83c9fc4517e5e76b751c5a6639a8950508734 100644 --- a/polkadot/xcm/xcm-builder/src/lib.rs +++ b/polkadot/xcm/xcm-builder/src/lib.rs @@ -20,6 +20,8 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + #[cfg(test)] mod tests; @@ -54,7 +56,7 @@ pub use currency_adapter::CurrencyAdapter; mod fee_handling; pub use fee_handling::{ - deposit_or_burn_fee, HandleFee, XcmFeeManagerFromComponents, XcmFeeToAccount, + deposit_or_burn_fee, HandleFee, SendXcmFeeToAccount, XcmFeeManagerFromComponents, }; mod filter_asset_location; diff --git a/polkadot/xcm/xcm-builder/src/location_conversion.rs b/polkadot/xcm/xcm-builder/src/location_conversion.rs index f95258492381b387fd71c7186b74b0f09a0aea66..1d840e9c0dde45cd2bb47024b713656b91051392 100644 --- a/polkadot/xcm/xcm-builder/src/location_conversion.rs +++ b/polkadot/xcm/xcm-builder/src/location_conversion.rs @@ -15,11 +15,12 @@ // along with Polkadot. If not, see . use crate::universal_exports::ensure_is_remote; +use alloc::vec::Vec; use codec::{Compact, Decode, Encode}; +use core::marker::PhantomData; use frame_support::traits::Get; use sp_io::hashing::blake2_256; use sp_runtime::traits::{AccountIdConversion, TrailingZeroInput, TryConvert}; -use sp_std::{marker::PhantomData, prelude::*}; use xcm::latest::prelude::*; use xcm_executor::traits::ConvertLocation; @@ -460,7 +461,9 @@ impl #[cfg(test)] mod tests { use super::*; + use alloc::vec; use polkadot_primitives::AccountId; + pub type ForeignChainAliasAccount = HashedDescription; diff --git a/polkadot/xcm/xcm-builder/src/matches_location.rs b/polkadot/xcm/xcm-builder/src/matches_location.rs index b6c2807e6b29db302e2d1182729c5acb4426b24b..71c5ec1efd6f95cc177e931cd7e774d291f71fc2 100644 --- a/polkadot/xcm/xcm-builder/src/matches_location.rs +++ b/polkadot/xcm/xcm-builder/src/matches_location.rs @@ -17,14 +17,14 @@ //! Various implementations and utilities for matching and filtering `Location` and //! `InteriorLocation` types. +use core::marker::PhantomData; use frame_support::traits::{Contains, Get}; use sp_runtime::traits::MaybeEquivalence; -use sp_std::marker::PhantomData; use xcm::latest::{InteriorLocation, Location, NetworkId}; /// An implementation of `Contains` that checks for `Location` or /// `InteriorLocation` if starts with the provided type `T`. -pub struct StartsWith(sp_std::marker::PhantomData<(T, L)>); +pub struct StartsWith(core::marker::PhantomData<(T, L)>); impl, L: TryInto + Clone> Contains for StartsWith { fn contains(location: &L) -> bool { let latest_location: Location = @@ -42,7 +42,7 @@ impl> Contains for StartsWith { /// An implementation of `Contains` that checks for `Location` or /// `InteriorLocation` if starts with expected `GlobalConsensus(NetworkId)` provided as type /// `T`. -pub struct StartsWithExplicitGlobalConsensus(sp_std::marker::PhantomData); +pub struct StartsWithExplicitGlobalConsensus(core::marker::PhantomData); impl> Contains for StartsWithExplicitGlobalConsensus { fn contains(location: &Location) -> bool { matches!(location.interior().global_consensus(), Ok(requested_network) if requested_network.eq(&T::get())) diff --git a/polkadot/xcm/xcm-builder/src/matches_token.rs b/polkadot/xcm/xcm-builder/src/matches_token.rs index e49fd18f88d806b09614696040fab29ead657ee2..095c50a5a25b006e44fdf3baf7fa911209b6dd5d 100644 --- a/polkadot/xcm/xcm-builder/src/matches_token.rs +++ b/polkadot/xcm/xcm-builder/src/matches_token.rs @@ -16,8 +16,8 @@ //! Various implementations for the `MatchesFungible` trait. +use core::marker::PhantomData; use frame_support::traits::Get; -use sp_std::marker::PhantomData; use xcm::latest::{ Asset, AssetId, AssetInstance, Fungibility::{Fungible, NonFungible}, diff --git a/polkadot/xcm/xcm-builder/src/nonfungible_adapter.rs b/polkadot/xcm/xcm-builder/src/nonfungible_adapter.rs index b69002eafc5b9945c9991a0fd3c981dd3d922338..8e6232ea64d271a9142a07adea573a59f4c17312 100644 --- a/polkadot/xcm/xcm-builder/src/nonfungible_adapter.rs +++ b/polkadot/xcm/xcm-builder/src/nonfungible_adapter.rs @@ -17,11 +17,11 @@ //! Adapters to work with [`frame_support::traits::tokens::nonfungible`] through XCM. use crate::MintLocation; +use core::{marker::PhantomData, result}; use frame_support::{ ensure, traits::{tokens::nonfungible, Get}, }; -use sp_std::{marker::PhantomData, prelude::*, result}; use xcm::latest::prelude::*; use xcm_executor::traits::{ ConvertLocation, Error as MatchError, MatchesNonFungible, TransactAsset, diff --git a/polkadot/xcm/xcm-builder/src/nonfungibles_adapter.rs b/polkadot/xcm/xcm-builder/src/nonfungibles_adapter.rs index 3fce953848ebdaf0021d84a333fdb00c346b5096..b111a05a4f1fc2a9c0559c42f672a9734fd110fe 100644 --- a/polkadot/xcm/xcm-builder/src/nonfungibles_adapter.rs +++ b/polkadot/xcm/xcm-builder/src/nonfungibles_adapter.rs @@ -17,11 +17,11 @@ //! Adapters to work with [`frame_support::traits::tokens::nonfungibles`] through XCM. use crate::{AssetChecking, MintLocation}; +use core::{marker::PhantomData, result}; use frame_support::{ ensure, traits::{tokens::nonfungibles, Get}, }; -use sp_std::{marker::PhantomData, prelude::*, result}; use xcm::latest::prelude::*; use xcm_executor::traits::{ ConvertLocation, Error as MatchError, MatchesNonFungibles, TransactAsset, diff --git a/polkadot/xcm/xcm-builder/src/origin_aliases.rs b/polkadot/xcm/xcm-builder/src/origin_aliases.rs index bbf810463a7c5054b368207774c977a49e3232aa..d568adc3127ce0c83207e04c87a27294f45c34fa 100644 --- a/polkadot/xcm/xcm-builder/src/origin_aliases.rs +++ b/polkadot/xcm/xcm-builder/src/origin_aliases.rs @@ -16,8 +16,8 @@ //! Implementation for `ContainsPair`. +use core::marker::PhantomData; use frame_support::traits::{Contains, ContainsPair}; -use sp_std::marker::PhantomData; use xcm::latest::prelude::*; /// Alias a Foreign `AccountId32` with a local `AccountId32` if the foreign `AccountId32` matches diff --git a/polkadot/xcm/xcm-builder/src/origin_conversion.rs b/polkadot/xcm/xcm-builder/src/origin_conversion.rs index f64b5660f66748458b6eec7cc3eb02625525de14..6e73c0dae7b698e151b67763e03a3f6dc2ea45b8 100644 --- a/polkadot/xcm/xcm-builder/src/origin_conversion.rs +++ b/polkadot/xcm/xcm-builder/src/origin_conversion.rs @@ -16,11 +16,11 @@ //! Various implementations for `ConvertOrigin`. +use core::marker::PhantomData; use frame_support::traits::{EnsureOrigin, Get, GetBacking, OriginTrait}; use frame_system::RawOrigin as SystemRawOrigin; use polkadot_parachain_primitives::primitives::IsSystem; use sp_runtime::traits::TryConvert; -use sp_std::marker::PhantomData; use xcm::latest::{BodyId, BodyPart, Junction, Junctions::*, Location, NetworkId, OriginKind}; use xcm_executor::traits::{ConvertLocation, ConvertOrigin}; diff --git a/polkadot/xcm/xcm-builder/src/pay.rs b/polkadot/xcm/xcm-builder/src/pay.rs index 35b624b041539e3d89fdb98a56d0910d5033417f..978c6870cdaf1e65ffc74adb175fd2e80ba53031 100644 --- a/polkadot/xcm/xcm-builder/src/pay.rs +++ b/polkadot/xcm/xcm-builder/src/pay.rs @@ -16,12 +16,13 @@ //! `PayOverXcm` struct for paying through XCM and getting the status back. +use alloc::vec; +use core::marker::PhantomData; use frame_support::traits::{ tokens::{Pay, PaymentStatus}, Get, }; use sp_runtime::traits::TryConvert; -use sp_std::{marker::PhantomData, vec}; use xcm::{opaque::lts::Weight, prelude::*}; use xcm_executor::traits::{QueryHandler, QueryResponseStatus}; @@ -199,7 +200,7 @@ pub struct LocatableAssetId { /// Adapter `struct` which implements a conversion from any `AssetKind` into a [`LocatableAssetId`] /// value using a fixed `Location` for the `location` field. -pub struct FixedLocation(sp_std::marker::PhantomData); +pub struct FixedLocation(core::marker::PhantomData); impl, AssetKind: Into> TryConvert for FixedLocation { diff --git a/polkadot/xcm/xcm-builder/src/process_xcm_message.rs b/polkadot/xcm/xcm-builder/src/process_xcm_message.rs index ef8c71fc2495175c3db20d89688fb983e180776d..2e6f8c5fb566166f600bd9d9a7ef20f8a39fae40 100644 --- a/polkadot/xcm/xcm-builder/src/process_xcm_message.rs +++ b/polkadot/xcm/xcm-builder/src/process_xcm_message.rs @@ -17,9 +17,9 @@ //! Implementation of `ProcessMessage` for an `ExecuteXcm` implementation. use codec::{Decode, FullCodec, MaxEncodedLen}; +use core::{fmt::Debug, marker::PhantomData}; use frame_support::traits::{ProcessMessage, ProcessMessageError}; use scale_info::TypeInfo; -use sp_std::{fmt::Debug, marker::PhantomData}; use sp_weights::{Weight, WeightMeter}; use xcm::prelude::*; @@ -118,6 +118,7 @@ impl< #[cfg(test)] mod tests { use super::*; + use alloc::vec; use codec::Encode; use frame_support::{ assert_err, assert_ok, diff --git a/polkadot/xcm/xcm-builder/src/routing.rs b/polkadot/xcm/xcm-builder/src/routing.rs index 543aef97c34095b06c8f4ef840d55f8a9eb0d49b..03ef780ef0325c24e4f53b1013e558a3e0d3990b 100644 --- a/polkadot/xcm/xcm-builder/src/routing.rs +++ b/polkadot/xcm/xcm-builder/src/routing.rs @@ -16,9 +16,10 @@ //! Various implementations for `SendXcm`. +use alloc::vec::Vec; use codec::Encode; +use core::{marker::PhantomData, result::Result}; use frame_system::unique; -use sp_std::{marker::PhantomData, result::Result, vec::Vec}; use xcm::prelude::*; use xcm_executor::{traits::FeeReason, FeesMode}; @@ -173,7 +174,7 @@ impl InspectMessageQueues for Tuple { /// `Inner::Ticket`. Therefore, this router aims to validate at least the passed `message`. /// /// NOTE: For use in mock runtimes which don't have the DMP/UMP/HRMP XCM validations. -pub struct EnsureDecodableXcm(sp_std::marker::PhantomData); +pub struct EnsureDecodableXcm(core::marker::PhantomData); impl SendXcm for EnsureDecodableXcm { type Ticket = Inner::Ticket; diff --git a/polkadot/xcm/xcm-builder/src/test_utils.rs b/polkadot/xcm/xcm-builder/src/test_utils.rs index 3131dece37570ecda2650c9e03ba44e5346b5f43..37a49a1b3dc7e742c291e49274490dd20aa1ddee 100644 --- a/polkadot/xcm/xcm-builder/src/test_utils.rs +++ b/polkadot/xcm/xcm-builder/src/test_utils.rs @@ -16,11 +16,11 @@ // Shared test utilities and implementations for the XCM Builder. +use alloc::vec::Vec; use frame_support::{ parameter_types, traits::{Contains, CrateVersion, PalletInfoData, PalletsInfoAccess}, }; -use sp_std::vec::Vec; pub use xcm::latest::{prelude::*, Weight}; use xcm_executor::traits::{ClaimAssets, DropAssets, VersionChangeNotifier}; pub use xcm_executor::{ diff --git a/polkadot/xcm/xcm-builder/src/tests/mock.rs b/polkadot/xcm/xcm-builder/src/tests/mock.rs index f35c73bdb68572b326557b362d20ec888850691e..ac43d217ff3ff221becd89878e95772cf4000ded 100644 --- a/polkadot/xcm/xcm-builder/src/tests/mock.rs +++ b/polkadot/xcm/xcm-builder/src/tests/mock.rs @@ -26,7 +26,12 @@ pub use crate::{ AllowTopLevelPaidExecutionFrom, AllowUnpaidExecutionFrom, FixedRateOfFungible, FixedWeightBounds, TakeWeightCredit, }; +pub use alloc::collections::{btree_map::BTreeMap, btree_set::BTreeSet}; pub use codec::{Decode, Encode}; +pub use core::{ + cell::{Cell, RefCell}, + fmt::Debug, +}; use frame_support::traits::{ContainsPair, Everything}; pub use frame_support::{ dispatch::{DispatchInfo, DispatchResultWithPostInfo, GetDispatchInfo, PostDispatchInfo}, @@ -34,11 +39,6 @@ pub use frame_support::{ sp_runtime::{traits::Dispatchable, DispatchError, DispatchErrorWithPostInfo}, traits::{Contains, Get, IsInVec}, }; -pub use sp_std::{ - cell::{Cell, RefCell}, - collections::{btree_map::BTreeMap, btree_set::BTreeSet}, - fmt::Debug, -}; pub use xcm::latest::{prelude::*, QueryId, Weight}; use xcm_executor::traits::{Properties, QueryHandler, QueryResponseStatus}; pub use xcm_executor::{ diff --git a/polkadot/xcm/xcm-builder/src/tests/mod.rs b/polkadot/xcm/xcm-builder/src/tests/mod.rs index 16ce3d2cf8ffef68d1f218fb1082cee8dc122b4b..379baaf5e37678a712a6ee337993b37bcbc2ecf5 100644 --- a/polkadot/xcm/xcm-builder/src/tests/mod.rs +++ b/polkadot/xcm/xcm-builder/src/tests/mod.rs @@ -15,6 +15,7 @@ // along with Polkadot. If not, see . use super::{test_utils::*, *}; +use alloc::{vec, vec::Vec}; use frame_support::{ assert_err, traits::{ConstU32, ContainsPair, ProcessMessageError}, diff --git a/polkadot/xcm/xcm-builder/src/universal_exports.rs b/polkadot/xcm/xcm-builder/src/universal_exports.rs index 9820d535f7efdeab1097d8b305fb9f62a19a02f4..8aa9602fcc297e9a402f7df11188773466b6ac90 100644 --- a/polkadot/xcm/xcm-builder/src/universal_exports.rs +++ b/polkadot/xcm/xcm-builder/src/universal_exports.rs @@ -17,9 +17,10 @@ //! Traits and utilities to help with origin mutation and bridging. use crate::InspectMessageQueues; +use alloc::{vec, vec::Vec}; use codec::{Decode, Encode}; +use core::{convert::TryInto, marker::PhantomData}; use frame_support::{ensure, traits::Get}; -use sp_std::{convert::TryInto, marker::PhantomData, prelude::*}; use xcm::prelude::*; use xcm_executor::traits::{validate_export, ExportXcm}; use SendError::*; @@ -149,7 +150,7 @@ impl NetworkExportTableItem { /// An adapter for the implementation of `ExporterFor`, which attempts to find the /// `(bridge_location, payment)` for the requested `network` and `remote_location` in the provided /// `T` table containing various exporters. -pub struct NetworkExportTable(sp_std::marker::PhantomData); +pub struct NetworkExportTable(core::marker::PhantomData); impl>> ExporterFor for NetworkExportTable { fn exporter_for( network: &NetworkId, @@ -649,7 +650,7 @@ mod tests { pub PaymentForNetworkAAndParachain2000: Asset = (Location::parent(), 150).into(); - pub BridgeTable: sp_std::vec::Vec = sp_std::vec![ + pub BridgeTable: alloc::vec::Vec = alloc::vec![ // NetworkA allows `Parachain(1000)` as remote location WITHOUT payment. NetworkExportTableItem::new( NetworkA::get(), diff --git a/polkadot/xcm/xcm-builder/src/weight.rs b/polkadot/xcm/xcm-builder/src/weight.rs index 1efa42ce95601d34b1f28e69b3c3ce59685ce9af..7861fdcc2e579b54b03fe509956c9a46e3405c2c 100644 --- a/polkadot/xcm/xcm-builder/src/weight.rs +++ b/polkadot/xcm/xcm-builder/src/weight.rs @@ -15,6 +15,7 @@ // along with Polkadot. If not, see . use codec::Decode; +use core::{marker::PhantomData, result::Result}; use frame_support::{ dispatch::GetDispatchInfo, traits::{ @@ -27,7 +28,6 @@ use frame_support::{ }, }; use sp_runtime::traits::{SaturatedConversion, Saturating, Zero}; -use sp_std::{marker::PhantomData, result::Result}; use xcm::latest::{prelude::*, GetWeight, Weight}; use xcm_executor::{ traits::{WeightBounds, WeightTrader}, diff --git a/polkadot/xcm/xcm-builder/tests/mock/mod.rs b/polkadot/xcm/xcm-builder/tests/mock/mod.rs index 582d596b78f1092397dc821dd9152f4295a350fd..0468b0a5410c416a0703502cc38a13dba2a79853 100644 --- a/polkadot/xcm/xcm-builder/tests/mock/mod.rs +++ b/polkadot/xcm/xcm-builder/tests/mock/mod.rs @@ -15,6 +15,7 @@ // along with Polkadot. If not, see . use codec::Encode; +use core::cell::RefCell; use frame_support::{ construct_runtime, derive_impl, parameter_types, traits::{Everything, Nothing}, @@ -23,7 +24,6 @@ use frame_support::{ use frame_system::EnsureRoot; use primitive_types::H256; use sp_runtime::{traits::IdentityLookup, AccountId32, BuildStorage}; -use sp_std::cell::RefCell; use polkadot_parachain_primitives::primitives::Id as ParaId; use polkadot_runtime_parachains::{configuration, origin, shared}; diff --git a/polkadot/xcm/xcm-executor/Cargo.toml b/polkadot/xcm/xcm-executor/Cargo.toml index 8f7b94612b597c239e15afee33f04b07e3a77dc0..cc966f91fe4db948c38a9d4faeff267aefc7e59c 100644 --- a/polkadot/xcm/xcm-executor/Cargo.toml +++ b/polkadot/xcm/xcm-executor/Cargo.toml @@ -15,14 +15,13 @@ environmental = { workspace = true } codec = { features = ["derive"], workspace = true } scale-info = { features = ["derive", "serde"], workspace = true } xcm = { workspace = true } -sp-std = { workspace = true } sp-io = { workspace = true } sp-arithmetic = { workspace = true } sp-core = { workspace = true } sp-runtime = { workspace = true } sp-weights = { workspace = true } frame-support = { workspace = true } -log = { workspace = true } +tracing = { workspace = true } frame-benchmarking = { optional = true, workspace = true } [features] @@ -37,13 +36,12 @@ std = [ "environmental/std", "frame-benchmarking/std", "frame-support/std", - "log/std", "scale-info/std", "sp-arithmetic/std", "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", "sp-weights/std", + "tracing/std", "xcm/std", ] diff --git a/polkadot/xcm/xcm-executor/src/assets.rs b/polkadot/xcm/xcm-executor/src/assets.rs index 4407752f7024273a28883b695d895bcd6a9e7d35..09e7535ebf81d09f07a119224dad42647d4bc366 100644 --- a/polkadot/xcm/xcm-executor/src/assets.rs +++ b/polkadot/xcm/xcm-executor/src/assets.rs @@ -14,12 +14,12 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -use sp_runtime::{traits::Saturating, RuntimeDebug}; -use sp_std::{ +use alloc::{ collections::{btree_map::BTreeMap, btree_set::BTreeSet}, - mem, - prelude::*, + vec::Vec, }; +use core::mem; +use sp_runtime::{traits::Saturating, RuntimeDebug}; use xcm::latest::{ Asset, AssetFilter, AssetId, AssetInstance, Assets, Fungibility::{Fungible, NonFungible}, @@ -520,7 +520,9 @@ impl AssetsInHolding { #[cfg(test)] mod tests { use super::*; + use alloc::vec; use xcm::latest::prelude::*; + #[allow(non_snake_case)] /// Concrete fungible constructor fn CF(amount: u128) -> Asset { diff --git a/polkadot/xcm/xcm-executor/src/lib.rs b/polkadot/xcm/xcm-executor/src/lib.rs index da9de93ca0f6f1a94f388d9078e95305e5c210e9..1daf5ae750cfbd0bb5a407eceb8d621023586fe0 100644 --- a/polkadot/xcm/xcm-executor/src/lib.rs +++ b/polkadot/xcm/xcm-executor/src/lib.rs @@ -16,7 +16,11 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + +use alloc::{vec, vec::Vec}; use codec::{Decode, Encode}; +use core::{fmt::Debug, marker::PhantomData}; use frame_support::{ dispatch::GetDispatchInfo, ensure, @@ -24,7 +28,6 @@ use frame_support::{ }; use sp_core::defer; use sp_io::hashing::blake2_128; -use sp_std::{fmt::Debug, marker::PhantomData, prelude::*}; use sp_weights::Weight; use xcm::latest::prelude::*; @@ -208,9 +211,12 @@ impl ExecuteXcm for XcmExecutor Outcome { let origin = origin.into(); - log::trace!( + tracing::trace!( target: "xcm::execute", - "origin: {origin:?}, message: {message:?}, weight_credit: {weight_credit:?}", + ?origin, + ?message, + ?weight_credit, + "Executing message", ); let mut properties = Properties { weight_credit, message_id: None }; @@ -226,10 +232,13 @@ impl ExecuteXcm for XcmExecutor ExecuteXcm for XcmExecutor for frame_benchmarking::BenchmarkError { fn from(error: ExecutorError) -> Self { - log::error!( - "XCM ERROR >> Index: {:?}, Error: {:?}, Weight: {:?}", - error.index, - error.xcm_error, - error.weight + tracing::error!( + index = ?error.index, + xcm_error = ?error.xcm_error, + weight = ?error.weight, + "XCM ERROR", ); Self::Stop("xcm executor error: see error logs") } @@ -326,10 +335,12 @@ impl XcmExecutor { let mut weight_used = xcm_weight.saturating_sub(self.total_surplus); if !self.holding.is_empty() { - log::trace!( + tracing::trace!( target: "xcm::post_process", - "Trapping assets in holding register: {:?}, context: {:?} (original_origin: {:?})", - self.holding, self.context, self.original_origin, + holding_register = ?self.holding, + context = ?self.context, + original_origin = ?self.original_origin, + "Trapping assets in holding register", ); let effective_origin = self.context.origin.as_ref().unwrap_or(&self.original_origin); let trap_weight = @@ -342,7 +353,13 @@ impl XcmExecutor { // TODO: #2841 #REALWEIGHT We should deduct the cost of any instructions following // the error which didn't end up being executed. Some((_i, e)) => { - log::trace!(target: "xcm::post_process", "Execution errored at {:?}: {:?} (original_origin: {:?})", _i, e, self.original_origin); + tracing::trace!( + target: "xcm::post_process", + instruction = ?_i, + error = ?e, + original_origin = ?self.original_origin, + "Execution failed", + ); Outcome::Incomplete { used: weight_used, error: e } }, } @@ -363,8 +380,12 @@ impl XcmExecutor { msg: Xcm<()>, reason: FeeReason, ) -> Result { - log::trace!( - target: "xcm::send", "Sending msg: {msg:?}, to destination: {dest:?}, (reason: {reason:?})" + tracing::trace!( + target: "xcm::send", + ?msg, + destination = ?dest, + reason = ?reason, + "Sending msg", ); let (ticket, fee) = validate_send::(dest, msg)?; self.take_fee(fee, reason)?; @@ -374,7 +395,7 @@ impl XcmExecutor { /// Remove the registered error handler and return it. Do not refund its weight. fn take_error_handler(&mut self) -> Xcm { let mut r = Xcm::(vec![]); - sp_std::mem::swap(&mut self.error_handler, &mut r); + core::mem::swap(&mut self.error_handler, &mut r); self.error_handler_weight = Weight::zero(); r } @@ -389,7 +410,7 @@ impl XcmExecutor { /// Remove the registered appendix and return it. fn take_appendix(&mut self) -> Xcm { let mut r = Xcm::(vec![]); - sp_std::mem::swap(&mut self.appendix, &mut r); + core::mem::swap(&mut self.appendix, &mut r); self.appendix_weight = Weight::zero(); r } @@ -400,7 +421,12 @@ impl XcmExecutor { // `holding_limit` items (which has a best case outcome of holding.len() == holding_limit), // then the operation is guaranteed to succeed. let worst_case_holding_len = self.holding.len() + assets_length; - log::trace!(target: "xcm::ensure_can_subsume_assets", "worst_case_holding_len: {:?}, holding_limit: {:?}", worst_case_holding_len, self.holding_limit); + tracing::trace!( + target: "xcm::ensure_can_subsume_assets", + ?worst_case_holding_len, + holding_limit = ?self.holding_limit, + "Ensuring subsume assets work", + ); ensure!(worst_case_holding_len <= self.holding_limit * 2, XcmError::HoldingWouldOverflow); Ok(()) } @@ -408,12 +434,12 @@ impl XcmExecutor { /// Refund any unused weight. fn refund_surplus(&mut self) -> Result<(), XcmError> { let current_surplus = self.total_surplus.saturating_sub(self.total_refunded); - log::trace!( + tracing::trace!( target: "xcm::refund_surplus", - "total_surplus: {:?}, total_refunded: {:?}, current_surplus: {:?}", - self.total_surplus, - self.total_refunded, - current_surplus, + total_surplus = ?self.total_surplus, + total_refunded = ?self.total_refunded, + ?current_surplus, + "Refunding surplus", ); if current_surplus.any_gt(Weight::zero()) { if let Some(w) = self.trader.refund_weight(current_surplus, &self.context) { @@ -426,7 +452,7 @@ impl XcmExecutor { .defensive_proof( "refund_weight returned an asset capable of buying weight; qed", ); - log::error!( + tracing::error!( target: "xcm::refund_surplus", "error: HoldingWouldOverflow", ); @@ -436,10 +462,9 @@ impl XcmExecutor { self.holding.subsume_assets(w.into()); } } - log::trace!( + tracing::trace!( target: "xcm::refund_surplus", - "total_refunded: {:?}", - self.total_refunded, + total_refunded = ?self.total_refunded, ); Ok(()) } @@ -448,13 +473,13 @@ impl XcmExecutor { if Config::FeeManager::is_waived(self.origin_ref(), reason.clone()) { return Ok(()) } - log::trace!( + tracing::trace!( target: "xcm::fees", - "taking fee: {:?} from origin_ref: {:?} in fees_mode: {:?} for a reason: {:?}", - fee, - self.origin_ref(), - self.fees_mode, - reason, + ?fee, + origin_ref = ?self.origin_ref(), + fees_mode = ?self.fees_mode, + ?reason, + "Taking fees", ); let paid = if self.fees_mode.jit_withdraw { let origin = self.origin_ref().ok_or(XcmError::BadOrigin)?; @@ -507,7 +532,7 @@ impl XcmExecutor { let reanchor_context = Config::UniversalLocation::get(); let reanchored = reanchorable.reanchored(&destination, &reanchor_context).map_err(|error| { - log::error!(target: "xcm::reanchor", "Failed reanchoring with error {error:?}"); + tracing::error!(target: "xcm::reanchor", ?error, "Failed reanchoring with error"); XcmError::ReanchorFailed })?; Ok((reanchored, reanchor_context)) @@ -530,13 +555,12 @@ impl XcmExecutor { } fn process(&mut self, xcm: Xcm) -> Result<(), ExecutorError> { - log::trace!( + tracing::trace!( target: "xcm::process", - "origin: {:?}, total_surplus/refunded: {:?}/{:?}, error_handler_weight: {:?}", - self.origin_ref(), - self.total_surplus, - self.total_refunded, - self.error_handler_weight, + origin = ?self.origin_ref(), + total_surplus = ?self.total_surplus, + total_refunded = ?self.total_refunded, + error_handler_weight = ?self.error_handler_weight, ); let mut result = Ok(()); for (i, instr) in xcm.0.into_iter().enumerate() { @@ -566,7 +590,7 @@ impl XcmExecutor { self.process_instruction(instr) }); if let Err(e) = inst_res { - log::trace!(target: "xcm::execute", "!!! ERROR: {:?}", e); + tracing::trace!(target: "xcm::execute", "!!! ERROR: {:?}", e); *r = Err(ExecutorError { index: i as u32, xcm_error: e, @@ -588,11 +612,12 @@ impl XcmExecutor { &mut self, instr: Instruction, ) -> Result<(), XcmError> { - log::trace!( + tracing::trace!( target: "xcm::process_instruction", - "=== {:?}", - instr + instruction = ?instr, + "Processing instruction", ); + match instr { WithdrawAsset(assets) => { let origin = self.origin_ref().ok_or(XcmError::BadOrigin)?; @@ -694,7 +719,7 @@ impl XcmExecutor { Transact { origin_kind, require_weight_at_most, mut call } => { // We assume that the Relay-chain is allowed to use transact on this parachain. let origin = self.cloned_origin().ok_or_else(|| { - log::trace!( + tracing::trace!( target: "xcm::process_instruction::transact", "No origin provided", ); @@ -704,7 +729,7 @@ impl XcmExecutor { // TODO: #2841 #TRANSACTFILTER allow the trait to issue filters for the relay-chain let message_call = call.take_decoded().map_err(|_| { - log::trace!( + tracing::trace!( target: "xcm::process_instruction::transact", "Failed to decode call", ); @@ -712,13 +737,14 @@ impl XcmExecutor { XcmError::FailedToDecode })?; - log::trace!( + tracing::trace!( target: "xcm::process_instruction::transact", - "Processing call: {message_call:?}", + ?call, + "Processing call", ); if !Config::SafeCallFilter::contains(&message_call) { - log::trace!( + tracing::trace!( target: "xcm::process_instruction::transact", "Call filtered by `SafeCallFilter`", ); @@ -729,26 +755,31 @@ impl XcmExecutor { let dispatch_origin = Config::OriginConverter::convert_origin(origin.clone(), origin_kind).map_err( |_| { - log::trace!( + tracing::trace!( target: "xcm::process_instruction::transact", - "Failed to convert origin {origin:?} and origin kind {origin_kind:?} to a local origin." + ?origin, + ?origin_kind, + "Failed to convert origin to a local origin." ); XcmError::BadOrigin }, )?; - log::trace!( + tracing::trace!( target: "xcm::process_instruction::transact", - "Dispatching with origin: {dispatch_origin:?}", + origin = ?dispatch_origin, + "Dispatching with origin", ); let weight = message_call.get_dispatch_info().weight; if !weight.all_lte(require_weight_at_most) { - log::trace!( + tracing::trace!( target: "xcm::process_instruction::transact", - "Max {weight} bigger than require at most {require_weight_at_most}", + %weight, + %require_weight_at_most, + "Max weight bigger than require at most", ); return Err(XcmError::MaxWeightInvalid) @@ -757,17 +788,19 @@ impl XcmExecutor { let maybe_actual_weight = match Config::CallDispatcher::dispatch(message_call, dispatch_origin) { Ok(post_info) => { - log::trace!( + tracing::trace!( target: "xcm::process_instruction::transact", - "Dispatch successful: {post_info:?}" + ?post_info, + "Dispatch successful" ); self.transact_status = MaybeErrorCode::Success; post_info.actual_weight }, Err(error_and_info) => { - log::trace!( + tracing::trace!( target: "xcm::process_instruction::transact", - "Dispatch failed {error_and_info:?}" + ?error_and_info, + "Dispatch failed" ); self.transact_status = error_and_info.error.encode().into(); diff --git a/polkadot/xcm/xcm-executor/src/traits/asset_lock.rs b/polkadot/xcm/xcm-executor/src/traits/asset_lock.rs index b6270c529452133c011fef24b9ac63e057acb91a..b4e9f32983fd52f27eb66d31bb7098d780389de9 100644 --- a/polkadot/xcm/xcm-executor/src/traits/asset_lock.rs +++ b/polkadot/xcm/xcm-executor/src/traits/asset_lock.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -use sp_std::convert::Infallible; +use core::convert::Infallible; use xcm::prelude::*; #[derive(Debug)] diff --git a/polkadot/xcm/xcm-executor/src/traits/conversion.rs b/polkadot/xcm/xcm-executor/src/traits/conversion.rs index 9e2f4c83997ac2b370536822454bcfbea41c4896..bc62ad655669756793327d23d3d24f5f2da1be9c 100644 --- a/polkadot/xcm/xcm-executor/src/traits/conversion.rs +++ b/polkadot/xcm/xcm-executor/src/traits/conversion.rs @@ -14,9 +14,9 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . +use core::{marker::PhantomData, result::Result}; use frame_support::traits::{Contains, OriginTrait}; use sp_runtime::{traits::Dispatchable, DispatchErrorWithPostInfo}; -use sp_std::{marker::PhantomData, result::Result}; use xcm::latest::prelude::*; /// Means of converting a location into an account identifier. @@ -88,19 +88,45 @@ pub trait ConvertOrigin { #[impl_trait_for_tuples::impl_for_tuples(30)] impl ConvertOrigin for Tuple { fn convert_origin(origin: impl Into, kind: OriginKind) -> Result { + let origin = origin.into(); + + tracing::trace!( + target: "xcm::convert_origin", + ?origin, + ?kind, + "Converting origin", + ); + for_tuples!( #( + let convert_origin = core::any::type_name::(); + let origin = match Tuple::convert_origin(origin, kind) { - Err(o) => o, - r => return r + Err(o) => { + tracing::trace!( + target: "xcm::convert_origin", + %convert_origin, + "Convert origin step failed", + ); + + o + }, + Ok(o) => { + tracing::trace!( + target: "xcm::convert_origin", + %convert_origin, + "Convert origin step succeeded", + ); + + return Ok(o) + } }; )* ); - let origin = origin.into(); - log::trace!( + + tracing::trace!( target: "xcm::convert_origin", - "could not convert: origin: {:?}, kind: {:?}", - origin, - kind, + "Converting origin failed", ); + Err(origin) } } diff --git a/polkadot/xcm/xcm-executor/src/traits/on_response.rs b/polkadot/xcm/xcm-executor/src/traits/on_response.rs index 5d2412d6137552db68d30cf61b25b10521afd966..a4ed6014b4fc8bc423bbc5cceb20cee15fe7890f 100644 --- a/polkadot/xcm/xcm-executor/src/traits/on_response.rs +++ b/polkadot/xcm/xcm-executor/src/traits/on_response.rs @@ -16,10 +16,9 @@ use crate::{Junctions::Here, Xcm}; use codec::{Decode, Encode}; -use core::result; +use core::{fmt::Debug, result}; use frame_support::{pallet_prelude::Get, parameter_types}; use sp_arithmetic::traits::Zero; -use sp_std::fmt::Debug; use xcm::latest::{ Error as XcmError, InteriorLocation, Location, QueryId, Response, Result as XcmResult, Weight, XcmContext, diff --git a/polkadot/xcm/xcm-executor/src/traits/should_execute.rs b/polkadot/xcm/xcm-executor/src/traits/should_execute.rs index e76d56bfe6164d16487f65ed79c1a1a58a9949fe..ec9ef70cc817e5a230ae843581fb736ce06770ee 100644 --- a/polkadot/xcm/xcm-executor/src/traits/should_execute.rs +++ b/polkadot/xcm/xcm-executor/src/traits/should_execute.rs @@ -14,8 +14,8 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . +use core::result::Result; use frame_support::traits::ProcessMessageError; -use sp_std::result::Result; use xcm::latest::{Instruction, Location, Weight, XcmHash}; /// Properties of an XCM message and its imminent execution. @@ -59,19 +59,35 @@ impl ShouldExecute for Tuple { properties: &mut Properties, ) -> Result<(), ProcessMessageError> { for_tuples!( #( - match Tuple::should_execute(origin, instructions, max_weight, properties) { - Ok(()) => return Ok(()), - _ => (), + let barrier = core::any::type_name::(); + match Tuple::should_execute(origin, instructions, max_weight, properties) { + Ok(()) => { + tracing::trace!( + target: "xcm::should_execute", + ?origin, + ?instructions, + ?max_weight, + ?properties, + %barrier, + "pass barrier", + ); + return Ok(()) + }, + Err(error) => { + tracing::trace!( + target: "xcm::should_execute", + ?origin, + ?instructions, + ?max_weight, + ?properties, + ?error, + %barrier, + "did not pass barrier", + ); + }, } )* ); - log::trace!( - target: "xcm::should_execute", - "did not pass barrier: origin: {:?}, instructions: {:?}, max_weight: {:?}, properties: {:?}", - origin, - instructions, - max_weight, - properties, - ); + Err(ProcessMessageError::Unsupported) } } diff --git a/polkadot/xcm/xcm-executor/src/traits/token_matching.rs b/polkadot/xcm/xcm-executor/src/traits/token_matching.rs index e9a7e3ad845daf2f3f0a8da05c7d9d3d3711a291..aa44aee4f9de39cd7bcda09e3ce3b4e294d8ee6d 100644 --- a/polkadot/xcm/xcm-executor/src/traits/token_matching.rs +++ b/polkadot/xcm/xcm-executor/src/traits/token_matching.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -use sp_std::result; +use core::result; use xcm::latest::prelude::*; pub trait MatchesFungible { @@ -27,7 +27,7 @@ impl MatchesFungible for Tuple { for_tuples!( #( match Tuple::matches_fungible(a) { o @ Some(_) => return o, _ => () } )* ); - log::trace!(target: "xcm::matches_fungible", "did not match fungible asset: {:?}", &a); + tracing::trace!(target: "xcm::matches_fungible", asset = ?a, "did not match fungible asset"); None } } @@ -42,7 +42,7 @@ impl MatchesNonFungible for Tuple { for_tuples!( #( match Tuple::matches_nonfungible(a) { o @ Some(_) => return o, _ => () } )* ); - log::trace!(target: "xcm::matches_non_fungible", "did not match non-fungible asset: {:?}", &a); + tracing::trace!(target: "xcm::matches_non_fungible", asset = ?a, "did not match non-fungible asset"); None } } @@ -86,7 +86,7 @@ impl MatchesFungibles for Tuple { for_tuples!( #( match Tuple::matches_fungibles(a) { o @ Ok(_) => return o, _ => () } )* ); - log::trace!(target: "xcm::matches_fungibles", "did not match fungibles asset: {:?}", &a); + tracing::trace!(target: "xcm::matches_fungibles", asset = ?a, "did not match fungibles asset"); Err(Error::AssetNotHandled) } } @@ -101,7 +101,7 @@ impl MatchesNonFungibles for Tuple { for_tuples!( #( match Tuple::matches_nonfungibles(a) { o @ Ok(_) => return o, _ => () } )* ); - log::trace!(target: "xcm::matches_non_fungibles", "did not match fungibles asset: {:?}", &a); + tracing::trace!(target: "xcm::matches_non_fungibles", asset = ?a, "did not match fungibles asset"); Err(Error::AssetNotHandled) } } diff --git a/polkadot/xcm/xcm-executor/src/traits/transact_asset.rs b/polkadot/xcm/xcm-executor/src/traits/transact_asset.rs index e8a52d8256851b4baf9565ba5ddeb47ae28667a7..c2331f805b4bddd51493fa7d9ec8c384baa20f14 100644 --- a/polkadot/xcm/xcm-executor/src/traits/transact_asset.rs +++ b/polkadot/xcm/xcm-executor/src/traits/transact_asset.rs @@ -15,7 +15,7 @@ // along with Polkadot. If not, see . use crate::AssetsInHolding; -use sp_std::result::Result; +use core::result::Result; use xcm::latest::{Asset, Error as XcmError, Location, Result as XcmResult, XcmContext}; /// Facility for asset transacting. @@ -148,12 +148,12 @@ impl TransactAsset for Tuple { r => return r, } )* ); - log::trace!( + tracing::trace!( target: "xcm::TransactAsset::can_check_in", - "asset not found: what: {:?}, origin: {:?}, context: {:?}", - what, - origin, - context, + ?what, + ?origin, + ?context, + "asset not found", ); Err(XcmError::AssetNotFound) } @@ -171,12 +171,12 @@ impl TransactAsset for Tuple { r => return r, } )* ); - log::trace!( + tracing::trace!( target: "xcm::TransactAsset::can_check_out", - "asset not found: what: {:?}, dest: {:?}, context: {:?}", - what, - dest, - context, + ?what, + ?dest, + ?context, + "asset not found", ); Err(XcmError::AssetNotFound) } @@ -194,12 +194,12 @@ impl TransactAsset for Tuple { r => return r, } )* ); - log::trace!( + tracing::trace!( target: "xcm::TransactAsset::deposit_asset", - "did not deposit asset: what: {:?}, who: {:?}, context: {:?}", - what, - who, - context, + ?what, + ?who, + ?context, + "did not deposit asset", ); Err(XcmError::AssetNotFound) } @@ -215,12 +215,12 @@ impl TransactAsset for Tuple { r => return r, } )* ); - log::trace!( + tracing::trace!( target: "xcm::TransactAsset::withdraw_asset", - "did not withdraw asset: what: {:?}, who: {:?}, maybe_context: {:?}", - what, - who, - maybe_context, + ?what, + ?who, + ?maybe_context, + "did not withdraw asset", ); Err(XcmError::AssetNotFound) } @@ -237,13 +237,13 @@ impl TransactAsset for Tuple { r => return r, } )* ); - log::trace!( + tracing::trace!( target: "xcm::TransactAsset::internal_transfer_asset", - "did not transfer asset: what: {:?}, from: {:?}, to: {:?}, context: {:?}", - what, - from, - to, - context, + ?what, + ?from, + ?to, + ?context, + "did not transfer asset", ); Err(XcmError::AssetNotFound) } diff --git a/polkadot/xcm/xcm-executor/src/traits/weight.rs b/polkadot/xcm/xcm-executor/src/traits/weight.rs index efb9a2dfb6efdf65a074f631c691c0bfec88d600..72de3e0f433b96ed1718be70e3c0feb20340453a 100644 --- a/polkadot/xcm/xcm-executor/src/traits/weight.rs +++ b/polkadot/xcm/xcm-executor/src/traits/weight.rs @@ -15,7 +15,7 @@ // along with Polkadot. If not, see . use crate::AssetsInHolding; -use sp_std::result::Result; +use core::result::Result; use xcm::latest::{prelude::*, Weight}; /// Determine the weight of an XCM message. @@ -80,18 +80,38 @@ impl WeightTrader for Tuple { let mut too_expensive_error_found = false; let mut last_error = None; for_tuples!( #( + let weight_trader = core::any::type_name::(); + match Tuple.buy_weight(weight, payment.clone(), context) { - Ok(assets) => return Ok(assets), - Err(e) => { - if let XcmError::TooExpensive = e { + Ok(assets) => { + tracing::trace!( + target: "xcm::buy_weight", + %weight_trader, + "Buy weight succeeded", + ); + + return Ok(assets) + }, + Err(error) => { + if let XcmError::TooExpensive = error { too_expensive_error_found = true; } - last_error = Some(e) + last_error = Some(error); + + tracing::trace!( + target: "xcm::buy_weight", + ?error, + %weight_trader, + "Weight trader failed", + ); } } )* ); - log::trace!(target: "xcm::buy_weight", "last_error: {:?}, too_expensive_error_found: {}", last_error, too_expensive_error_found); + tracing::trace!( + target: "xcm::buy_weight", + "Buy weight failed", + ); // if we have multiple traders, and first one returns `TooExpensive` and others fail e.g. // `AssetNotFound` then it is more accurate to return `TooExpensive` then `AssetNotFound` diff --git a/polkadot/xcm/xcm-runtime-apis/Cargo.toml b/polkadot/xcm/xcm-runtime-apis/Cargo.toml index 7d3f1a20b639a719db1fbc023dcc688eff6f2a52..748d5af68a1fdee6c62873370d33387d55a06e6f 100644 --- a/polkadot/xcm/xcm-runtime-apis/Cargo.toml +++ b/polkadot/xcm/xcm-runtime-apis/Cargo.toml @@ -16,7 +16,6 @@ scale-info = { features = ["derive", "serde"], workspace = true } frame-support = { workspace = true } sp-api = { workspace = true } -sp-std = { workspace = true } sp-weights = { workspace = true } xcm = { workspace = true } xcm-executor = { workspace = true } @@ -48,7 +47,6 @@ std = [ "scale-info/std", "sp-api/std", "sp-io/std", - "sp-std/std", "sp-weights/std", "xcm-builder/std", "xcm-executor/std", diff --git a/polkadot/xcm/xcm-runtime-apis/src/conversions.rs b/polkadot/xcm/xcm-runtime-apis/src/conversions.rs index d422664557e0eb94729a6876fc9001cf786d4b72..e5eeac013fee6e8b7222429dfd0ed93afa9384c9 100644 --- a/polkadot/xcm/xcm-runtime-apis/src/conversions.rs +++ b/polkadot/xcm/xcm-runtime-apis/src/conversions.rs @@ -44,7 +44,7 @@ pub enum Error { /// It is useful when you already have a `ConvertLocation` implementation and a default /// `Ss58Prefix`. pub struct LocationToAccountHelper( - sp_std::marker::PhantomData<(AccountId, Conversion)>, + core::marker::PhantomData<(AccountId, Conversion)>, ); impl> LocationToAccountHelper diff --git a/polkadot/xcm/xcm-runtime-apis/src/dry_run.rs b/polkadot/xcm/xcm-runtime-apis/src/dry_run.rs index 9828acab402300a55abf2ece820cf8871c76a858..2a1a0daf0d5d5d0bae868e973df56f7e35b41592 100644 --- a/polkadot/xcm/xcm-runtime-apis/src/dry_run.rs +++ b/polkadot/xcm/xcm-runtime-apis/src/dry_run.rs @@ -18,9 +18,9 @@ //! This API can be used to simulate XCMs and, for example, find the fees //! that need to be paid. +use alloc::vec::Vec; use codec::{Decode, Encode}; use frame_support::pallet_prelude::{DispatchResultWithPostInfo, TypeInfo}; -use sp_std::vec::Vec; use xcm::prelude::*; /// Effects of dry-running an extrinsic. diff --git a/polkadot/xcm/xcm-runtime-apis/src/fees.rs b/polkadot/xcm/xcm-runtime-apis/src/fees.rs index 572d4edf533865e66299eba7bd0d22a890547603..3445d42ecab3bda1a212e60f2be5583a31e04b58 100644 --- a/polkadot/xcm/xcm-runtime-apis/src/fees.rs +++ b/polkadot/xcm/xcm-runtime-apis/src/fees.rs @@ -16,9 +16,9 @@ //! Runtime API definition for getting XCM fees. +use alloc::vec::Vec; use codec::{Decode, Encode}; use frame_support::pallet_prelude::TypeInfo; -use sp_std::vec::Vec; use sp_weights::Weight; use xcm::{Version, VersionedAssetId, VersionedAssets, VersionedLocation, VersionedXcm}; diff --git a/polkadot/xcm/xcm-runtime-apis/src/lib.rs b/polkadot/xcm/xcm-runtime-apis/src/lib.rs index 7b3b86214b3a14d3886b8dec2928d564358e370f..b106836c1132b253acdc01e8b9fd63a7c4ff828b 100644 --- a/polkadot/xcm/xcm-runtime-apis/src/lib.rs +++ b/polkadot/xcm/xcm-runtime-apis/src/lib.rs @@ -18,6 +18,8 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + /// Exposes runtime APIs for various XCM-related conversions. pub mod conversions; diff --git a/polkadot/xcm/xcm-runtime-apis/tests/mock.rs b/polkadot/xcm/xcm-runtime-apis/tests/mock.rs index e723e254635659de94c489363260da84e27b440e..c76b26fcd2a337545450da4d77cb0103c3e8eb8c 100644 --- a/polkadot/xcm/xcm-runtime-apis/tests/mock.rs +++ b/polkadot/xcm/xcm-runtime-apis/tests/mock.rs @@ -18,6 +18,7 @@ //! Implements both runtime APIs for fee estimation and getting the messages for transfers. use codec::Encode; +use core::{cell::RefCell, marker::PhantomData}; use frame_support::{ construct_runtime, derive_impl, parameter_types, sp_runtime, sp_runtime::{ @@ -32,7 +33,6 @@ use frame_support::{ }; use frame_system::{EnsureRoot, RawOrigin as SystemRawOrigin}; use pallet_xcm::TestWeightInfo; -use sp_std::{cell::RefCell, marker::PhantomData}; use xcm::{prelude::*, Version as XcmVersion}; use xcm_builder::{ AllowTopLevelPaidExecutionFrom, ConvertedConcreteId, EnsureXcmOrigin, FixedRateOfFungible, diff --git a/polkadot/xcm/xcm-simulator/example/src/parachain/mod.rs b/polkadot/xcm/xcm-simulator/example/src/parachain/mod.rs index 93c8302757cb061bc1f97d003ce8b7de2374448e..bfb455aba3f9302200d58bcd6b7c074d1053468f 100644 --- a/polkadot/xcm/xcm-simulator/example/src/parachain/mod.rs +++ b/polkadot/xcm/xcm-simulator/example/src/parachain/mod.rs @@ -31,7 +31,6 @@ use sp_runtime::{ traits::{Get, IdentityLookup}, AccountId32, }; -use sp_std::prelude::*; use xcm::latest::prelude::*; use xcm_builder::{EnsureXcmOrigin, SignedToAccountId32}; use xcm_executor::{traits::ConvertLocation, XcmExecutor}; @@ -101,7 +100,7 @@ impl EnsureOriginWithArg for ForeignCreators { fn try_origin( o: RuntimeOrigin, a: &Location, - ) -> sp_std::result::Result { + ) -> core::result::Result { let origin_location = pallet_xcm::EnsureXcm::::try_origin(o.clone())?; if !a.starts_with(&origin_location) { return Err(o); diff --git a/polkadot/xcm/xcm-simulator/fuzzer/src/parachain.rs b/polkadot/xcm/xcm-simulator/fuzzer/src/parachain.rs index 11435868d4682ae4229b7939f2a8685316c7e296..616329a2f06b43f73d059a3471f49c2d7fa82e95 100644 --- a/polkadot/xcm/xcm-simulator/fuzzer/src/parachain.rs +++ b/polkadot/xcm/xcm-simulator/fuzzer/src/parachain.rs @@ -29,7 +29,6 @@ use sp_runtime::{ traits::{AccountIdLookup, BlakeTwo256, Hash, IdentifyAccount, Verify}, MultiAddress, MultiSignature, }; -use sp_std::prelude::*; use pallet_xcm::XcmPassthrough; use polkadot_core_primitives::BlockNumber as RelayBlockNumber; diff --git a/polkadot/xcm/xcm-simulator/src/lib.rs b/polkadot/xcm/xcm-simulator/src/lib.rs index a6747a4789edf8065462b831893ebc8b0284dd18..59df394406ea00fd3a3d0edb5e78efe1475e77bc 100644 --- a/polkadot/xcm/xcm-simulator/src/lib.rs +++ b/polkadot/xcm/xcm-simulator/src/lib.rs @@ -20,15 +20,18 @@ /// Used for sending messages. pub mod mock_message_queue; +extern crate alloc; + pub use codec::Encode; pub use paste; +pub use alloc::collections::vec_deque::VecDeque; +pub use core::{cell::RefCell, marker::PhantomData}; pub use frame_support::{ traits::{EnqueueMessage, Get, ProcessMessage, ProcessMessageError, ServiceQueues}, weights::{Weight, WeightMeter}, }; pub use sp_io::{hashing::blake2_256, TestExternalities}; -pub use sp_std::{cell::RefCell, collections::vec_deque::VecDeque, marker::PhantomData}; pub use polkadot_core_primitives::BlockNumber as RelayBlockNumber; pub use polkadot_parachain_primitives::primitives::{ diff --git a/polkadot/xcm/xcm-simulator/src/mock_message_queue.rs b/polkadot/xcm/xcm-simulator/src/mock_message_queue.rs index 96b47999fe952145b09faa93aaf2cefd5143acb9..bf7b0e15967c027738751cff3edaa27c29f41a0c 100644 --- a/polkadot/xcm/xcm-simulator/src/mock_message_queue.rs +++ b/polkadot/xcm/xcm-simulator/src/mock_message_queue.rs @@ -24,7 +24,6 @@ use polkadot_parachain_primitives::primitives::{ use polkadot_primitives::BlockNumber as RelayBlockNumber; use sp_runtime::traits::{Get, Hash}; -use sp_std::prelude::*; use xcm::{latest::prelude::*, VersionedXcm}; pub use pallet::*; diff --git a/prdoc/pr_3286.prdoc b/prdoc/pr_3286.prdoc index 6ec3f6552a4a7369d1881e621e3070460d0b344f..3433f63f30295a57d8889eea12aedf731f8471cf 100644 --- a/prdoc/pr_3286.prdoc +++ b/prdoc/pr_3286.prdoc @@ -14,3 +14,4 @@ doc: crates: - name: pallet-assets + bump: patch diff --git a/prdoc/pr_4563.prdoc b/prdoc/pr_4563.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..3780eee5898b555f44f9d7c7d6670e2c06ff4702 --- /dev/null +++ b/prdoc/pr_4563.prdoc @@ -0,0 +1,12 @@ +title: Try State Hook for Bounties. + +doc: + - audience: Runtime User + description: | + Invariants for storage items in the bounties pallet. Enforces the following Invariants: + 1.`BountyCount` should be greater or equals to the length of the number of items in `Bounties`. + 2.`BountyCount` should be greater or equals to the length of the number of items in `BountyDescriptions`. + 3. Number of items in `Bounties` should be the same as `BountyDescriptions` length. +crates: +- name: pallet-bounties + bump: minor diff --git a/prdoc/pr_4566.prdoc b/prdoc/pr_4566.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..ea2979bb363aa2c26313f4e0b2d1108e99437492 --- /dev/null +++ b/prdoc/pr_4566.prdoc @@ -0,0 +1,23 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: "[pallet_contracts] Add support for transient storage in contracts host functions" + +doc: + - audience: Runtime User + description: | + This PR implements transient storage, which behaves identically to regular storage + but is kept only in memory and discarded after every transaction. + This functionality is similar to the `TSTORE` and `TLOAD` operations used in Ethereum. + The following new host functions have been introduced: `get_transient_storage`, + `set_transient_storage`, `take_transient_storage`, `clear_transient_storage` and + `contains_transient_storage`. + These functions are declared as unstable and thus are not activated. + +crates: + - name: pallet-contracts + bump: major + - name: pallet-contracts-uapi + bump: major + - name: contracts-rococo-runtime + bump: minor diff --git a/prdoc/pr_4640.prdoc b/prdoc/pr_4640.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..52abc8f4baa5dbefe370ea3ed7b5992afa376924 --- /dev/null +++ b/prdoc/pr_4640.prdoc @@ -0,0 +1,20 @@ +title: Introduce tool for validating PoVs locally + +doc: + - audience: + - Runtime Dev + - Node Dev + description: | + Introduces the `cumulus-pov-validator` for running PoVs locally. This can be helpful for debugging issues that are + only happening when the PoV gets validated on the relay chain or for example to profile the validation code. + Besides that the `polkadot-parachain` was extended with the CLI flag `--export-pov-to-path` to let a collator export + all its build PoV's to the given directory. These PoV's can then be feed into the `cumulus-pov-validator`. + +crates: + - name: polkadot-parachain-bin + bump: minor + - name: cumulus-client-consensus-aura + bump: minor + - name: cumulus-pov-validator + bump: patch + validate: false diff --git a/prdoc/pr_4663.prdoc b/prdoc/pr_4663.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..74b1274828d5c9fb31014c37b39798600f6c25fa --- /dev/null +++ b/prdoc/pr_4663.prdoc @@ -0,0 +1,14 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Add elastic scaling MVP guide + +doc: + - audience: Node Operator + description: | + Adds a guide for parachains that want to use the experimental elastic scaling MVP. + Will be viewable at: https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/guides/enable_elastic_scaling_mvp/index.html + +crates: + - name: polkadot-parachain-bin + bump: none diff --git a/prdoc/pr_4751.prdoc b/prdoc/pr_4751.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..5a2c42209088039a3b570995121d661e620a9a2c --- /dev/null +++ b/prdoc/pr_4751.prdoc @@ -0,0 +1,22 @@ +title: "Use all parachain heads for BEEFY MMR extra data" + +doc: + - audience: Runtime Dev + description: | + Previously, the extra data in an MMR leaf nodes was only computed based on lease-based parachain heads. + This PR extends the extra data to include others, including on-demand parachain heads. + Currently, the number of heads is limited to the first 1024 heads sorted by para id. + +crates: + - name: polkadot-runtime-parachains + bump: minor + - name: rococo-runtime + bump: minor + - name: westend-runtime + bump: minor + - name: pallet-mmr + bump: major + - name: pallet-beefy-mmr + bump: minor + - name: polkadot-sdk + bump: minor diff --git a/prdoc/pr_4755.prdoc b/prdoc/pr_4755.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..1018446cb67e7e20a77ce1780c7157fdeed3db56 --- /dev/null +++ b/prdoc/pr_4755.prdoc @@ -0,0 +1,24 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Send PeerViewChange with high priority + +doc: + - audience: Node Dev + description: | + - orchestra updated to 0.4.0, which introduces support for prioritizing system messages. + - PeerViewChange sent with high priority and should be processed first in a queue. + - To count them in tests added tracker to TestSender and TestOverseer. It acts more like a smoke test though. + + +crates: + - name: polkadot-overseer + bump: minor + - name: polkadot-network-bridge + bump: patch + - name: polkadot-availability-distribution + bump: patch + - name: polkadot-test-malus + bump: patch + - name: polkadot-node-subsystem-test-helpers + bump: patch diff --git a/prdoc/pr_4848.prdoc b/prdoc/pr_4848.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..cbc0c8322d7722678922ef8ba53056aba7836319 --- /dev/null +++ b/prdoc/pr_4848.prdoc @@ -0,0 +1,14 @@ +title: Optimize logic for gossiping assignments + +doc: + - audience: Node Dev + description: | + Optimize the logic for gossiping assignments by obtaining the list of peer ids + from the topology instead of iterating through all connected validators, this + gives us a 15% to 20% reduction in cpu usage. + +crates: +- name: polkadot-approval-distribution + bump: minor +- name: polkadot-node-network-protocol + bump: minor \ No newline at end of file diff --git a/prdoc/pr_4930.prdoc b/prdoc/pr_4930.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..a7c9a302b11852815b6665370da72097074bedea --- /dev/null +++ b/prdoc/pr_4930.prdoc @@ -0,0 +1,15 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Add test macro to emulated chains + +doc: + - audience: Runtime Dev + description: | + This PR adds a portable test macro that can be used to test trapped assets can be + claimed in an emulated chain. + + +crates: +- name: emulated-integration-tests-common + bump: minor diff --git a/prdoc/pr_4935.prdoc b/prdoc/pr_4935.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..2b06899b63398353209eb38ad5410e24fc3e4f6d --- /dev/null +++ b/prdoc/pr_4935.prdoc @@ -0,0 +1,75 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: "Bridges V2 refactoring backport and `pallet_bridge_messages` simplifications" + +doc: + - audience: Runtime Dev + description: | + This introduces several simplifications to the pallet_bridge_messages::Config configuration. + Types like `BridgedChainId`, `MaxUnrewardedRelayerEntriesAtInboundLane`, `MaxUnconfirmedMessagesAtInboundLane`, `MaximalOutboundPayloadSize`, + `InboundRelayer`, `TargetHeaderChain`, and `SourceHeaderChain` were removed. + Now, you only need to provide specific bridging chain configurations for `ThisChain`, `BridgedChain`, and `BridgedHeaderChain`. + + If you previously specified implementations for the bp_runtime::Chain* traits, those will fit here exactly, for example: + ``` + type ThisChain = bp_bridge_hub_rococo::BridgeHubRococo; + type BridgedChain = bp_bridge_hub_westend::BridgeHubWestend; + type BridgedHeaderChain = pallet_bridge_parachains::ParachainHeaders< + Runtime, + BridgeParachainWestendInstance, + bp_bridge_hub_westend::BridgeHubWestend, + >; + ``` + +crates: + - name: pallet-bridge-messages + bump: major + - name: bridge-runtime-common + bump: major + - name: bp-header-chain + bump: major + - name: bp-runtime + bump: major + - name: bp-messages + bump: major + - name: bp-polkadot-core + bump: patch + - name: bp-bridge-hub-kusama + bump: minor + - name: bp-bridge-hub-polkadot + bump: minor + - name: bp-bridge-hub-rococo + bump: minor + - name: bp-bridge-hub-westend + bump: minor + - name: bp-kusama + bump: minor + - name: bp-polkadot + bump: minor + - name: bp-polkadot-bulletin + bump: minor + - name: bp-rococo + bump: minor + - name: bp-test-utils + bump: patch + - name: bp-westend + bump: minor + - name: bridge-hub-test-utils + bump: major + - name: pallet-bridge-grandpa + bump: patch + - name: pallet-bridge-parachains + bump: patch + - name: pallet-bridge-relayers + bump: patch + - name: pallet-xcm-bridge-hub + bump: patch + - name: asset-hub-rococo-runtime + bump: patch + - name: asset-hub-westend-runtime + bump: patch + - name: bridge-hub-rococo-runtime + bump: major + - name: bridge-hub-westend-runtime + bump: major diff --git a/prdoc/pr_4936.prdoc b/prdoc/pr_4936.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..f9b7ee506a7ac6eb09014943ec5ce47e427f34e0 --- /dev/null +++ b/prdoc/pr_4936.prdoc @@ -0,0 +1,13 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: "Balances Pallet: Emit events when TI is updated in currency impl" + +doc: + - audience: Runtime Dev + description: | + Previously, in the Currency impl, the implementation of pallet_balances was not emitting any instances of Issued and Rescinded events, even though the Fungible equivalent was. This PR adds the Issued and Rescinded events in appropriate places in impl_currency along with tests. + +crates: +- name: pallet-balances + bump: patch diff --git a/prdoc/pr_4959.prdoc b/prdoc/pr_4959.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..4891a97917956b2326871fda30e74e8a1a15b8b3 --- /dev/null +++ b/prdoc/pr_4959.prdoc @@ -0,0 +1,45 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: relax XcmFeeToAccount trait bound on AccountId + +doc: + - audience: Runtime Dev + description: | + This PR relaxes the trait bound on AccountId for the XcmFeeToAccount struct by introducing a new struct called `SendXcmFeeToAccount`. + The old one (`XcmFeeToAccount`) will be deprecated at January 2025. + +crates: + - name: staging-xcm-builder + bump: minor + - name: staging-xcm + bump: minor + - name: pallet-xcm + bump: minor + - name: asset-hub-rococo-runtime + bump: minor + - name: asset-hub-westend-runtime + bump: minor + - name: bridge-hub-rococo-runtime + bump: minor + - name: bridge-hub-westend-runtime + bump: minor + - name: collectives-westend-runtime + bump: minor + - name: contracts-rococo-runtime + bump: minor + - name: coretime-rococo-runtime + bump: minor + - name: coretime-westend-runtime + bump: minor + - name: people-rococo-runtime + bump: minor + - name: people-westend-runtime + bump: minor + - name: penpal-runtime + bump: minor + - name: rococo-runtime + bump: minor + - name: westend-runtime + bump: minor + diff --git a/prdoc/pr_4972.prdoc b/prdoc/pr_4972.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..dd9f1b531aad1a8a36fbc4b2ba19469ceccdb898 --- /dev/null +++ b/prdoc/pr_4972.prdoc @@ -0,0 +1,14 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: "Remove `pallet::getter` usage from pallet-session" + +doc: + - audience: Runtime Dev + description: | + This PR removes the `pallet::getter`s from `pallet-session`. + The syntax `StorageItem::::get()` should be used instead. + +crates: + - name: pallet-session + bump: minor diff --git a/prdoc/pr_4976.prdoc b/prdoc/pr_4976.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..72b7b92bc47f711a564046349e0b351b08884287 --- /dev/null +++ b/prdoc/pr_4976.prdoc @@ -0,0 +1,15 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Add pub to xcm::v4::PalletInfo + +doc: + - audience: Runtime Dev + description: | + Forgot to make v4 PalletInfo fields public. Without them we cannot make use of the struct. + +crates: + - name: staging-xcm + bump: patch + validate: false + diff --git a/prdoc/pr_4997.prdoc b/prdoc/pr_4997.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..25620a7e63ea817e9009cf557748deb63d921f2e --- /dev/null +++ b/prdoc/pr_4997.prdoc @@ -0,0 +1,20 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: Do not crash on block gap in displaced_leaves_after_finalizing + +doc: + - audience: + - Node Operator + - Node Dev + description: | + After recent changes, crashes where occuring when calculating displaced branches after a block was finalized. + The reason are block gaps in the finalized chain. When encountering unknown blocks, the node was panicking. + This PR introduces changes to tolerate unknown blocks. Leafs that are separated by a gap from the to-be-finalized + block are not marked as displaced. + +crates: +- name: sc-client-db + bump: none +- name: sp-blockchain + bump: patch diff --git a/prdoc/pr_5011.prdoc b/prdoc/pr_5011.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..cb827bae6c591155087ad9a96095c1f3d716844f --- /dev/null +++ b/prdoc/pr_5011.prdoc @@ -0,0 +1,29 @@ +# Schema: Polkadot SDK PRDoc Schema (prdoc) v1.0.0 +# See doc at https://raw.githubusercontent.com/paritytech/polkadot-sdk/master/prdoc/schema_user.json + +title: "Use `BadOrigin` from `sp_runtime`" + +doc: + - audience: Runtime Dev + description: | + This PR refactor usages of deprecated `frame_support::error::BadOrigin` to `sp_runtime::traits::BadOrigin` + +crates: +- name: pallet-collective-content + bump: patch +- name: polkadot-runtime-common + bump: patch +- name: polkadot-runtime-parachains + bump: patch +- name: pallet-alliance + bump: patch +- name: pallet-contracts + bump: patch +- name: pallet-democracy + bump: patch +- name: pallet-nomination-pools + bump: patch +- name: pallet-ranked-collective + bump: patch +- name: pallet-utility + bump: patch diff --git a/prdoc/pr_5040.prdoc b/prdoc/pr_5040.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..62b175c1d64806fc2a916811af8cf3845eb8051a --- /dev/null +++ b/prdoc/pr_5040.prdoc @@ -0,0 +1,11 @@ +title: Update libp2p-websocket to v0.42.2 + +doc: + - audience: Node Operator + description: | + Fixes a panic coming from the libp2p-websocket which stops the node. + This fix ensures that polling multiple time after error results in an error instead of panics. + +crates: +- name: sc-network + bump: minor diff --git a/prdoc/schema_user.json b/prdoc/schema_user.json index e6c0468aaf8517956501324dc4ba087b444bb424..5f7d460a5cc080b1feb1f744b05e07addbb8cd51 100644 --- a/prdoc/schema_user.json +++ b/prdoc/schema_user.json @@ -148,7 +148,8 @@ } }, "required": [ - "name" + "name", + "bump" ] }, "migration_db": { diff --git a/substrate/bin/node/bench/src/import.rs b/substrate/bin/node/bench/src/import.rs index e340869dea0281092b41c94d107e65e4831c7e95..0b972650ef5a0fee317f040513bbb54ceb09bdd5 100644 --- a/substrate/bin/node/bench/src/import.rs +++ b/substrate/bin/node/bench/src/import.rs @@ -121,22 +121,23 @@ impl core::Benchmark for ImportBenchmark { .inspect_state(|| { match self.block_type { BlockType::RandomTransfersKeepAlive => { - // should be 8 per signed extrinsic + 1 per unsigned + // should be 9 per signed extrinsic + 1 per unsigned // we have 2 unsigned (timestamp and glutton bloat) while the rest are // signed in the block. - // those 8 events per signed are: + // those 9 events per signed are: // - transaction paid for the transaction payment // - withdraw (Balances::Withdraw) for charging the transaction fee // - new account (System::NewAccount) as we always transfer fund to // non-existent account // - endowed (Balances::Endowed) for this new account + // - issued (Balances::Issued) as total issuance is increased // - successful transfer (Event::Transfer) for this transfer operation // - 2x deposit (Balances::Deposit and Treasury::Deposit) for depositing // the transaction fee into the treasury // - extrinsic success assert_eq!( kitchensink_runtime::System::events().len(), - (self.block.extrinsics.len() - 2) * 8 + 2, + (self.block.extrinsics.len() - 2) * 9 + 2, ); }, BlockType::Noop => { diff --git a/substrate/bin/node/cli/Cargo.toml b/substrate/bin/node/cli/Cargo.toml index ab665f0792a46814343bb39f7497ae925bbe8e68..1856487ac9cac88ef3a812cbe89bd9341d232ca2 100644 --- a/substrate/bin/node/cli/Cargo.toml +++ b/substrate/bin/node/cli/Cargo.toml @@ -71,6 +71,7 @@ wait-timeout = { workspace = true } wat = { workspace = true } serde_json = { workspace = true, default-features = true } scale-info = { features = ["derive", "serde"], workspace = true, default-features = true } +pretty_assertions.workspace = true # These testing-only dependencies are not exported by the Polkadot-SDK crate: node-testing = { workspace = true } diff --git a/substrate/bin/node/cli/tests/basic.rs b/substrate/bin/node/cli/tests/basic.rs index b1f737ce399b32de652abd8c26bad1811727fcff..0a2e3fd25047f39c51ca75c59a0791fe5e040a56 100644 --- a/substrate/bin/node/cli/tests/basic.rs +++ b/substrate/bin/node/cli/tests/basic.rs @@ -35,6 +35,7 @@ use kitchensink_runtime::{ }; use node_primitives::{Balance, Hash}; use node_testing::keyring::*; +use pretty_assertions::assert_eq; use wat; pub mod common; @@ -380,6 +381,13 @@ fn full_native_block_import_works() { }), topics: vec![], }, + EventRecord { + phase: Phase::ApplyExtrinsic(1), + event: RuntimeEvent::Balances(pallet_balances::Event::Rescinded { + amount: fees * 2 / 10, + }), + topics: vec![], + }, EventRecord { phase: Phase::ApplyExtrinsic(1), event: RuntimeEvent::TransactionPayment( @@ -465,6 +473,13 @@ fn full_native_block_import_works() { }), topics: vec![], }, + EventRecord { + phase: Phase::ApplyExtrinsic(1), + event: RuntimeEvent::Balances(pallet_balances::Event::Rescinded { + amount: fees - fees * 8 / 10, + }), + topics: vec![], + }, EventRecord { phase: Phase::ApplyExtrinsic(1), event: RuntimeEvent::TransactionPayment( @@ -515,6 +530,13 @@ fn full_native_block_import_works() { }), topics: vec![], }, + EventRecord { + phase: Phase::ApplyExtrinsic(2), + event: RuntimeEvent::Balances(pallet_balances::Event::Rescinded { + amount: fees - fees * 8 / 10, + }), + topics: vec![], + }, EventRecord { phase: Phase::ApplyExtrinsic(2), event: RuntimeEvent::TransactionPayment( diff --git a/substrate/bin/node/runtime/src/assets_api.rs b/substrate/bin/node/runtime/src/assets_api.rs index 38ec56507113f561721887689a5f4540121e2403..98187e7391f3e2d316c53da6b52ebdaea97f85fc 100644 --- a/substrate/bin/node/runtime/src/assets_api.rs +++ b/substrate/bin/node/runtime/src/assets_api.rs @@ -20,8 +20,8 @@ use polkadot_sdk::*; +use alloc::vec::Vec; use codec::Codec; -use sp_std::vec::Vec; sp_api::decl_runtime_apis! { pub trait AssetsApi diff --git a/substrate/bin/node/runtime/src/impls.rs b/substrate/bin/node/runtime/src/impls.rs index dbe562857c99fcdd4730edd0aa5d985ab2e6dd51..6c121fad624b2c6be3b6a22813b6d56f57952526 100644 --- a/substrate/bin/node/runtime/src/impls.rs +++ b/substrate/bin/node/runtime/src/impls.rs @@ -17,8 +17,7 @@ //! Some configurable implementations as associated type for the substrate runtime. -use polkadot_sdk::*; - +use alloc::boxed::Box; use frame_support::{ pallet_prelude::*, traits::{ @@ -29,7 +28,7 @@ use frame_support::{ use pallet_alliance::{IdentityVerifier, ProposalIndex, ProposalProvider}; use pallet_asset_tx_payment::HandleCredit; use pallet_identity::legacy::IdentityField; -use sp_std::prelude::*; +use polkadot_sdk::*; use crate::{ AccountId, AllianceCollective, AllianceMotion, Assets, Authorship, Balances, Hash, diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index fc87fea57ba2e8e667c36d5808e793630373076f..78c7bba64579a80d750c2d20ebe96dba2de7536c 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -22,8 +22,11 @@ // `construct_runtime!` does a lot of recursion and requires us to increase the limits. #![recursion_limit = "1024"] +extern crate alloc; + use polkadot_sdk::*; +use alloc::{vec, vec::Vec}; use codec::{Decode, Encode, MaxEncodedLen}; use frame_election_provider_support::{ bounds::{ElectionBounds, ElectionBoundsBuilder}, @@ -100,7 +103,6 @@ use sp_runtime::{ ApplyExtrinsicResult, FixedPointNumber, FixedU128, Perbill, Percent, Permill, Perquintill, RuntimeDebug, }; -use sp_std::prelude::*; #[cfg(any(feature = "std", test))] use sp_version::NativeVersion; use sp_version::RuntimeVersion; @@ -1371,6 +1373,7 @@ impl pallet_contracts::Config for Runtime { type UploadOrigin = EnsureSigned; type InstantiateOrigin = EnsureSigned; type MaxDebugBufferLen = ConstU32<{ 2 * 1024 * 1024 }>; + type MaxTransientStorageSize = ConstU32<{ 1 * 1024 * 1024 }>; type RuntimeHoldReason = RuntimeHoldReason; #[cfg(not(feature = "runtime-benchmarks"))] type Migrations = (); @@ -1602,6 +1605,8 @@ impl pallet_mmr::Config for Runtime { type OnNewRoot = pallet_beefy_mmr::DepositBeefyDigest; type BlockHashProvider = pallet_mmr::DefaultBlockHashProvider; type WeightInfo = (); + #[cfg(feature = "runtime-benchmarks")] + type BenchmarkHelper = (); } parameter_types! { @@ -2660,7 +2665,7 @@ impl_runtime_apis! { Runtime::metadata_at_version(version) } - fn metadata_versions() -> sp_std::vec::Vec { + fn metadata_versions() -> alloc::vec::Vec { Runtime::metadata_versions() } } diff --git a/substrate/client/consensus/beefy/src/communication/peers.rs b/substrate/client/consensus/beefy/src/communication/peers.rs index 2d801aceaa8a76bf1c31820493bbd20b4f93f8da..929cc0c650b3e26e90016512042d620cc40c6408 100644 --- a/substrate/client/consensus/beefy/src/communication/peers.rs +++ b/substrate/client/consensus/beefy/src/communication/peers.rs @@ -75,6 +75,11 @@ impl KnownPeers { pub fn contains(&self, peer: &PeerId) -> bool { self.live.contains_key(peer) } + + /// Number of peers in the set. + pub fn len(&self) -> usize { + self.live.len() + } } #[cfg(test)] diff --git a/substrate/client/consensus/beefy/src/communication/request_response/outgoing_requests_engine.rs b/substrate/client/consensus/beefy/src/communication/request_response/outgoing_requests_engine.rs index e127e5a895905b212fda73b109714618b76367d9..95ecf35557a5189fae4cc117e71126d8c8076536 100644 --- a/substrate/client/consensus/beefy/src/communication/request_response/outgoing_requests_engine.rs +++ b/substrate/client/consensus/beefy/src/communication/request_response/outgoing_requests_engine.rs @@ -249,9 +249,16 @@ impl OnDemandJustificationsEngine OnDemandJustificationsEngine, + number: u64, + parent_hash: H256, + extrinsics_root: H256, + best: bool, + ) -> H256 { + use sp_runtime::testing::Digest; + + let digest = Digest::default(); + let header = + Header { number, parent_hash, state_root: Default::default(), digest, extrinsics_root }; + + let mut op = backend.begin_operation().unwrap(); + + op.set_block_data( + header.clone(), + Some(vec![]), + None, + None, + if best { NewBlockState::Best } else { NewBlockState::Normal }, + ) + .unwrap(); + + backend.commit_operation(op).unwrap(); + + header.hash() + } + pub fn insert_header_no_head( backend: &Backend, number: u64, @@ -3112,6 +3141,123 @@ pub(crate) mod tests { } } + #[test] + fn displaced_leaves_after_finalizing_works_with_disconnect() { + // In this test we will create a situation that can typically happen after warp sync. + // The situation looks like this: + // g -> -> a3 -> a4 + // Basically there is a gap of unimported blocks at some point in the chain. + let backend = Backend::::new_test(1000, 100); + let blockchain = backend.blockchain(); + let genesis_number = 0; + let genesis_hash = + insert_header(&backend, genesis_number, Default::default(), None, Default::default()); + + let a3_number = 3; + let a3_hash = insert_disconnected_header( + &backend, + a3_number, + H256::from([200; 32]), + H256::from([1; 32]), + true, + ); + + let a4_number = 4; + let a4_hash = + insert_disconnected_header(&backend, a4_number, a3_hash, H256::from([2; 32]), true); + { + let displaced = + blockchain.displaced_leaves_after_finalizing(a3_hash, a3_number).unwrap(); + assert_eq!(blockchain.leaves().unwrap(), vec![a4_hash, genesis_hash]); + assert_eq!(displaced.displaced_leaves, vec![]); + assert_eq!(displaced.displaced_blocks, vec![]); + } + + { + let displaced = + blockchain.displaced_leaves_after_finalizing(a4_hash, a4_number).unwrap(); + assert_eq!(blockchain.leaves().unwrap(), vec![a4_hash, genesis_hash]); + assert_eq!(displaced.displaced_leaves, vec![]); + assert_eq!(displaced.displaced_blocks, vec![]); + } + + // Import block a1 which has the genesis block as parent. + // g -> a1 -> -> a3(f) -> a4 + let a1_number = 1; + let a1_hash = insert_disconnected_header( + &backend, + a1_number, + genesis_hash, + H256::from([123; 32]), + false, + ); + { + let displaced = + blockchain.displaced_leaves_after_finalizing(a3_hash, a3_number).unwrap(); + assert_eq!(blockchain.leaves().unwrap(), vec![a4_hash, a1_hash]); + assert_eq!(displaced.displaced_leaves, vec![]); + assert_eq!(displaced.displaced_blocks, vec![]); + } + + // Import block b1 which has the genesis block as parent. + // g -> a1 -> -> a3(f) -> a4 + // \-> b1 + let b1_number = 1; + let b1_hash = insert_disconnected_header( + &backend, + b1_number, + genesis_hash, + H256::from([124; 32]), + false, + ); + { + let displaced = + blockchain.displaced_leaves_after_finalizing(a3_hash, a3_number).unwrap(); + assert_eq!(blockchain.leaves().unwrap(), vec![a4_hash, a1_hash, b1_hash]); + assert_eq!(displaced.displaced_leaves, vec![]); + assert_eq!(displaced.displaced_blocks, vec![]); + } + + // If branch of b blocks is higher in number than a branch, we + // should still not prune disconnected leafs. + // g -> a1 -> -> a3(f) -> a4 + // \-> b1 -> b2 ----------> b3 ----> b4 -> b5 + let b2_number = 2; + let b2_hash = + insert_disconnected_header(&backend, b2_number, b1_hash, H256::from([40; 32]), false); + let b3_number = 3; + let b3_hash = + insert_disconnected_header(&backend, b3_number, b2_hash, H256::from([41; 32]), false); + let b4_number = 4; + let b4_hash = + insert_disconnected_header(&backend, b4_number, b3_hash, H256::from([42; 32]), false); + let b5_number = 5; + let b5_hash = + insert_disconnected_header(&backend, b5_number, b4_hash, H256::from([43; 32]), false); + { + let displaced = + blockchain.displaced_leaves_after_finalizing(a3_hash, a3_number).unwrap(); + assert_eq!(blockchain.leaves().unwrap(), vec![b5_hash, a4_hash, a1_hash]); + assert_eq!(displaced.displaced_leaves, vec![]); + assert_eq!(displaced.displaced_blocks, vec![]); + } + + // Even though there is a disconnect, diplace should still detect + // branches above the block gap. + // /-> c4 + // g -> a1 -> -> a3 -> a4(f) + // \-> b1 -> b2 ----------> b3 -> b4 -> b5 + let c4_number = 4; + let c4_hash = + insert_disconnected_header(&backend, c4_number, a3_hash, H256::from([44; 32]), false); + { + let displaced = + blockchain.displaced_leaves_after_finalizing(a4_hash, a4_number).unwrap(); + assert_eq!(blockchain.leaves().unwrap(), vec![b5_hash, a4_hash, c4_hash, a1_hash]); + assert_eq!(displaced.displaced_leaves, vec![(c4_number, c4_hash)]); + assert_eq!(displaced.displaced_blocks, vec![c4_hash]); + } + } #[test] fn displaced_leaves_after_finalizing_works() { let backend = Backend::::new_test(1000, 100); @@ -3156,6 +3302,15 @@ pub(crate) mod tests { assert_eq!(displaced_a3.displaced_leaves, vec![]); assert_eq!(displaced_a3.displaced_blocks, vec![]); } + { + // Finalized block is above leaves and not imported yet. + // We will not be able to make a connection, + // nothing can be marked as displaced. + let displaced = + blockchain.displaced_leaves_after_finalizing(H256::from([57; 32]), 10).unwrap(); + assert_eq!(displaced.displaced_leaves, vec![]); + assert_eq!(displaced.displaced_blocks, vec![]); + } // fork from genesis: 2 prong. let b1_number = 1; diff --git a/substrate/client/executor/runtime-test/Cargo.toml b/substrate/client/executor/runtime-test/Cargo.toml index 5f5e7eb46d623782916e55637dfd93e892cab6fe..d132f47ff877f3c05580326e832a72c34676f7da 100644 --- a/substrate/client/executor/runtime-test/Cargo.toml +++ b/substrate/client/executor/runtime-test/Cargo.toml @@ -20,7 +20,6 @@ sp-core = { workspace = true } sp-io = { features = ["improved_panic_error_reporting"], workspace = true } sp-runtime = { workspace = true } sp-runtime-interface = { workspace = true } -sp-std = { workspace = true } [build-dependencies] substrate-wasm-builder = { optional = true, workspace = true, default-features = true } @@ -32,6 +31,5 @@ std = [ "sp-io/std", "sp-runtime-interface/std", "sp-runtime/std", - "sp-std/std", "substrate-wasm-builder", ] diff --git a/substrate/client/executor/runtime-test/src/lib.rs b/substrate/client/executor/runtime-test/src/lib.rs index 40683fbb664aadb6daf68595befcc68881322f05..08a5e39dff2cfdca2a2f3629caf939e836ef3144 100644 --- a/substrate/client/executor/runtime-test/src/lib.rs +++ b/substrate/client/executor/runtime-test/src/lib.rs @@ -32,7 +32,10 @@ pub fn wasm_binary_unwrap() -> &'static [u8] { } #[cfg(not(feature = "std"))] -use sp_std::{vec, vec::Vec}; +extern crate alloc; + +#[cfg(not(feature = "std"))] +use alloc::{vec, vec::Vec}; #[cfg(not(feature = "std"))] use sp_core::{ed25519, sr25519}; @@ -332,7 +335,7 @@ sp_core::wasm_export_functions! { let test_message = b"Hello invalid heap memory"; let ptr = (heap_base + offset) as *mut u8; - let message_slice = unsafe { sp_std::slice::from_raw_parts_mut(ptr, test_message.len()) }; + let message_slice = unsafe { alloc::slice::from_raw_parts_mut(ptr, test_message.len()) }; assert_ne!(test_message, message_slice); message_slice.copy_from_slice(test_message); diff --git a/substrate/client/network/src/litep2p/mod.rs b/substrate/client/network/src/litep2p/mod.rs index 824f62082cac7c593f74bac21cd66b1bf4fef11c..34ca5b716101ff4718fa6d17c0fe8d118f2ac420 100644 --- a/substrate/client/network/src/litep2p/mod.rs +++ b/substrate/client/network/src/litep2p/mod.rs @@ -851,6 +851,10 @@ impl NetworkBackend for Litep2pNetworkBac "`PUT_VALUE` for {key:?} ({query_id:?}) succeeded", ); + self.event_streams.send(Event::Dht( + DhtEvent::ValuePut(libp2p::kad::RecordKey::new(&key)) + )); + if let Some(ref metrics) = self.metrics { metrics .kademlia_query_duration diff --git a/substrate/client/network/src/litep2p/shim/request_response/mod.rs b/substrate/client/network/src/litep2p/shim/request_response/mod.rs index 82d01c01236f215a5123c34128f9b550e7abd4e9..a77acb464144f6b04ce1c8ad3b1b63ff6e535256 100644 --- a/substrate/client/network/src/litep2p/shim/request_response/mod.rs +++ b/substrate/client/network/src/litep2p/shim/request_response/mod.rs @@ -24,7 +24,7 @@ use crate::{ peer_store::PeerStoreProvider, request_responses::{IncomingRequest, OutgoingResponse}, service::{metrics::Metrics, traits::RequestResponseConfig as RequestResponseConfigT}, - IfDisconnected, ProtocolName, RequestFailure, + IfDisconnected, OutboundFailure, ProtocolName, RequestFailure, }; use futures::{channel::oneshot, future::BoxFuture, stream::FuturesUnordered, StreamExt}; @@ -369,10 +369,12 @@ impl RequestResponseProtocol { return }; - let error = match error { - RequestResponseError::NotConnected => Some(RequestFailure::NotConnected), - RequestResponseError::Rejected | RequestResponseError::Timeout => - Some(RequestFailure::Refused), + let status = match error { + RequestResponseError::NotConnected => + Some((RequestFailure::NotConnected, "not-connected")), + RequestResponseError::Rejected => Some((RequestFailure::Refused, "rejected")), + RequestResponseError::Timeout => + Some((RequestFailure::Network(OutboundFailure::Timeout), "timeout")), RequestResponseError::Canceled => { log::debug!( target: LOG_TARGET, @@ -387,7 +389,7 @@ impl RequestResponseProtocol { "{}: tried to send too large request to {peer:?} ({request_id:?})", self.protocol, ); - Some(RequestFailure::Refused) + Some((RequestFailure::Refused, "payload-too-large")) }, RequestResponseError::UnsupportedProtocol => match fallback_request { Some((request, protocol)) => match self.request_tx.get(&protocol) { @@ -426,15 +428,15 @@ impl RequestResponseProtocol { peer, ); - Some(RequestFailure::Refused) + Some((RequestFailure::Refused, "invalid-fallback-protocol")) }, }, - None => Some(RequestFailure::Refused), + None => Some((RequestFailure::Refused, "unsupported-protocol")), }, }; - if let Some(error) = error { - self.metrics.register_outbound_request_failure(error.to_string().as_ref()); + if let Some((error, reason)) = status { + self.metrics.register_outbound_request_failure(reason); let _ = tx.send(Err(error)); } } diff --git a/substrate/client/network/transactions/src/lib.rs b/substrate/client/network/transactions/src/lib.rs index 3384aab5149dcb5b6127d75e744f010db950b5d1..31ad0781035e5bd0662a617dcb31502048bdea81 100644 --- a/substrate/client/network/transactions/src/lib.rs +++ b/substrate/client/network/transactions/src/lib.rs @@ -368,7 +368,8 @@ where { self.on_transactions(peer, m); } else { - warn!(target: "sub-libp2p", "Failed to decode transactions list"); + warn!(target: "sub-libp2p", "Failed to decode transactions list from peer {peer}"); + self.network.report_peer(peer, rep::BAD_TRANSACTION); } }, } diff --git a/substrate/client/rpc-servers/src/lib.rs b/substrate/client/rpc-servers/src/lib.rs index 619498b333365ff1fa54672bd6ad94507fcd6d27..0bae16b113dffeee893a82922c5b5db34a8c5a6a 100644 --- a/substrate/client/rpc-servers/src/lib.rs +++ b/substrate/client/rpc-servers/src/lib.rs @@ -224,8 +224,9 @@ where ), }; - let rpc_middleware = - RpcServiceBuilder::new().option_layer(middleware_layer.clone()); + let rpc_middleware = RpcServiceBuilder::new() + .rpc_logger(1024) + .option_layer(middleware_layer.clone()); let mut svc = service_builder.set_rpc_middleware(rpc_middleware).build(methods, stop_handle); diff --git a/substrate/client/sysinfo/src/sysinfo.rs b/substrate/client/sysinfo/src/sysinfo.rs index 3fa583cf7aca1f6dab055e4d498982268f1be084..37b35fcb910327abef20968d4af973ecdd88412f 100644 --- a/substrate/client/sysinfo/src/sysinfo.rs +++ b/substrate/client/sysinfo/src/sysinfo.rs @@ -21,13 +21,13 @@ use crate::{ExecutionLimit, HwBench}; use sc_telemetry::SysInfo; use sp_core::{sr25519, Pair}; use sp_io::crypto::sr25519_verify; -use sp_std::{fmt, fmt::Formatter, prelude::*}; use derive_more::From; use rand::{seq::SliceRandom, Rng, RngCore}; use serde::{de::Visitor, Deserialize, Deserializer, Serialize, Serializer}; use std::{ - fmt::Display, + fmt, + fmt::{Display, Formatter}, fs::File, io::{Seek, SeekFrom, Write}, ops::{Deref, DerefMut}, diff --git a/substrate/frame/Cargo.toml b/substrate/frame/Cargo.toml index 594cb505cd60ff97b8247f4a9d284c3b3b82139f..41ece6c9a27fef834eac8468731b90b6f8ed5b9d 100644 --- a/substrate/frame/Cargo.toml +++ b/substrate/frame/Cargo.toml @@ -27,7 +27,6 @@ scale-info = { features = [ # primitive deps, used for developing FRAME pallets. sp-runtime = { workspace = true } -sp-std = { workspace = true } sp-io = { workspace = true } sp-core = { workspace = true } sp-arithmetic = { workspace = true } @@ -104,7 +103,6 @@ std = [ "sp-offchain?/std", "sp-runtime/std", "sp-session?/std", - "sp-std/std", "sp-storage/std", "sp-transaction-pool?/std", "sp-version?/std", diff --git a/substrate/frame/alliance/Cargo.toml b/substrate/frame/alliance/Cargo.toml index 7ad9961d9b89cfd28023e70934a2697cadaa6984..451b86b35ddef7fa96945888e9b885444171dc9d 100644 --- a/substrate/frame/alliance/Cargo.toml +++ b/substrate/frame/alliance/Cargo.toml @@ -22,7 +22,6 @@ log = { workspace = true } codec = { features = ["derive"], workspace = true } scale-info = { features = ["derive"], workspace = true } -sp-std = { workspace = true } sp-core = { workspace = true } sp-crypto-hashing = { optional = true, workspace = true } sp-io = { workspace = true } @@ -57,7 +56,6 @@ std = [ "sp-crypto-hashing?/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "array-bytes", diff --git a/substrate/frame/alliance/src/lib.rs b/substrate/frame/alliance/src/lib.rs index ed771c7226ea9d9c43a94b906722f5379e7c0174..be65f49e6e4ea406cc742f153009fb8d22ca4fd5 100644 --- a/substrate/frame/alliance/src/lib.rs +++ b/substrate/frame/alliance/src/lib.rs @@ -94,6 +94,9 @@ pub mod migration; mod types; pub mod weights; +extern crate alloc; + +use alloc::{boxed::Box, vec, vec::Vec}; use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; @@ -101,7 +104,6 @@ use sp_runtime::{ traits::{Dispatchable, Saturating, StaticLookup, Zero}, DispatchError, RuntimeDebug, }; -use sp_std::prelude::*; use frame_support::{ dispatch::{DispatchResult, DispatchResultWithPostInfo, GetDispatchInfo, PostDispatchInfo}, diff --git a/substrate/frame/alliance/src/tests.rs b/substrate/frame/alliance/src/tests.rs index edb515b8115a57eeac4fdade7ca4831e43ff17f9..ec31ebf6a47ae8eaf93025079069efe054dd02e8 100644 --- a/substrate/frame/alliance/src/tests.rs +++ b/substrate/frame/alliance/src/tests.rs @@ -17,8 +17,9 @@ //! Tests for the alliance pallet. -use frame_support::{assert_noop, assert_ok, error::BadOrigin}; +use frame_support::{assert_noop, assert_ok}; use frame_system::{EventRecord, Phase}; +use sp_runtime::traits::BadOrigin; use super::*; use crate::{self as alliance, mock::*}; diff --git a/substrate/frame/alliance/src/types.rs b/substrate/frame/alliance/src/types.rs index 149030b52c674a8007ea19f77ec1356fb44a49b3..75b949c19b3256d0276679662fb8b1fc8a81acc1 100644 --- a/substrate/frame/alliance/src/types.rs +++ b/substrate/frame/alliance/src/types.rs @@ -15,11 +15,11 @@ // See the License for the specific language governing permissions and // limitations under the License. +use alloc::vec::Vec; use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{traits::ConstU32, BoundedVec}; use scale_info::TypeInfo; use sp_runtime::RuntimeDebug; -use sp_std::prelude::*; /// A Multihash instance that only supports the basic functionality and no hashing. #[derive( diff --git a/substrate/frame/asset-conversion/Cargo.toml b/substrate/frame/asset-conversion/Cargo.toml index 27d86bf6710b0c343e72f8c0b01494020bb4b0d3..4e867ece1bd274c7d1ddf2596c8790d726ccf517 100644 --- a/substrate/frame/asset-conversion/Cargo.toml +++ b/substrate/frame/asset-conversion/Cargo.toml @@ -25,7 +25,6 @@ scale-info = { features = ["derive"], workspace = true } sp-api = { workspace = true } sp-core = { workspace = true } sp-io = { workspace = true } -sp-std = { workspace = true } sp-runtime = { workspace = true } sp-arithmetic = { workspace = true } @@ -51,7 +50,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/asset-conversion/ops/Cargo.toml b/substrate/frame/asset-conversion/ops/Cargo.toml index 0dc6cd5b1672ae02fcaf8b9a08fd51618bf981c5..97a676fde10d56e3a9e13e41c0ff5f89dd50a7ce 100644 --- a/substrate/frame/asset-conversion/ops/Cargo.toml +++ b/substrate/frame/asset-conversion/ops/Cargo.toml @@ -24,7 +24,6 @@ pallet-asset-conversion = { workspace = true } scale-info = { features = ["derive"], workspace = true } sp-core = { workspace = true } sp-io = { workspace = true } -sp-std = { workspace = true } sp-runtime = { workspace = true } sp-arithmetic = { workspace = true } @@ -50,7 +49,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/asset-conversion/ops/src/benchmarking.rs b/substrate/frame/asset-conversion/ops/src/benchmarking.rs index a7370f38bc4b0472c4baea94bffc0d26b3169efe..384e17c9f0aac59ade14dfb928ed9247afaa34a1 100644 --- a/substrate/frame/asset-conversion/ops/src/benchmarking.rs +++ b/substrate/frame/asset-conversion/ops/src/benchmarking.rs @@ -28,7 +28,6 @@ use frame_system::RawOrigin as SystemOrigin; use pallet_asset_conversion::{BenchmarkHelper, Pallet as AssetConversion}; use sp_core::Get; use sp_runtime::traits::One; -use sp_std::prelude::*; /// Provides a pair of amounts expected to serve as sufficient initial liquidity for a pool. fn valid_liquidity_amount(ed1: T::Balance, ed2: T::Balance) -> (T::Balance, T::Balance) diff --git a/substrate/frame/asset-conversion/ops/src/lib.rs b/substrate/frame/asset-conversion/ops/src/lib.rs index a655a9cb44525fe58bf07f283c0cf3cdf2c9fd42..58c15b47a3eb347c60042e522263507de9017e3b 100644 --- a/substrate/frame/asset-conversion/ops/src/lib.rs +++ b/substrate/frame/asset-conversion/ops/src/lib.rs @@ -42,6 +42,9 @@ pub mod weights; pub use pallet::*; pub use weights::WeightInfo; +extern crate alloc; + +use alloc::boxed::Box; use frame_support::traits::{ fungible::{Inspect as FungibleInspect, Mutate as FungibleMutate}, fungibles::{roles::ResetTeam, Inspect, Mutate, Refund}, @@ -50,7 +53,6 @@ use frame_support::traits::{ }; use pallet_asset_conversion::{PoolLocator, Pools}; use sp_runtime::traits::{TryConvert, Zero}; -use sp_std::boxed::Box; #[frame_support::pallet] pub mod pallet { diff --git a/substrate/frame/asset-conversion/ops/src/mock.rs b/substrate/frame/asset-conversion/ops/src/mock.rs index 91c18b2e79494eb39812c0aca9f33dfdf6710d60..5c05faa6aa88dba9bb5c55b58cd5a1de7054dac1 100644 --- a/substrate/frame/asset-conversion/ops/src/mock.rs +++ b/substrate/frame/asset-conversion/ops/src/mock.rs @@ -17,7 +17,6 @@ //! Test environment for Asset Conversion Ops pallet. -use super::*; use crate as pallet_asset_conversion_ops; use core::default::Default; use frame_support::{ diff --git a/substrate/frame/asset-conversion/src/benchmarking.rs b/substrate/frame/asset-conversion/src/benchmarking.rs index c5f68476b1d0a620425719877843b9a276a9f08e..b003fe482881dd27996d8f9392e66aab46c5b5a2 100644 --- a/substrate/frame/asset-conversion/src/benchmarking.rs +++ b/substrate/frame/asset-conversion/src/benchmarking.rs @@ -19,6 +19,8 @@ use super::*; use crate::Pallet as AssetConversion; +use alloc::vec; +use core::marker::PhantomData; use frame_benchmarking::{v2::*, whitelisted_caller}; use frame_support::{ assert_ok, @@ -29,7 +31,6 @@ use frame_support::{ }; use frame_system::RawOrigin as SystemOrigin; use sp_core::Get; -use sp_std::{marker::PhantomData, prelude::*}; /// Benchmark Helper pub trait BenchmarkHelper { diff --git a/substrate/frame/asset-conversion/src/lib.rs b/substrate/frame/asset-conversion/src/lib.rs index 62acb693efb1c1e36bf22ad0530649f796a0d5a7..a9dc30375e5a89672cda919d0ff75469f9c7bf4d 100644 --- a/substrate/frame/asset-conversion/src/lib.rs +++ b/substrate/frame/asset-conversion/src/lib.rs @@ -70,6 +70,9 @@ pub use swap::*; pub use types::*; pub use weights::WeightInfo; +extern crate alloc; + +use alloc::{boxed::Box, collections::btree_set::BTreeSet, vec::Vec}; use codec::Codec; use frame_support::{ storage::{with_storage_layer, with_transaction}, @@ -93,7 +96,6 @@ use sp_runtime::{ }, DispatchError, Saturating, TokenError, TransactionOutcome, }; -use sp_std::{boxed::Box, collections::btree_set::BTreeSet, vec::Vec}; #[frame_support::pallet] pub mod pallet { diff --git a/substrate/frame/asset-rate/Cargo.toml b/substrate/frame/asset-rate/Cargo.toml index 96c87020684fbf195b8d2cac1976c4884ea6d7cc..4aeb6a39e8241b0322bc1df82810c2c2c5afba01 100644 --- a/substrate/frame/asset-rate/Cargo.toml +++ b/substrate/frame/asset-rate/Cargo.toml @@ -23,7 +23,6 @@ frame-benchmarking = { optional = true, workspace = true } frame-support = { workspace = true } frame-system = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } sp-core = { optional = true, workspace = true } [dev-dependencies] @@ -43,7 +42,6 @@ std = [ "sp-core?/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/asset-rate/src/lib.rs b/substrate/frame/asset-rate/src/lib.rs index 69f8267a4f25fe2fa82113eb6d9673b05b4ab6aa..cfb013a73f5e802f9403e7a12c4aba1e3c70e8c6 100644 --- a/substrate/frame/asset-rate/src/lib.rs +++ b/substrate/frame/asset-rate/src/lib.rs @@ -59,6 +59,9 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + +use alloc::boxed::Box; use frame_support::traits::{ fungible::Inspect, tokens::{ConversionFromAssetBalance, ConversionToAssetBalance}, @@ -67,7 +70,6 @@ use sp_runtime::{ traits::{CheckedDiv, Zero}, FixedPointNumber, FixedU128, }; -use sp_std::boxed::Box; pub use pallet::*; pub use weights::WeightInfo; diff --git a/substrate/frame/assets/Cargo.toml b/substrate/frame/assets/Cargo.toml index d0b5dc777898898fa1e71b259ea018be11de8552..802b8b9f39d80d34a501db3fe3859afc0fb4d799 100644 --- a/substrate/frame/assets/Cargo.toml +++ b/substrate/frame/assets/Cargo.toml @@ -20,7 +20,6 @@ codec = { workspace = true } impl-trait-for-tuples = "0.2.2" log = { workspace = true } scale-info = { features = ["derive"], workspace = true } -sp-std = { workspace = true } # Needed for various traits. In our case, `OnFinalize`. sp-runtime = { workspace = true } # Needed for type-safe access to storage DB. @@ -48,7 +47,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/assets/src/benchmarking.rs b/substrate/frame/assets/src/benchmarking.rs index 1b65bb953d77c0f4f75b14d74b1c84fefecf81aa..97cc04174a0c63d630ddfe0b2ebf669c85af56c2 100644 --- a/substrate/frame/assets/src/benchmarking.rs +++ b/substrate/frame/assets/src/benchmarking.rs @@ -20,13 +20,13 @@ #![cfg(feature = "runtime-benchmarks")] use super::*; +use alloc::vec; use frame_benchmarking::v1::{ account, benchmarks_instance_pallet, whitelist_account, whitelisted_caller, BenchmarkError, }; use frame_support::traits::{EnsureOrigin, Get, UnfilteredDispatchable}; use frame_system::RawOrigin as SystemOrigin; use sp_runtime::traits::Bounded; -use sp_std::prelude::*; use crate::Pallet as Assets; @@ -76,7 +76,7 @@ fn swap_is_sufficient, I: 'static>(s: &mut bool) { let asset_id = default_asset_id::(); Asset::::mutate(&asset_id.into(), |maybe_a| { if let Some(ref mut a) = maybe_a { - sp_std::mem::swap(s, &mut a.is_sufficient) + core::mem::swap(s, &mut a.is_sufficient) } }); } diff --git a/substrate/frame/assets/src/functions.rs b/substrate/frame/assets/src/functions.rs index 1e4a9522759c35b868447c8a0960643d468e4c71..c218c4ddc952cc4f6ef3a7be652e7000660c1150 100644 --- a/substrate/frame/assets/src/functions.rs +++ b/substrate/frame/assets/src/functions.rs @@ -18,6 +18,7 @@ //! Functions for the Assets pallet. use super::*; +use alloc::vec; use frame_support::{defensive, traits::Get, BoundedVec}; #[must_use] @@ -35,20 +36,20 @@ impl, I: 'static> Pallet { /// Return the extra "sid-car" data for `id`/`who`, or `None` if the account doesn't exist. pub fn adjust_extra( id: T::AssetId, - who: impl sp_std::borrow::Borrow, + who: impl core::borrow::Borrow, ) -> Option> { ExtraMutator::maybe_new(id, who) } /// Get the asset `id` balance of `who`, or zero if the asset-account doesn't exist. - pub fn balance(id: T::AssetId, who: impl sp_std::borrow::Borrow) -> T::Balance { + pub fn balance(id: T::AssetId, who: impl core::borrow::Borrow) -> T::Balance { Self::maybe_balance(id, who).unwrap_or_default() } /// Get the asset `id` balance of `who` if the asset-account exists. pub fn maybe_balance( id: T::AssetId, - who: impl sp_std::borrow::Borrow, + who: impl core::borrow::Borrow, ) -> Option { Account::::get(id, who.borrow()).map(|a| a.balance) } diff --git a/substrate/frame/assets/src/impl_fungibles.rs b/substrate/frame/assets/src/impl_fungibles.rs index 30122f6d788ff868b6f077f3e0c4e7cd3b26915f..578fa08c4e63ed8cc7dfedea21608228e03c6415 100644 --- a/substrate/frame/assets/src/impl_fungibles.rs +++ b/substrate/frame/assets/src/impl_fungibles.rs @@ -17,6 +17,7 @@ //! Implementations for fungibles trait. +use alloc::vec::Vec; use frame_support::{ defensive, traits::tokens::{ diff --git a/substrate/frame/assets/src/lib.rs b/substrate/frame/assets/src/lib.rs index 6dbce717a8e8db6cd09af424d26b0f5557b8c650..b9b5b2388dfbe270508b713c315e8a029a27d92f 100644 --- a/substrate/frame/assets/src/lib.rs +++ b/substrate/frame/assets/src/lib.rs @@ -167,13 +167,15 @@ mod impl_stored_map; mod types; pub use types::*; +extern crate alloc; + use scale_info::TypeInfo; use sp_runtime::{ traits::{AtLeast32BitUnsigned, CheckedAdd, CheckedSub, Saturating, StaticLookup, Zero}, ArithmeticError, DispatchError, TokenError, }; -use sp_std::prelude::*; +use alloc::vec::Vec; use core::marker::PhantomData; use frame_support::{ dispatch::DispatchResult, diff --git a/substrate/frame/atomic-swap/Cargo.toml b/substrate/frame/atomic-swap/Cargo.toml index 7e2f5fc74ab22cebf835c1924478067f8a2abc3b..033100630129697bbb0d0d2ae0179fbb6d35ea7b 100644 --- a/substrate/frame/atomic-swap/Cargo.toml +++ b/substrate/frame/atomic-swap/Cargo.toml @@ -23,7 +23,6 @@ frame-system = { workspace = true } sp-core = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] pallet-balances = { workspace = true, default-features = true } @@ -39,7 +38,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] try-runtime = [ "frame-support/try-runtime", diff --git a/substrate/frame/atomic-swap/src/lib.rs b/substrate/frame/atomic-swap/src/lib.rs index dc0300dc1a5c95d2654dfa5a210e6efab26125f6..c3010f5c9c03bce4b2dedc22f522a5fd84128980 100644 --- a/substrate/frame/atomic-swap/src/lib.rs +++ b/substrate/frame/atomic-swap/src/lib.rs @@ -42,6 +42,9 @@ mod tests; +extern crate alloc; + +use alloc::vec::Vec; use codec::{Decode, Encode}; use core::{ marker::PhantomData, @@ -58,7 +61,6 @@ use frame_system::pallet_prelude::BlockNumberFor; use scale_info::TypeInfo; use sp_io::hashing::blake2_256; use sp_runtime::RuntimeDebug; -use sp_std::vec::Vec; /// Pending atomic swap operation. #[derive(Clone, Eq, PartialEq, RuntimeDebugNoBound, Encode, Decode, TypeInfo, MaxEncodedLen)] diff --git a/substrate/frame/aura/Cargo.toml b/substrate/frame/aura/Cargo.toml index 97582e7d2e9dbf110a1c22b5de6ad5e592acb980..f9d74592763875aa5ef46f9665d6759504555a62 100644 --- a/substrate/frame/aura/Cargo.toml +++ b/substrate/frame/aura/Cargo.toml @@ -25,7 +25,6 @@ pallet-timestamp = { workspace = true } sp-application-crypto = { workspace = true } sp-consensus-aura = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] sp-core = { workspace = true } @@ -45,7 +44,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] try-runtime = [ "frame-support/try-runtime", diff --git a/substrate/frame/aura/src/lib.rs b/substrate/frame/aura/src/lib.rs index 3ca1444aaae9b61511a33ed6a9dc9075a2e8c864..f829578fb285132812f6ce341cf4f5efcb950101 100644 --- a/substrate/frame/aura/src/lib.rs +++ b/substrate/frame/aura/src/lib.rs @@ -38,6 +38,9 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + +use alloc::vec::Vec; use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{ traits::{DisabledValidators, FindAuthor, Get, OnTimestampSet, OneSessionHandler}, @@ -50,7 +53,6 @@ use sp_runtime::{ traits::{IsMember, Member, SaturatedConversion, Saturating, Zero}, RuntimeAppPublic, }; -use sp_std::prelude::*; pub mod migrations; mod mock; @@ -66,7 +68,7 @@ const LOG_TARGET: &str = "runtime::aura"; /// /// This was the default behavior of the Aura pallet and may be used for /// backwards compatibility. -pub struct MinimumPeriodTimesTwo(sp_std::marker::PhantomData); +pub struct MinimumPeriodTimesTwo(core::marker::PhantomData); impl Get for MinimumPeriodTimesTwo { fn get() -> T::Moment { @@ -119,7 +121,7 @@ pub mod pallet { } #[pallet::pallet] - pub struct Pallet(sp_std::marker::PhantomData); + pub struct Pallet(core::marker::PhantomData); #[pallet::hooks] impl Hooks> for Pallet { @@ -362,7 +364,7 @@ impl FindAuthor for Pallet { /// We can not implement `FindAuthor` twice, because the compiler does not know if /// `u32 == T::AuthorityId` and thus, prevents us to implement the trait twice. #[doc(hidden)] -pub struct FindAccountFromAuthorIndex(sp_std::marker::PhantomData<(T, Inner)>); +pub struct FindAccountFromAuthorIndex(core::marker::PhantomData<(T, Inner)>); impl> FindAuthor for FindAccountFromAuthorIndex diff --git a/substrate/frame/authority-discovery/Cargo.toml b/substrate/frame/authority-discovery/Cargo.toml index 79057d94107be2485c6bfb48ec9a20373b83e143..9d55a7fd5dcb83454396ee08d209f8d2930dfe6c 100644 --- a/substrate/frame/authority-discovery/Cargo.toml +++ b/substrate/frame/authority-discovery/Cargo.toml @@ -28,7 +28,6 @@ pallet-session = { features = [ sp-application-crypto = { workspace = true } sp-authority-discovery = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] sp-core = { workspace = true, default-features = true } @@ -47,7 +46,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] try-runtime = [ "frame-support/try-runtime", diff --git a/substrate/frame/authority-discovery/src/lib.rs b/substrate/frame/authority-discovery/src/lib.rs index 16f71960d693bec3de2babe446470e2db94bb8b9..220b39292b57598cdc1def77baef6874d7165c95 100644 --- a/substrate/frame/authority-discovery/src/lib.rs +++ b/substrate/frame/authority-discovery/src/lib.rs @@ -23,12 +23,14 @@ // Ensure we're `no_std` when compiling for Wasm. #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + +use alloc::vec::Vec; use frame_support::{ traits::{Get, OneSessionHandler}, WeakBoundedVec, }; use sp_authority_discovery::AuthorityId; -use sp_std::prelude::*; pub use pallet::*; @@ -62,7 +64,7 @@ pub mod pallet { pub struct GenesisConfig { pub keys: Vec, #[serde(skip)] - pub _config: sp_std::marker::PhantomData, + pub _config: core::marker::PhantomData, } #[pallet::genesis_build] @@ -168,6 +170,7 @@ impl OneSessionHandler for Pallet { mod tests { use super::*; use crate as pallet_authority_discovery; + use alloc::vec; use frame_support::{derive_impl, parameter_types, traits::ConstU32}; use sp_application_crypto::Pair; use sp_authority_discovery::AuthorityPair; diff --git a/substrate/frame/authorship/Cargo.toml b/substrate/frame/authorship/Cargo.toml index 58292c0eba393d482740a7cd59a748b17658f8c4..8ecacca93e0ab50c7a3d5d5fdfe2a5af43f99f2f 100644 --- a/substrate/frame/authorship/Cargo.toml +++ b/substrate/frame/authorship/Cargo.toml @@ -24,7 +24,6 @@ scale-info = { features = ["derive"], workspace = true } frame-support = { workspace = true } frame-system = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] sp-core = { workspace = true, default-features = true } @@ -40,7 +39,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] try-runtime = [ "frame-support/try-runtime", diff --git a/substrate/frame/authorship/src/lib.rs b/substrate/frame/authorship/src/lib.rs index d8f1baab23c8b11579c22a986dc65286f2e2508a..a0cca806e7863cef0259febfb3cba0cdeee4238f 100644 --- a/substrate/frame/authorship/src/lib.rs +++ b/substrate/frame/authorship/src/lib.rs @@ -22,7 +22,6 @@ #![cfg_attr(not(feature = "std"), no_std)] use frame_support::traits::FindAuthor; -use sp_std::prelude::*; pub use pallet::*; diff --git a/substrate/frame/babe/Cargo.toml b/substrate/frame/babe/Cargo.toml index 68638798e796a0a0cf67fd428216fb5b8114e95d..3dfda3b618be3764557ff53ec57578ff0515d5e9 100644 --- a/substrate/frame/babe/Cargo.toml +++ b/substrate/frame/babe/Cargo.toml @@ -32,7 +32,6 @@ sp-io = { workspace = true } sp-runtime = { features = ["serde"], workspace = true } sp-session = { workspace = true } sp-staking = { features = ["serde"], workspace = true } -sp-std = { workspace = true } [dev-dependencies] frame-election-provider-support = { workspace = true, default-features = true } @@ -65,7 +64,6 @@ std = [ "sp-runtime/std", "sp-session/std", "sp-staking/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/babe/src/equivocation.rs b/substrate/frame/babe/src/equivocation.rs index ed1df640583b26db4d07462618da92f324c59e4e..4be07bdae1f0154c2ca1331bbdd62b6540dae665 100644 --- a/substrate/frame/babe/src/equivocation.rs +++ b/substrate/frame/babe/src/equivocation.rs @@ -33,6 +33,7 @@ //! that the `ValidateUnsigned` for the BABE pallet is used in the runtime //! definition. +use alloc::{boxed::Box, vec, vec::Vec}; use frame_support::traits::{Get, KeyOwnerProofSystem}; use frame_system::pallet_prelude::HeaderFor; use log::{error, info}; @@ -50,7 +51,6 @@ use sp_staking::{ offence::{Kind, Offence, OffenceReportSystem, ReportOffence}, SessionIndex, }; -use sp_std::prelude::*; use crate::{Call, Config, Error, Pallet, LOG_TARGET}; @@ -104,7 +104,7 @@ impl Offence for EquivocationOffence { /// - On-chain validity checks and processing are mostly delegated to the user provided generic /// types implementing `KeyOwnerProofSystem` and `ReportOffence` traits. /// - Offence reporter for unsigned transactions is fetched via the the authorship pallet. -pub struct EquivocationReportSystem(sp_std::marker::PhantomData<(T, R, P, L)>); +pub struct EquivocationReportSystem(core::marker::PhantomData<(T, R, P, L)>); impl OffenceReportSystem, (EquivocationProof>, T::KeyOwnerProof)> diff --git a/substrate/frame/babe/src/lib.rs b/substrate/frame/babe/src/lib.rs index 9e16f1d09515688e0fc7226918d197dd86d9cb7e..3e33d5627c47b7b062af4431f913dd896e68d2bd 100644 --- a/substrate/frame/babe/src/lib.rs +++ b/substrate/frame/babe/src/lib.rs @@ -21,6 +21,9 @@ #![cfg_attr(not(feature = "std"), no_std)] #![warn(unused_must_use, unsafe_code, unused_variables, unused_must_use)] +extern crate alloc; + +use alloc::{boxed::Box, vec, vec::Vec}; use codec::{Decode, Encode}; use frame_support::{ dispatch::{DispatchResultWithPostInfo, Pays}, @@ -44,7 +47,6 @@ use sp_runtime::{ }; use sp_session::{GetSessionNumber, GetValidatorCount}; use sp_staking::{offence::OffenceReportSystem, SessionIndex}; -use sp_std::prelude::*; pub use sp_consensus_babe::AuthorityId; @@ -315,7 +317,7 @@ pub mod pallet { pub authorities: Vec<(AuthorityId, BabeAuthorityWeight)>, pub epoch_config: BabeEpochConfiguration, #[serde(skip)] - pub _config: sp_std::marker::PhantomData, + pub _config: core::marker::PhantomData, } #[pallet::genesis_build] @@ -687,7 +689,7 @@ impl Pallet { // Update the start blocks of the previous and new current epoch. EpochStart::::mutate(|(previous_epoch_start_block, current_epoch_start_block)| { - *previous_epoch_start_block = sp_std::mem::take(current_epoch_start_block); + *previous_epoch_start_block = core::mem::take(current_epoch_start_block); *current_epoch_start_block = >::block_number(); }); @@ -868,7 +870,7 @@ impl Pallet { /// randomness. Returns the new randomness. fn randomness_change_epoch(next_epoch_index: u64) -> BabeRandomness { let this_randomness = NextRandomness::::get(); - let segment_idx: u32 = SegmentIndex::::mutate(|s| sp_std::mem::replace(s, 0)); + let segment_idx: u32 = SegmentIndex::::mutate(|s| core::mem::replace(s, 0)); // overestimate to the segment being full. let rho_size = (segment_idx.saturating_add(1) * UNDER_CONSTRUCTION_SEGMENT_LENGTH) as usize; @@ -1055,7 +1057,7 @@ pub mod migrations { fn pallet_prefix() -> &'static str; } - struct __OldNextEpochConfig(sp_std::marker::PhantomData); + struct __OldNextEpochConfig(core::marker::PhantomData); impl frame_support::traits::StorageInstance for __OldNextEpochConfig { fn pallet_prefix() -> &'static str { T::pallet_prefix() diff --git a/substrate/frame/bags-list/Cargo.toml b/substrate/frame/bags-list/Cargo.toml index bf57bd2af53cef42fda4c963b327f52aa08edb89..549c4334b55db2d28508b92b98e6a45aa3365921 100644 --- a/substrate/frame/bags-list/Cargo.toml +++ b/substrate/frame/bags-list/Cargo.toml @@ -25,7 +25,6 @@ scale-info = { features = [ # primitives sp-runtime = { workspace = true } -sp-std = { workspace = true } # FRAME frame-support = { workspace = true } @@ -66,7 +65,6 @@ std = [ "sp-core?/std", "sp-io?/std", "sp-runtime/std", - "sp-std/std", "sp-tracing?/std", ] runtime-benchmarks = [ diff --git a/substrate/frame/bags-list/remote-tests/src/lib.rs b/substrate/frame/bags-list/remote-tests/src/lib.rs index 9f7c22d99dad1edf798259b784e91f90fe339104..1f0584fa07e5b78f3dc5a433af5a753e36eeb1f8 100644 --- a/substrate/frame/bags-list/remote-tests/src/lib.rs +++ b/substrate/frame/bags-list/remote-tests/src/lib.rs @@ -19,7 +19,6 @@ use frame_election_provider_support::ScoreProvider; use pallet_bags_list::Instance1; -use sp_std::prelude::*; /// A common log target to use. pub const LOG_TARGET: &str = "runtime::bags-list::remote-tests"; diff --git a/substrate/frame/bags-list/src/benchmarks.rs b/substrate/frame/bags-list/src/benchmarks.rs index 0c3955c0d7b79882b4fa97fe18ba0988fcc7d2af..55f4c24835ea685868eede09977fe967fc4a7bcf 100644 --- a/substrate/frame/bags-list/src/benchmarks.rs +++ b/substrate/frame/bags-list/src/benchmarks.rs @@ -19,6 +19,7 @@ use super::*; use crate::list::List; +use alloc::{vec, vec::Vec}; use frame_benchmarking::v1::{ account, benchmarks_instance_pallet, whitelist_account, whitelisted_caller, }; diff --git a/substrate/frame/bags-list/src/lib.rs b/substrate/frame/bags-list/src/lib.rs index 8e3d4cc1f012d7c5c8fa62c8eea903ea8fa522da..f6af1da5e7b78e9274add30b81e9cf25cf499df5 100644 --- a/substrate/frame/bags-list/src/lib.rs +++ b/substrate/frame/bags-list/src/lib.rs @@ -122,11 +122,13 @@ #[doc = docify::embed!("src/tests.rs", examples_work)] pub mod example {} +extern crate alloc; + +use alloc::boxed::Box; use codec::FullCodec; use frame_election_provider_support::{ScoreProvider, SortedListProvider}; use frame_system::ensure_signed; use sp_runtime::traits::{AtLeast32BitUnsigned, Bounded, StaticLookup}; -use sp_std::prelude::*; #[cfg(any(test, feature = "try-runtime", feature = "fuzz"))] use sp_runtime::TryRuntimeError; @@ -238,7 +240,7 @@ pub mod pallet { + Eq + Ord + PartialOrd - + sp_std::fmt::Debug + + core::fmt::Debug + Copy + AtLeast32BitUnsigned + Bounded @@ -465,7 +467,7 @@ impl, I: 'static> SortedListProvider for Pallet let node = list::Node::::get(who).unwrap(); let current_bag_idx = thresholds .iter() - .chain(sp_std::iter::once(&T::Score::max_value())) + .chain(core::iter::once(&T::Score::max_value())) .position(|w| w == &node.bag_upper) .unwrap(); diff --git a/substrate/frame/bags-list/src/list/mod.rs b/substrate/frame/bags-list/src/list/mod.rs index e90530341a1552b61e8d0caca39b1e5c021c4367..696b64d40e9b91bb5483159b4e21ecd5f800aa18 100644 --- a/substrate/frame/bags-list/src/list/mod.rs +++ b/substrate/frame/bags-list/src/list/mod.rs @@ -25,7 +25,12 @@ //! interface. use crate::Config; +use alloc::{ + boxed::Box, + collections::{btree_map::BTreeMap, btree_set::BTreeSet}, +}; use codec::{Decode, Encode, MaxEncodedLen}; +use core::{iter, marker::PhantomData}; use frame_election_provider_support::ScoreProvider; use frame_support::{ defensive, ensure, @@ -34,14 +39,15 @@ use frame_support::{ }; use scale_info::TypeInfo; use sp_runtime::traits::{Bounded, Zero}; -use sp_std::{ - boxed::Box, - collections::{btree_map::BTreeMap, btree_set::BTreeSet}, - iter, - marker::PhantomData, - prelude::*, -}; +#[cfg(any( + test, + feature = "try-runtime", + feature = "fuzz", + feature = "std", + feature = "runtime-benchmarks" +))] +use alloc::vec::Vec; #[cfg(any(test, feature = "try-runtime", feature = "fuzz"))] use sp_runtime::TryRuntimeError; @@ -274,7 +280,7 @@ impl, I: 'static> List { let start_node = Node::::get(start).ok_or(ListError::NodeNotFound)?; let start_node_upper = start_node.bag_upper; - let start_bag = sp_std::iter::successors(start_node.next(), |prev| prev.next()); + let start_bag = core::iter::successors(start_node.next(), |prev| prev.next()); let thresholds = T::BagThresholds::get(); let idx = thresholds.partition_point(|&threshold| start_node_upper > threshold); @@ -341,7 +347,7 @@ impl, I: 'static> List { if !Self::contains(id) { return Err(ListError::NodeNotFound) } - let _ = Self::remove_many(sp_std::iter::once(id)); + let _ = Self::remove_many(core::iter::once(id)); Ok(()) } @@ -591,7 +597,7 @@ impl, I: 'static> List { Box::new(iter) } else { // otherwise, insert it here. - Box::new(iter.chain(sp_std::iter::once(T::Score::max_value()))) + Box::new(iter.chain(core::iter::once(T::Score::max_value()))) }; iter.filter_map(|t| { @@ -673,7 +679,7 @@ impl, I: 'static> Bag { /// Iterate over the nodes in this bag. pub(crate) fn iter(&self) -> impl Iterator> { - sp_std::iter::successors(self.head(), |prev| prev.next()) + core::iter::successors(self.head(), |prev| prev.next()) } /// Insert a new id into this bag. @@ -804,7 +810,7 @@ impl, I: 'static> Bag { #[cfg(feature = "std")] #[allow(dead_code)] pub fn std_iter(&self) -> impl Iterator> { - sp_std::iter::successors(self.head(), |prev| prev.next()) + core::iter::successors(self.head(), |prev| prev.next()) } } diff --git a/substrate/frame/bags-list/src/migrations.rs b/substrate/frame/bags-list/src/migrations.rs index 7df63a6a44c54ebaeae42a177ed0328766e53593..bfc70fef370a54853c7ab277c01e922dc0aa24fc 100644 --- a/substrate/frame/bags-list/src/migrations.rs +++ b/substrate/frame/bags-list/src/migrations.rs @@ -28,10 +28,10 @@ use frame_support::ensure; use sp_runtime::TryRuntimeError; #[cfg(feature = "try-runtime")] -use sp_std::vec::Vec; +use alloc::vec::Vec; /// A struct that does not migration, but only checks that the counter prefix exists and is correct. -pub struct CheckCounterPrefix, I: 'static>(sp_std::marker::PhantomData<(T, I)>); +pub struct CheckCounterPrefix, I: 'static>(core::marker::PhantomData<(T, I)>); impl, I: 'static> OnRuntimeUpgrade for CheckCounterPrefix { fn on_runtime_upgrade() -> frame_support::weights::Weight { frame_support::weights::Weight::zero() @@ -88,7 +88,7 @@ mod old { } /// A struct that migrates all bags lists to contain a score value. -pub struct AddScore, I: 'static = ()>(sp_std::marker::PhantomData<(T, I)>); +pub struct AddScore, I: 'static = ()>(core::marker::PhantomData<(T, I)>); impl, I: 'static> OnRuntimeUpgrade for AddScore { #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result, TryRuntimeError> { diff --git a/substrate/frame/balances/Cargo.toml b/substrate/frame/balances/Cargo.toml index 5fa8fa84bf59e2401fba74f17f9c838f6cf3775a..85734dce9e9b2400b05e77202442bdb8e9ffb3b0 100644 --- a/substrate/frame/balances/Cargo.toml +++ b/substrate/frame/balances/Cargo.toml @@ -23,7 +23,6 @@ frame-benchmarking = { optional = true, workspace = true } frame-support = { workspace = true } frame-system = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } docify = { workspace = true } [dev-dependencies] @@ -46,7 +45,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] # Enable support for setting the existential deposit to zero. insecure_zero_ed = [] diff --git a/substrate/frame/balances/src/impl_currency.rs b/substrate/frame/balances/src/impl_currency.rs index d5fe9934e239e9e4c513e9e021686eec3ca757c3..049f0cc626c2e61cc276527dd9258e3d32ec7382 100644 --- a/substrate/frame/balances/src/impl_currency.rs +++ b/substrate/frame/balances/src/impl_currency.rs @@ -34,13 +34,14 @@ use frame_support::{ }; use frame_system::pallet_prelude::BlockNumberFor; pub use imbalances::{NegativeImbalance, PositiveImbalance}; +use sp_runtime::traits::Bounded; // wrapping these imbalances in a private module is necessary to ensure absolute privacy // of the inner member. mod imbalances { - use super::{result, Config, Imbalance, RuntimeDebug, Saturating, TryDrop, Zero}; + use super::*; + use core::mem; use frame_support::traits::SameOrOther; - use sp_std::mem; /// Opaque, move-only struct with private fields that serves as a token denoting that /// funds have been created without any equal and opposite accounting. @@ -199,14 +200,20 @@ mod imbalances { impl, I: 'static> Drop for PositiveImbalance { /// Basic drop handler will just square up the total issuance. fn drop(&mut self) { - >::mutate(|v| *v = v.saturating_add(self.0)); + if !self.0.is_zero() { + >::mutate(|v| *v = v.saturating_add(self.0)); + Pallet::::deposit_event(Event::::Issued { amount: self.0 }); + } } } impl, I: 'static> Drop for NegativeImbalance { /// Basic drop handler will just square up the total issuance. fn drop(&mut self) { - >::mutate(|v| *v = v.saturating_sub(self.0)); + if !self.0.is_zero() { + >::mutate(|v| *v = v.saturating_sub(self.0)); + Pallet::::deposit_event(Event::::Rescinded { amount: self.0 }); + } } } } @@ -263,6 +270,8 @@ where Zero::zero() }); }); + + Pallet::::deposit_event(Event::::Rescinded { amount }); PositiveImbalance::new(amount) } @@ -279,6 +288,8 @@ where Self::Balance::max_value() }) }); + + Pallet::::deposit_event(Event::::Issued { amount }); NegativeImbalance::new(amount) } diff --git a/substrate/frame/balances/src/lib.rs b/substrate/frame/balances/src/lib.rs index d01884293c0902ea66636877d1b3d65fbd74f5a1..ddca685aa012bbc5e5bc39e040661588f64e9fa4 100644 --- a/substrate/frame/balances/src/lib.rs +++ b/substrate/frame/balances/src/lib.rs @@ -150,7 +150,11 @@ mod tests; mod types; pub mod weights; +extern crate alloc; + +use alloc::vec::Vec; use codec::{Codec, MaxEncodedLen}; +use core::{cmp, fmt::Debug, mem, result}; use frame_support::{ ensure, pallet_prelude::DispatchResult, @@ -171,12 +175,11 @@ pub use impl_currency::{NegativeImbalance, PositiveImbalance}; use scale_info::TypeInfo; use sp_runtime::{ traits::{ - AtLeast32BitUnsigned, Bounded, CheckedAdd, CheckedSub, MaybeSerializeDeserialize, - Saturating, StaticLookup, Zero, + AtLeast32BitUnsigned, CheckedAdd, CheckedSub, MaybeSerializeDeserialize, Saturating, + StaticLookup, Zero, }, ArithmeticError, DispatchError, FixedPointOperand, Perbill, RuntimeDebug, TokenError, }; -use sp_std::{cmp, fmt::Debug, mem, prelude::*, result}; pub use types::{ AccountData, AdjustmentDirection, BalanceLock, DustCleaner, ExtraFlags, Reasons, ReserveData, }; @@ -525,7 +528,7 @@ pub mod pallet { .iter() .map(|(x, _)| x) .cloned() - .collect::>(); + .collect::>(); assert!( endowed_accounts.len() == self.balances.len(), @@ -856,13 +859,13 @@ pub mod pallet { } /// Get the free balance of an account. - pub fn free_balance(who: impl sp_std::borrow::Borrow) -> T::Balance { + pub fn free_balance(who: impl core::borrow::Borrow) -> T::Balance { Self::account(who.borrow()).free } /// Get the balance of an account that can be used for transfers, reservations, or any other /// non-locking, non-transaction-fee activity. Will be at most `free_balance`. - pub fn usable_balance(who: impl sp_std::borrow::Borrow) -> T::Balance { + pub fn usable_balance(who: impl core::borrow::Borrow) -> T::Balance { >::reducible_balance(who.borrow(), Expendable, Polite) } @@ -870,14 +873,12 @@ pub mod pallet { /// or any other kind of fees, though). Will be at most `free_balance`. /// /// This requires that the account stays alive. - pub fn usable_balance_for_fees( - who: impl sp_std::borrow::Borrow, - ) -> T::Balance { + pub fn usable_balance_for_fees(who: impl core::borrow::Borrow) -> T::Balance { >::reducible_balance(who.borrow(), Protect, Polite) } /// Get the reserved balance of an account. - pub fn reserved_balance(who: impl sp_std::borrow::Borrow) -> T::Balance { + pub fn reserved_balance(who: impl core::borrow::Borrow) -> T::Balance { Self::account(who.borrow()).reserved } diff --git a/substrate/frame/balances/src/tests/currency_tests.rs b/substrate/frame/balances/src/tests/currency_tests.rs index 9ad4aca64406b8ab1e284bf69d081211d47b37d9..fb69368a621616ba324a45c43d433b8b7e62acf4 100644 --- a/substrate/frame/balances/src/tests/currency_tests.rs +++ b/substrate/frame/balances/src/tests/currency_tests.rs @@ -399,10 +399,13 @@ fn reward_should_work() { ExtBuilder::default().monied(true).build_and_execute_with(|| { assert_eq!(Balances::total_balance(&1), 10); assert_ok!(Balances::deposit_into_existing(&1, 10).map(drop)); - System::assert_last_event(RuntimeEvent::Balances(crate::Event::Deposit { - who: 1, - amount: 10, - })); + assert_eq!( + events(), + [ + RuntimeEvent::Balances(crate::Event::Deposit { who: 1, amount: 10 }), + RuntimeEvent::Balances(crate::Event::Issued { amount: 10 }), + ] + ); assert_eq!(Balances::total_balance(&1), 20); assert_eq!(Balances::total_issuance(), 120); }); @@ -480,7 +483,7 @@ fn withdrawing_balance_should_work() { let _ = Balances::deposit_creating(&2, 111); let _ = Balances::withdraw(&2, 11, WithdrawReasons::TRANSFER, ExistenceRequirement::KeepAlive); - System::assert_last_event(RuntimeEvent::Balances(crate::Event::Withdraw { + System::assert_has_event(RuntimeEvent::Balances(crate::Event::Withdraw { who: 2, amount: 11, })); @@ -889,6 +892,7 @@ fn emit_events_with_existential_deposit() { [ RuntimeEvent::System(system::Event::NewAccount { account: 1 }), RuntimeEvent::Balances(crate::Event::Endowed { account: 1, free_balance: 100 }), + RuntimeEvent::Balances(crate::Event::Issued { amount: 100 }), RuntimeEvent::Balances(crate::Event::BalanceSet { who: 1, free: 100 }), ] ); @@ -902,6 +906,7 @@ fn emit_events_with_existential_deposit() { RuntimeEvent::System(system::Event::KilledAccount { account: 1 }), RuntimeEvent::Balances(crate::Event::DustLost { account: 1, amount: 99 }), RuntimeEvent::Balances(crate::Event::Slashed { who: 1, amount: 1 }), + RuntimeEvent::Balances(crate::Event::Rescinded { amount: 1 }), ] ); }); @@ -918,6 +923,7 @@ fn emit_events_with_no_existential_deposit_suicide() { RuntimeEvent::Balances(crate::Event::BalanceSet { who: 1, free: 100 }), RuntimeEvent::System(system::Event::NewAccount { account: 1 }), RuntimeEvent::Balances(crate::Event::Endowed { account: 1, free_balance: 100 }), + RuntimeEvent::Balances(crate::Event::Issued { amount: 100 }), ] ); @@ -929,6 +935,7 @@ fn emit_events_with_no_existential_deposit_suicide() { [ RuntimeEvent::System(system::Event::KilledAccount { account: 1 }), RuntimeEvent::Balances(crate::Event::Slashed { who: 1, amount: 100 }), + RuntimeEvent::Balances(crate::Event::Rescinded { amount: 100 }), ] ); }); @@ -954,7 +961,7 @@ fn slash_full_works() { assert_eq!(Balances::slash(&1, 1_000), (NegativeImbalance::new(1000), 0)); // Account is still alive assert!(!System::account_exists(&1)); - System::assert_last_event(RuntimeEvent::Balances(crate::Event::Slashed { + System::assert_has_event(RuntimeEvent::Balances(crate::Event::Slashed { who: 1, amount: 1000, })); @@ -969,7 +976,7 @@ fn slash_partial_works() { assert_eq!(Balances::slash(&1, 900), (NegativeImbalance::new(900), 0)); // Account is still alive assert!(System::account_exists(&1)); - System::assert_last_event(RuntimeEvent::Balances(crate::Event::Slashed { + System::assert_has_event(RuntimeEvent::Balances(crate::Event::Slashed { who: 1, amount: 900, })); @@ -983,7 +990,7 @@ fn slash_dusting_works() { // Slashed completed in full assert_eq!(Balances::slash(&1, 950), (NegativeImbalance::new(950), 0)); assert!(!System::account_exists(&1)); - System::assert_last_event(RuntimeEvent::Balances(crate::Event::Slashed { + System::assert_has_event(RuntimeEvent::Balances(crate::Event::Slashed { who: 1, amount: 950, })); @@ -998,7 +1005,7 @@ fn slash_does_not_take_from_reserve() { // Slashed completed in full assert_eq!(Balances::slash(&1, 900), (NegativeImbalance::new(800), 100)); assert_eq!(Balances::reserved_balance(&1), 100); - System::assert_last_event(RuntimeEvent::Balances(crate::Event::Slashed { + System::assert_has_event(RuntimeEvent::Balances(crate::Event::Slashed { who: 1, amount: 800, })); @@ -1399,6 +1406,7 @@ fn self_transfer_noop() { Event::Deposit { who: 1, amount: 100 }.into(), SysEvent::NewAccount { account: 1 }.into(), Event::Endowed { account: 1, free_balance: 100 }.into(), + Event::Issued { amount: 100 }.into(), ] ); assert_eq!(Balances::free_balance(1), 100); diff --git a/substrate/frame/balances/src/tests/reentrancy_tests.rs b/substrate/frame/balances/src/tests/reentrancy_tests.rs index 717f04978577f1d82f1c743cbac988a6820f90bc..0b66f2c93e3a74c55de103117dd67d3e0968adaa 100644 --- a/substrate/frame/balances/src/tests/reentrancy_tests.rs +++ b/substrate/frame/balances/src/tests/reentrancy_tests.rs @@ -52,7 +52,7 @@ fn transfer_dust_removal_tst1_should_work() { assert_eq!(Balances::free_balance(&1), 1050); // Verify the events - assert_eq!(System::events().len(), 12); + assert_eq!(System::events().len(), 14); System::assert_has_event(RuntimeEvent::Balances(crate::Event::Transfer { from: 2, @@ -93,7 +93,7 @@ fn transfer_dust_removal_tst2_should_work() { assert_eq!(Balances::free_balance(&1), 1500); // Verify the events - assert_eq!(System::events().len(), 10); + assert_eq!(System::events().len(), 12); System::assert_has_event(RuntimeEvent::Balances(crate::Event::Transfer { from: 2, @@ -139,7 +139,7 @@ fn repatriating_reserved_balance_dust_removal_should_work() { assert_eq!(Balances::free_balance(1), 1500); // Verify the events - assert_eq!(System::events().len(), 10); + assert_eq!(System::events().len(), 12); System::assert_has_event(RuntimeEvent::Balances(crate::Event::Transfer { from: 2, @@ -167,6 +167,7 @@ fn emit_events_with_no_existential_deposit_suicide_with_dust() { [ RuntimeEvent::System(system::Event::NewAccount { account: 1 }), RuntimeEvent::Balances(crate::Event::Endowed { account: 1, free_balance: 100 }), + RuntimeEvent::Balances(crate::Event::Issued { amount: 100 }), RuntimeEvent::Balances(crate::Event::BalanceSet { who: 1, free: 100 }), ] ); diff --git a/substrate/frame/beefy-mmr/Cargo.toml b/substrate/frame/beefy-mmr/Cargo.toml index b46998a857426fb3edfa8affaea702cffc2f4732..92e903af138d595d063b344bb24238e632a3430d 100644 --- a/substrate/frame/beefy-mmr/Cargo.toml +++ b/substrate/frame/beefy-mmr/Cargo.toml @@ -27,7 +27,6 @@ sp-consensus-beefy = { workspace = true } sp-core = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } sp-api = { workspace = true } sp-state-machine = { workspace = true } @@ -56,7 +55,6 @@ std = [ "sp-runtime/std", "sp-staking/std", "sp-state-machine/std", - "sp-std/std", ] try-runtime = [ "frame-support/try-runtime", @@ -66,3 +64,10 @@ try-runtime = [ "pallet-session/try-runtime", "sp-runtime/try-runtime", ] +runtime-benchmarks = [ + "frame-support/runtime-benchmarks", + "frame-system/runtime-benchmarks", + "pallet-mmr/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", + "sp-staking/runtime-benchmarks", +] diff --git a/substrate/frame/beefy-mmr/src/lib.rs b/substrate/frame/beefy-mmr/src/lib.rs index 18ebc9d8f38a765153bbd2cde73265ee1e87f480..ec341cad2084a717b5e90fdf1921d62c05ea914e 100644 --- a/substrate/frame/beefy-mmr/src/lib.rs +++ b/substrate/frame/beefy-mmr/src/lib.rs @@ -33,9 +33,11 @@ //! //! and thanks to versioning can be easily updated in the future. +extern crate alloc; + use sp_runtime::traits::{Convert, Header, Member}; -use sp_std::prelude::*; +use alloc::vec::Vec; use codec::Decode; use pallet_mmr::{primitives::AncestryProof, LeafDataProvider, ParentNumberAndHash}; use sp_consensus_beefy::{ @@ -56,7 +58,7 @@ mod mock; mod tests; /// A BEEFY consensus digest item with MMR root hash. -pub struct DepositBeefyDigest(sp_std::marker::PhantomData); +pub struct DepositBeefyDigest(core::marker::PhantomData); impl pallet_mmr::primitives::OnNewRoot for DepositBeefyDigest where diff --git a/substrate/frame/beefy-mmr/src/mock.rs b/substrate/frame/beefy-mmr/src/mock.rs index 0521bdabbe4958c99aebceef48a4a4a8b031cb6a..3adef4f32bf43a1aca43d39483303d35ee916ff6 100644 --- a/substrate/frame/beefy-mmr/src/mock.rs +++ b/substrate/frame/beefy-mmr/src/mock.rs @@ -93,6 +93,9 @@ impl pallet_mmr::Config for Test { type BlockHashProvider = pallet_mmr::DefaultBlockHashProvider; type WeightInfo = (); + + #[cfg(feature = "runtime-benchmarks")] + type BenchmarkHelper = (); } impl pallet_beefy::Config for Test { diff --git a/substrate/frame/beefy/Cargo.toml b/substrate/frame/beefy/Cargo.toml index 8ce3a05985be7dfa383b91c187451f3a4753efd6..089b817e226f37878cfdd2fb00d231afea642d03 100644 --- a/substrate/frame/beefy/Cargo.toml +++ b/substrate/frame/beefy/Cargo.toml @@ -24,7 +24,6 @@ sp-consensus-beefy = { features = ["serde"], workspace = true } sp-runtime = { features = ["serde"], workspace = true } sp-session = { workspace = true } sp-staking = { features = ["serde"], workspace = true } -sp-std = { workspace = true } [dev-dependencies] frame-election-provider-support = { workspace = true, default-features = true } @@ -61,7 +60,6 @@ std = [ "sp-session/std", "sp-staking/std", "sp-state-machine/std", - "sp-std/std", ] try-runtime = [ "frame-election-provider-support/try-runtime", diff --git a/substrate/frame/beefy/src/equivocation.rs b/substrate/frame/beefy/src/equivocation.rs index a1526e7811111366b6f4a3012529f7e81df0e5db..15345e6ae1997ccd0e768edd56afcecb11e21f35 100644 --- a/substrate/frame/beefy/src/equivocation.rs +++ b/substrate/frame/beefy/src/equivocation.rs @@ -34,6 +34,7 @@ //! that the `ValidateUnsigned` for the BEEFY pallet is used in the runtime //! definition. +use alloc::{vec, vec::Vec}; use codec::{self as codec, Decode, Encode}; use frame_support::traits::{Get, KeyOwnerProofSystem}; use frame_system::pallet_prelude::{BlockNumberFor, HeaderFor}; @@ -54,7 +55,6 @@ use sp_staking::{ offence::{Kind, Offence, OffenceReportSystem, ReportOffence}, SessionIndex, }; -use sp_std::prelude::*; use super::{Call, Config, Error, Pallet, LOG_TARGET}; @@ -122,7 +122,7 @@ where /// - On-chain validity checks and processing are mostly delegated to the user provided generic /// types implementing `KeyOwnerProofSystem` and `ReportOffence` traits. /// - Offence reporter for unsigned transactions is fetched via the authorship pallet. -pub struct EquivocationReportSystem(sp_std::marker::PhantomData<(T, R, P, L)>); +pub struct EquivocationReportSystem(core::marker::PhantomData<(T, R, P, L)>); /// Equivocation evidence convenience alias. pub enum EquivocationEvidenceFor { diff --git a/substrate/frame/beefy/src/lib.rs b/substrate/frame/beefy/src/lib.rs index a49f5d28f455a99560b9fc445f1a64c471aa54cc..fd9a0027c6fc6f8fb34cea5c4e6ce0940530155b 100644 --- a/substrate/frame/beefy/src/lib.rs +++ b/substrate/frame/beefy/src/lib.rs @@ -17,6 +17,9 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + +use alloc::{boxed::Box, vec::Vec}; use codec::{Encode, MaxEncodedLen}; use frame_support::{ @@ -38,7 +41,6 @@ use sp_runtime::{ }; use sp_session::{GetSessionNumber, GetValidatorCount}; use sp_staking::{offence::OffenceReportSystem, SessionIndex}; -use sp_std::prelude::*; use sp_consensus_beefy::{ AncestryHelper, AuthorityIndex, BeefyAuthorityId, ConsensusLog, DoubleVotingProof, diff --git a/substrate/frame/benchmarking/Cargo.toml b/substrate/frame/benchmarking/Cargo.toml index a2c15951a596673edf2ab6d3485dbefb022e7acb..61bc706963bb6c457e17a4cbc68a81b557a9e8d5 100644 --- a/substrate/frame/benchmarking/Cargo.toml +++ b/substrate/frame/benchmarking/Cargo.toml @@ -31,7 +31,6 @@ sp-core = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } sp-runtime-interface = { workspace = true } -sp-std = { workspace = true } sp-storage = { workspace = true } static_assertions = { workspace = true, default-features = true } @@ -58,7 +57,6 @@ std = [ "sp-keystore/std", "sp-runtime-interface/std", "sp-runtime/std", - "sp-std/std", "sp-storage/std", ] runtime-benchmarks = [ diff --git a/substrate/frame/benchmarking/pov/Cargo.toml b/substrate/frame/benchmarking/pov/Cargo.toml index 4341f011fcbf9c323fbe9b5b7de7d1b86bc71c12..6a449fb597d5641c15d807e79d2ec9b96d2dc78e 100644 --- a/substrate/frame/benchmarking/pov/Cargo.toml +++ b/substrate/frame/benchmarking/pov/Cargo.toml @@ -22,7 +22,6 @@ frame-support = { workspace = true } frame-system = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [features] default = ["std"] @@ -34,7 +33,6 @@ std = [ "scale-info/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/benchmarking/pov/src/benchmarking.rs b/substrate/frame/benchmarking/pov/src/benchmarking.rs index 7e6aa8e6bf605859fe3cc6bf0cd0b4bd3d56ccc1..bf3d406d0b2b04364646ac4051f73d7efcebe502 100644 --- a/substrate/frame/benchmarking/pov/src/benchmarking.rs +++ b/substrate/frame/benchmarking/pov/src/benchmarking.rs @@ -247,7 +247,7 @@ mod benchmarks { #[benchmark(pov_mode = Measured)] fn measured_storage_value_read_linear_size(l: Linear<0, { 1 << 22 }>) { - let v: sp_runtime::BoundedVec = sp_std::vec![0u8; l as usize].try_into().unwrap(); + let v: sp_runtime::BoundedVec = alloc::vec![0u8; l as usize].try_into().unwrap(); LargeValue::::put(&v); #[block] { @@ -257,7 +257,7 @@ mod benchmarks { #[benchmark(pov_mode = MaxEncodedLen)] fn mel_storage_value_read_linear_size(l: Linear<0, { 1 << 22 }>) { - let v: sp_runtime::BoundedVec = sp_std::vec![0u8; l as usize].try_into().unwrap(); + let v: sp_runtime::BoundedVec = alloc::vec![0u8; l as usize].try_into().unwrap(); LargeValue::::put(&v); #[block] { @@ -267,7 +267,7 @@ mod benchmarks { #[benchmark(pov_mode = Measured)] fn measured_storage_double_value_read_linear_size(l: Linear<0, { 1 << 22 }>) { - let v: sp_runtime::BoundedVec = sp_std::vec![0u8; l as usize].try_into().unwrap(); + let v: sp_runtime::BoundedVec = alloc::vec![0u8; l as usize].try_into().unwrap(); LargeValue::::put(&v); LargeValue2::::put(&v); #[block] @@ -279,7 +279,7 @@ mod benchmarks { #[benchmark(pov_mode = MaxEncodedLen)] fn mel_storage_double_value_read_linear_size(l: Linear<0, { 1 << 22 }>) { - let v: sp_runtime::BoundedVec = sp_std::vec![0u8; l as usize].try_into().unwrap(); + let v: sp_runtime::BoundedVec = alloc::vec![0u8; l as usize].try_into().unwrap(); LargeValue::::put(&v); LargeValue2::::put(&v); #[block] @@ -293,7 +293,7 @@ mod benchmarks { Pov::LargeValue2: Measured })] fn mel_mixed_storage_double_value_read_linear_size(l: Linear<0, { 1 << 22 }>) { - let v: sp_runtime::BoundedVec = sp_std::vec![0u8; l as usize].try_into().unwrap(); + let v: sp_runtime::BoundedVec = alloc::vec![0u8; l as usize].try_into().unwrap(); LargeValue::::put(&v); LargeValue2::::put(&v); #[block] @@ -307,7 +307,7 @@ mod benchmarks { Pov::LargeValue2: MaxEncodedLen })] fn measured_mixed_storage_double_value_read_linear_size(l: Linear<0, { 1 << 22 }>) { - let v: sp_runtime::BoundedVec = sp_std::vec![0u8; l as usize].try_into().unwrap(); + let v: sp_runtime::BoundedVec = alloc::vec![0u8; l as usize].try_into().unwrap(); LargeValue::::put(&v); LargeValue2::::put(&v); #[block] @@ -319,8 +319,8 @@ mod benchmarks { #[benchmark(pov_mode = Measured)] fn storage_map_unbounded_both_measured_read(i: Linear<0, 1000>) { - UnboundedMap::::insert(i, sp_std::vec![0; i as usize]); - UnboundedMap2::::insert(i, sp_std::vec![0; i as usize]); + UnboundedMap::::insert(i, alloc::vec![0; i as usize]); + UnboundedMap2::::insert(i, alloc::vec![0; i as usize]); #[block] { assert!(UnboundedMap::::get(i).is_some()); @@ -333,7 +333,7 @@ mod benchmarks { })] fn storage_map_partial_unbounded_read(i: Linear<0, 1000>) { Map1M::::insert(i, 0); - UnboundedMap::::insert(i, sp_std::vec![0; i as usize]); + UnboundedMap::::insert(i, alloc::vec![0; i as usize]); #[block] { assert!(Map1M::::get(i).is_some()); @@ -346,7 +346,7 @@ mod benchmarks { })] fn storage_map_partial_unbounded_ignored_read(i: Linear<0, 1000>) { Map1M::::insert(i, 0); - UnboundedMap::::insert(i, sp_std::vec![0; i as usize]); + UnboundedMap::::insert(i, alloc::vec![0; i as usize]); #[block] { assert!(Map1M::::get(i).is_some()); @@ -379,7 +379,7 @@ mod benchmarks { #[benchmark] fn storage_iteration() { for i in 0..65000 { - UnboundedMapTwox::::insert(i, sp_std::vec![0; 64]); + UnboundedMapTwox::::insert(i, alloc::vec![0; 64]); } #[block] { diff --git a/substrate/frame/benchmarking/pov/src/lib.rs b/substrate/frame/benchmarking/pov/src/lib.rs index eb02ccc983c09fd5084a174d07cdc10fd5ecac22..4cdbaec2305c129ee03e6323b0aea0e811b96efb 100644 --- a/substrate/frame/benchmarking/pov/src/lib.rs +++ b/substrate/frame/benchmarking/pov/src/lib.rs @@ -23,13 +23,15 @@ mod benchmarking; mod tests; mod weights; +extern crate alloc; + pub use pallet::*; #[frame_support::pallet] pub mod pallet { + use alloc::vec::Vec; use frame_support::pallet_prelude::*; use frame_system::pallet_prelude::*; - use sp_std::prelude::*; #[pallet::pallet] pub struct Pallet(_); diff --git a/substrate/frame/benchmarking/src/baseline.rs b/substrate/frame/benchmarking/src/baseline.rs index e76d5aed7b8d3539810ec7c7cd2f83acb51479eb..711d2123ca8316c7715a7a7fd5cc292bbb5e409a 100644 --- a/substrate/frame/benchmarking/src/baseline.rs +++ b/substrate/frame/benchmarking/src/baseline.rs @@ -21,12 +21,12 @@ #![cfg(feature = "runtime-benchmarks")] use crate::benchmarks; +use alloc::{vec, vec::Vec}; use frame_system::Pallet as System; use sp_runtime::{ traits::{AppVerify, Hash}, RuntimeAppPublic, }; -use sp_std::{vec, vec::Vec}; mod crypto { use sp_application_crypto::{app_crypto, sr25519, KeyTypeId}; diff --git a/substrate/frame/benchmarking/src/lib.rs b/substrate/frame/benchmarking/src/lib.rs index d4ee0abbecce5be341881d73004c59bf71d9db97..625da2a24bd0ad1d9375bdffeaeca87b0beb9671 100644 --- a/substrate/frame/benchmarking/src/lib.rs +++ b/substrate/frame/benchmarking/src/lib.rs @@ -19,6 +19,8 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + #[cfg(feature = "std")] mod analysis; #[cfg(test)] @@ -35,6 +37,7 @@ pub mod v1; /// The exports are not stable and should not be relied on. #[doc(hidden)] pub mod __private { + pub use alloc::{boxed::Box, str, vec, vec::Vec}; pub use codec; pub use frame_support::{storage, traits}; pub use log; @@ -42,7 +45,6 @@ pub mod __private { pub use sp_core::defer; pub use sp_io::storage::root as storage_root; pub use sp_runtime::{traits::Zero, StateVersion}; - pub use sp_std::{self, boxed::Box, str, vec, vec::Vec}; pub use sp_storage::{well_known_keys, TrackedStorageKey}; } diff --git a/substrate/frame/benchmarking/src/tests.rs b/substrate/frame/benchmarking/src/tests.rs index bcca5fe7c2f2a59fb81c6f4e52ee1f5e7f7c0da3..09011eadb03ae850ddb00a6c29c59ecc33315746 100644 --- a/substrate/frame/benchmarking/src/tests.rs +++ b/substrate/frame/benchmarking/src/tests.rs @@ -25,7 +25,6 @@ use sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; -use sp_std::prelude::*; use std::cell::RefCell; #[frame_support::pallet(dev_mode)] @@ -130,7 +129,6 @@ mod benchmarks { use frame_support::{assert_err, assert_ok, ensure, traits::Get}; use frame_system::RawOrigin; use rusty_fork::rusty_fork_test; - use sp_std::prelude::*; // Additional used internally by the benchmark macro. use super::pallet_test::{Call, Config, Pallet}; diff --git a/substrate/frame/benchmarking/src/tests_instance.rs b/substrate/frame/benchmarking/src/tests_instance.rs index d6e1cf99ef73f33820fbea31c8f31a560ec487b6..ecffbd1a018fa067d7b7fa0013fc4d9aef49f460 100644 --- a/substrate/frame/benchmarking/src/tests_instance.rs +++ b/substrate/frame/benchmarking/src/tests_instance.rs @@ -25,7 +25,6 @@ use sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, BuildStorage, }; -use sp_std::prelude::*; #[frame_support::pallet] mod pallet_test { @@ -131,7 +130,6 @@ mod benchmarks { use crate::account; use frame_support::ensure; use frame_system::RawOrigin; - use sp_std::prelude::*; // Additional used internally by the benchmark macro. use super::pallet_test::{Call, Config, Pallet}; diff --git a/substrate/frame/benchmarking/src/utils.rs b/substrate/frame/benchmarking/src/utils.rs index bfa25f63ef33eb9cb724a7ca3aa25ec706046d98..ca362f7aa7efe20e4c78a29a2a7d3136ec548775 100644 --- a/substrate/frame/benchmarking/src/utils.rs +++ b/substrate/frame/benchmarking/src/utils.rs @@ -16,6 +16,7 @@ // limitations under the License. //! Interfaces, types and utils for benchmarking a FRAME runtime. +use alloc::vec::Vec; use codec::{Decode, Encode}; use frame_support::{dispatch::DispatchErrorWithPostInfo, pallet_prelude::*, traits::StorageInfo}; use scale_info::TypeInfo; @@ -23,7 +24,6 @@ use scale_info::TypeInfo; use serde::{Deserialize, Serialize}; use sp_io::hashing::blake2_256; use sp_runtime::{traits::TrailingZeroInput, DispatchError}; -use sp_std::vec::Vec; use sp_storage::TrackedStorageKey; /// An alphabet of possible parameters to use for benchmarking. diff --git a/substrate/frame/benchmarking/src/v1.rs b/substrate/frame/benchmarking/src/v1.rs index 07778646237edc6f4f2fdb0151033dc8cd84aa5f..d687f9fdfa1048241e6a4547ce0d5fa5a9110b8d 100644 --- a/substrate/frame/benchmarking/src/v1.rs +++ b/substrate/frame/benchmarking/src/v1.rs @@ -1741,9 +1741,9 @@ pub fn show_benchmark_debug_info( * Components: {:?}\n\ * Verify: {:?}\n\ * Error message: {}", - sp_std::str::from_utf8(instance_string) + alloc::str::from_utf8(instance_string) .expect("it's all just strings ran through the wasm interface. qed"), - sp_std::str::from_utf8(benchmark) + alloc::str::from_utf8(benchmark) .expect("it's all just strings ran through the wasm interface. qed"), components, verify, diff --git a/substrate/frame/bounties/Cargo.toml b/substrate/frame/bounties/Cargo.toml index 4b242a1a577ced6599a8142acc8d85f8af0f93e2..cb9fa1f964b06fa56a27b3de31cf7cc88ac37d67 100644 --- a/substrate/frame/bounties/Cargo.toml +++ b/substrate/frame/bounties/Cargo.toml @@ -28,7 +28,6 @@ pallet-treasury = { workspace = true } sp-core = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] pallet-balances = { workspace = true, default-features = true } @@ -47,7 +46,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/bounties/src/benchmarking.rs b/substrate/frame/bounties/src/benchmarking.rs index a009b132f0598c9ec54a52780982436c9839495f..de93ba5c4ce7ac30ad5a090358d7da33ccb34ba9 100644 --- a/substrate/frame/bounties/src/benchmarking.rs +++ b/substrate/frame/bounties/src/benchmarking.rs @@ -21,6 +21,7 @@ use super::*; +use alloc::{vec, vec::Vec}; use frame_benchmarking::v1::{ account, benchmarks_instance_pallet, whitelisted_caller, BenchmarkError, }; @@ -231,5 +232,5 @@ benchmarks_instance_pallet! { } } - impl_benchmark_test_suite!(Bounties, crate::tests::new_test_ext(), crate::tests::Test) + impl_benchmark_test_suite!(Bounties, crate::tests::ExtBuilder::default().build(), crate::tests::Test) } diff --git a/substrate/frame/bounties/src/lib.rs b/substrate/frame/bounties/src/lib.rs index e27ecbda3a2b91ab7433724d488f016046ab71fd..7b89a6e3e76f5ead57e76c17a304080d2dc978d0 100644 --- a/substrate/frame/bounties/src/lib.rs +++ b/substrate/frame/bounties/src/lib.rs @@ -87,7 +87,9 @@ pub mod migrations; mod tests; pub mod weights; -use sp_std::prelude::*; +extern crate alloc; + +use alloc::vec::Vec; use frame_support::traits::{ Currency, ExistenceRequirement::AllowDeath, Get, Imbalance, OnUnbalanced, ReservableCurrency, @@ -807,6 +809,54 @@ pub mod pallet { Ok(()) } } + + #[pallet::hooks] + impl, I: 'static> Hooks> for Pallet { + #[cfg(feature = "try-runtime")] + fn try_state(_n: BlockNumberFor) -> Result<(), sp_runtime::TryRuntimeError> { + Self::do_try_state() + } + } +} + +#[cfg(any(feature = "try-runtime", test))] +impl, I: 'static> Pallet { + /// Ensure the correctness of the state of this pallet. + /// + /// This should be valid before or after each state transition of this pallet. + pub fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> { + Self::try_state_bounties_count()?; + + Ok(()) + } + + /// # Invariants + /// + /// * `BountyCount` should be greater or equals to the length of the number of items in + /// `Bounties`. + /// * `BountyCount` should be greater or equals to the length of the number of items in + /// `BountyDescriptions`. + /// * Number of items in `Bounties` should be the same as `BountyDescriptions` length. + fn try_state_bounties_count() -> Result<(), sp_runtime::TryRuntimeError> { + let bounties_length = Bounties::::iter().count() as u32; + + ensure!( + >::get() >= bounties_length, + "`BountyCount` must be grater or equals the number of `Bounties` in storage" + ); + + let bounties_description_length = BountyDescriptions::::iter().count() as u32; + ensure!( + >::get() >= bounties_description_length, + "`BountyCount` must be grater or equals the number of `BountiesDescriptions` in storage." + ); + + ensure!( + bounties_length == bounties_description_length, + "Number of `Bounties` in storage must be the same as the Number of `BountiesDescription` in storage." + ); + Ok(()) + } } impl, I: 'static> Pallet { diff --git a/substrate/frame/bounties/src/tests.rs b/substrate/frame/bounties/src/tests.rs index 9f3a52263ec8d8513e35b04835b632febb04c524..7cd4798267450641eb2ec71da952ae8c7ed8bf27 100644 --- a/substrate/frame/bounties/src/tests.rs +++ b/substrate/frame/bounties/src/tests.rs @@ -167,18 +167,36 @@ impl Config for Test { type TreasuryError = pallet_treasury::Error; type TreasuryError1 = pallet_treasury::Error; -pub fn new_test_ext() -> sp_io::TestExternalities { - let mut ext: sp_io::TestExternalities = RuntimeGenesisConfig { - system: frame_system::GenesisConfig::default(), - balances: pallet_balances::GenesisConfig { balances: vec![(0, 100), (1, 98), (2, 1)] }, - treasury: Default::default(), - treasury_1: Default::default(), +pub struct ExtBuilder {} + +impl Default for ExtBuilder { + fn default() -> Self { + Self {} + } +} + +impl ExtBuilder { + pub fn build(self) -> sp_io::TestExternalities { + let mut ext: sp_io::TestExternalities = RuntimeGenesisConfig { + system: frame_system::GenesisConfig::default(), + balances: pallet_balances::GenesisConfig { balances: vec![(0, 100), (1, 98), (2, 1)] }, + treasury: Default::default(), + treasury_1: Default::default(), + } + .build_storage() + .unwrap() + .into(); + ext.execute_with(|| System::set_block_number(1)); + ext + } + + pub fn build_and_execute(self, test: impl FnOnce() -> ()) { + self.build().execute_with(|| { + test(); + Bounties::do_try_state().expect("All invariants must hold after a test"); + Bounties1::do_try_state().expect("All invariants must hold after a test"); + }) } - .build_storage() - .unwrap() - .into(); - ext.execute_with(|| System::set_block_number(1)); - ext } fn last_event() -> BountiesEvent { @@ -192,7 +210,7 @@ fn last_event() -> BountiesEvent { #[test] fn genesis_config_works() { - new_test_ext().execute_with(|| { + ExtBuilder::default().build_and_execute(|| { assert_eq!(Treasury::pot(), 0); assert_eq!(Treasury::proposal_count(), 0); }); @@ -200,7 +218,7 @@ fn genesis_config_works() { #[test] fn minting_works() { - new_test_ext().execute_with(|| { + ExtBuilder::default().build_and_execute(|| { // Check that accumulate works when we have Some value in Dummy already. Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Treasury::pot(), 100); @@ -209,7 +227,7 @@ fn minting_works() { #[test] fn accepted_spend_proposal_ignored_outside_spend_period() { - new_test_ext().execute_with(|| { + ExtBuilder::default().build_and_execute(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_ok!({ Treasury::spend_local(RuntimeOrigin::root(), 100, 3) }); @@ -222,7 +240,7 @@ fn accepted_spend_proposal_ignored_outside_spend_period() { #[test] fn unused_pot_should_diminish() { - new_test_ext().execute_with(|| { + ExtBuilder::default().build_and_execute(|| { let init_total_issuance = Balances::total_issuance(); Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Balances::total_issuance(), init_total_issuance + 100); @@ -235,7 +253,7 @@ fn unused_pot_should_diminish() { #[test] fn accepted_spend_proposal_enacted_on_spend_period() { - new_test_ext().execute_with(|| { + ExtBuilder::default().build_and_execute(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Treasury::pot(), 100); @@ -249,7 +267,7 @@ fn accepted_spend_proposal_enacted_on_spend_period() { #[test] fn pot_underflow_should_not_diminish() { - new_test_ext().execute_with(|| { + ExtBuilder::default().build_and_execute(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Treasury::pot(), 100); @@ -269,7 +287,7 @@ fn pot_underflow_should_not_diminish() { // i.e. pot should not include existential deposit needed for account survival. #[test] fn treasury_account_doesnt_get_deleted() { - new_test_ext().execute_with(|| { + ExtBuilder::default().build_and_execute(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Treasury::pot(), 100); let treasury_balance = Balances::free_balance(&Treasury::account_id()); @@ -321,7 +339,7 @@ fn inexistent_account_works() { #[test] fn propose_bounty_works() { - new_test_ext().execute_with(|| { + ExtBuilder::default().build_and_execute(|| { System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); @@ -358,7 +376,7 @@ fn propose_bounty_works() { #[test] fn propose_bounty_validation_works() { - new_test_ext().execute_with(|| { + ExtBuilder::default().build_and_execute(|| { System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); @@ -387,7 +405,7 @@ fn propose_bounty_validation_works() { #[test] fn close_bounty_works() { - new_test_ext().execute_with(|| { + ExtBuilder::default().build_and_execute(|| { System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_noop!(Bounties::close_bounty(RuntimeOrigin::root(), 0), Error::::InvalidIndex); @@ -412,7 +430,7 @@ fn close_bounty_works() { #[test] fn approve_bounty_works() { - new_test_ext().execute_with(|| { + ExtBuilder::default().build_and_execute(|| { System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_noop!( @@ -473,7 +491,7 @@ fn approve_bounty_works() { #[test] fn assign_curator_works() { - new_test_ext().execute_with(|| { + ExtBuilder::default().build_and_execute(|| { System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); @@ -543,7 +561,7 @@ fn assign_curator_works() { #[test] fn unassign_curator_works() { - new_test_ext().execute_with(|| { + ExtBuilder::default().build_and_execute(|| { System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); @@ -596,7 +614,7 @@ fn unassign_curator_works() { #[test] fn award_and_claim_bounty_works() { - new_test_ext().execute_with(|| { + ExtBuilder::default().build_and_execute(|| { System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); Balances::make_free_balance_be(&4, 10); @@ -663,7 +681,7 @@ fn award_and_claim_bounty_works() { #[test] fn claim_handles_high_fee() { - new_test_ext().execute_with(|| { + ExtBuilder::default().build_and_execute(|| { System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); Balances::make_free_balance_be(&4, 30); @@ -704,7 +722,7 @@ fn claim_handles_high_fee() { #[test] fn cancel_and_refund() { - new_test_ext().execute_with(|| { + ExtBuilder::default().build_and_execute(|| { System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); @@ -747,7 +765,7 @@ fn cancel_and_refund() { #[test] fn award_and_cancel() { - new_test_ext().execute_with(|| { + ExtBuilder::default().build_and_execute(|| { System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); @@ -790,7 +808,7 @@ fn award_and_cancel() { #[test] fn expire_and_unassign() { - new_test_ext().execute_with(|| { + ExtBuilder::default().build_and_execute(|| { System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); @@ -838,7 +856,7 @@ fn expire_and_unassign() { #[test] fn extend_expiry() { - new_test_ext().execute_with(|| { + ExtBuilder::default().build_and_execute(|| { System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); Balances::make_free_balance_be(&4, 10); @@ -974,7 +992,7 @@ fn genesis_funding_works() { #[test] fn unassign_curator_self() { - new_test_ext().execute_with(|| { + ExtBuilder::default().build_and_execute(|| { System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_ok!(Bounties::propose_bounty(RuntimeOrigin::signed(0), 50, b"12345".to_vec())); @@ -1015,7 +1033,7 @@ fn unassign_curator_self() { fn accept_curator_handles_different_deposit_calculations() { // This test will verify that a bounty with and without a fee results // in a different curator deposit: one using the value, and one using the fee. - new_test_ext().execute_with(|| { + ExtBuilder::default().build_and_execute(|| { // Case 1: With a fee let user = 1; let bounty_index = 0; @@ -1092,7 +1110,7 @@ fn accept_curator_handles_different_deposit_calculations() { #[test] fn approve_bounty_works_second_instance() { - new_test_ext().execute_with(|| { + ExtBuilder::default().build_and_execute(|| { // Set burn to 0 to make tracking funds easier. Burn::set(Permill::from_percent(0)); @@ -1118,7 +1136,7 @@ fn approve_bounty_works_second_instance() { #[test] fn approve_bounty_insufficient_spend_limit_errors() { - new_test_ext().execute_with(|| { + ExtBuilder::default().build_and_execute(|| { System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); @@ -1136,7 +1154,7 @@ fn approve_bounty_insufficient_spend_limit_errors() { #[test] fn approve_bounty_instance1_insufficient_spend_limit_errors() { - new_test_ext().execute_with(|| { + ExtBuilder::default().build_and_execute(|| { System::set_block_number(1); Balances::make_free_balance_be(&Treasury1::account_id(), 101); @@ -1154,7 +1172,7 @@ fn approve_bounty_instance1_insufficient_spend_limit_errors() { #[test] fn propose_curator_insufficient_spend_limit_errors() { - new_test_ext().execute_with(|| { + ExtBuilder::default().build_and_execute(|| { System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); @@ -1177,7 +1195,7 @@ fn propose_curator_insufficient_spend_limit_errors() { #[test] fn propose_curator_instance1_insufficient_spend_limit_errors() { - new_test_ext().execute_with(|| { + ExtBuilder::default().build_and_execute(|| { System::set_block_number(1); Balances::make_free_balance_be(&Treasury::account_id(), 101); diff --git a/substrate/frame/broker/Cargo.toml b/substrate/frame/broker/Cargo.toml index 77c4883e4a433ffb0e0fb8c376b23bf109948769..7593a4e8da14ab7d63e97b59c4860253a6ca51fd 100644 --- a/substrate/frame/broker/Cargo.toml +++ b/substrate/frame/broker/Cargo.toml @@ -20,7 +20,6 @@ codec = { features = ["derive"], workspace = true } scale-info = { features = ["derive"], workspace = true } bitvec = { workspace = true } sp-api = { workspace = true } -sp-std = { workspace = true } sp-arithmetic = { workspace = true } sp-core = { workspace = true } sp-runtime = { workspace = true } @@ -49,7 +48,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ diff --git a/substrate/frame/broker/src/benchmarking.rs b/substrate/frame/broker/src/benchmarking.rs index 3c9ea4cdba4e74da1df2fe343bc8412da2fe5466..33df56c95f65dbcc7fdc4472971b632d7b9ab605 100644 --- a/substrate/frame/broker/src/benchmarking.rs +++ b/substrate/frame/broker/src/benchmarking.rs @@ -20,6 +20,7 @@ use super::*; use crate::{CoreAssignment::Task, Pallet as Broker}; +use alloc::{vec, vec::Vec}; use frame_benchmarking::v2::*; use frame_support::{ storage::bounded_vec::BoundedVec, @@ -32,7 +33,6 @@ use frame_system::{Pallet as System, RawOrigin}; use sp_arithmetic::{traits::Zero, Perbill}; use sp_core::Get; use sp_runtime::{traits::BlockNumberProvider, Saturating}; -use sp_std::{vec, vec::Vec}; const SEED: u32 = 0; const MAX_CORE_COUNT: u16 = 1_000; diff --git a/substrate/frame/broker/src/coretime_interface.rs b/substrate/frame/broker/src/coretime_interface.rs index f92f8b22091ac992180fd3f44d93cffddd59061d..9c18e2c4ff0b33ce2357f8c1ba6860f2d56efc49 100644 --- a/substrate/frame/broker/src/coretime_interface.rs +++ b/substrate/frame/broker/src/coretime_interface.rs @@ -17,13 +17,14 @@ #![deny(missing_docs)] +use alloc::vec::Vec; use codec::{Decode, Encode, MaxEncodedLen}; +use core::fmt::Debug; use frame_support::Parameter; use scale_info::TypeInfo; use sp_arithmetic::traits::AtLeast32BitUnsigned; use sp_core::RuntimeDebug; use sp_runtime::traits::BlockNumberProvider; -use sp_std::{fmt::Debug, vec::Vec}; use crate::Timeslice; diff --git a/substrate/frame/broker/src/lib.rs b/substrate/frame/broker/src/lib.rs index 4cb380bae91d87e1ec32a96d88cfaa1b5fcd97a4..45c33c1bfa61545c0b02dfcd35f133ceef0c6e70 100644 --- a/substrate/frame/broker/src/lib.rs +++ b/substrate/frame/broker/src/lib.rs @@ -47,12 +47,15 @@ pub use core_mask::*; pub use coretime_interface::*; pub use types::*; +extern crate alloc; + /// The log target for this pallet. const LOG_TARGET: &str = "runtime::broker"; #[frame_support::pallet] pub mod pallet { use super::*; + use alloc::vec::Vec; use frame_support::{ pallet_prelude::{DispatchResult, DispatchResultWithPostInfo, *}, traits::{ @@ -63,7 +66,6 @@ pub mod pallet { }; use frame_system::pallet_prelude::*; use sp_runtime::traits::{Convert, ConvertBack}; - use sp_std::vec::Vec; const STORAGE_VERSION: StorageVersion = StorageVersion::new(3); @@ -496,7 +498,7 @@ pub mod pallet { #[pallet::genesis_config] pub struct GenesisConfig { #[serde(skip)] - pub _config: sp_std::marker::PhantomData, + pub _config: core::marker::PhantomData, } #[pallet::genesis_build] diff --git a/substrate/frame/broker/src/migration.rs b/substrate/frame/broker/src/migration.rs index 917f44a134cc17bb61ce6dfed0206a505a0f2d21..c2a243d6f0e8e571b7f52b4f7112348ed05ba998 100644 --- a/substrate/frame/broker/src/migration.rs +++ b/substrate/frame/broker/src/migration.rs @@ -23,9 +23,9 @@ use frame_support::traits::{Get, UncheckedOnRuntimeUpgrade}; use sp_runtime::Saturating; #[cfg(feature = "try-runtime")] -use frame_support::ensure; +use alloc::vec::Vec; #[cfg(feature = "try-runtime")] -use sp_std::vec::Vec; +use frame_support::ensure; mod v1 { use super::*; diff --git a/substrate/frame/broker/src/mock.rs b/substrate/frame/broker/src/mock.rs index f29651abff7b814791c446c29994e7617c619da1..6b1d2bbf7015dc8c1858678aaad9674177c9d638 100644 --- a/substrate/frame/broker/src/mock.rs +++ b/substrate/frame/broker/src/mock.rs @@ -18,6 +18,7 @@ #![cfg(test)] use crate::{test_fungibles::TestFungibles, *}; +use alloc::collections::btree_map::BTreeMap; use frame_support::{ assert_ok, derive_impl, ensure, ord_parameter_types, parameter_types, traits::{ @@ -34,7 +35,6 @@ use sp_runtime::{ traits::{BlockNumberProvider, Identity}, BuildStorage, Saturating, }; -use sp_std::collections::btree_map::BTreeMap; type Block = frame_system::mocking::MockBlock; diff --git a/substrate/frame/broker/src/nonfungible_impl.rs b/substrate/frame/broker/src/nonfungible_impl.rs index 80dcc175df539bbc9861fdaa30adfdab1bb40172..e272ecbe0081bcfe0dd97ec763fcfd77bb4f1ba4 100644 --- a/substrate/frame/broker/src/nonfungible_impl.rs +++ b/substrate/frame/broker/src/nonfungible_impl.rs @@ -16,11 +16,11 @@ // limitations under the License. use super::*; +use alloc::vec::Vec; use frame_support::{ pallet_prelude::{DispatchResult, *}, traits::nonfungible::{Inspect, Mutate, Transfer}, }; -use sp_std::vec::Vec; impl Inspect for Pallet { type ItemId = u128; diff --git a/substrate/frame/broker/src/test_fungibles.rs b/substrate/frame/broker/src/test_fungibles.rs index d18bff1495331e96b699e708975f4942925354fb..b0a06fc1a326d837e49506726a211ca600230138 100644 --- a/substrate/frame/broker/src/test_fungibles.rs +++ b/substrate/frame/broker/src/test_fungibles.rs @@ -15,6 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +use alloc::collections::btree_map::BTreeMap; use codec::{Decode, Encode}; use frame_support::{ parameter_types, @@ -29,7 +30,6 @@ use scale_info::TypeInfo; use sp_arithmetic::traits::Zero; use sp_core::{Get, TypedGet}; use sp_runtime::{DispatchError, DispatchResult}; -use sp_std::collections::btree_map::BTreeMap; parameter_types! { static TestAssetOf: BTreeMap<(u32, Vec), Vec> = Default::default(); diff --git a/substrate/frame/broker/src/tick_impls.rs b/substrate/frame/broker/src/tick_impls.rs index 3292faa4eb7e398bd603de6fa1108a1e5470f588..71a1286d73915dc554597abddc2e724a5cce98c4 100644 --- a/substrate/frame/broker/src/tick_impls.rs +++ b/substrate/frame/broker/src/tick_impls.rs @@ -16,10 +16,10 @@ // limitations under the License. use super::*; +use alloc::{vec, vec::Vec}; use frame_support::{pallet_prelude::*, traits::defensive_prelude::*, weights::WeightMeter}; use sp_arithmetic::traits::{One, SaturatedConversion, Saturating, Zero}; use sp_runtime::traits::ConvertBack; -use sp_std::{vec, vec::Vec}; use CompletionStatus::Complete; impl Pallet { diff --git a/substrate/frame/child-bounties/Cargo.toml b/substrate/frame/child-bounties/Cargo.toml index d0072e3a476132fb7ea2eeef35d895dc2829dc80..9c979b41462c45e20704dbb1111de1f4796acd2b 100644 --- a/substrate/frame/child-bounties/Cargo.toml +++ b/substrate/frame/child-bounties/Cargo.toml @@ -29,7 +29,6 @@ pallet-treasury = { workspace = true } sp-core = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] pallet-balances = { workspace = true, default-features = true } @@ -49,7 +48,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking", diff --git a/substrate/frame/child-bounties/src/benchmarking.rs b/substrate/frame/child-bounties/src/benchmarking.rs index 947cfcfaa96a2daeb88c68c9cda501c42554fbe3..b1f6370f33405495f4becb317b5c0459966d6710 100644 --- a/substrate/frame/child-bounties/src/benchmarking.rs +++ b/substrate/frame/child-bounties/src/benchmarking.rs @@ -21,6 +21,8 @@ use super::*; +use alloc::{vec, vec::Vec}; + use frame_benchmarking::v1::{account, benchmarks, whitelisted_caller, BenchmarkError}; use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; diff --git a/substrate/frame/child-bounties/src/lib.rs b/substrate/frame/child-bounties/src/lib.rs index 04a1f9799cb86e8831a849620b8288fc0692a9c8..911fd4c4c49f7118557dcc04dbe53600f4cbd1f7 100644 --- a/substrate/frame/child-bounties/src/lib.rs +++ b/substrate/frame/child-bounties/src/lib.rs @@ -56,7 +56,9 @@ mod benchmarking; mod tests; pub mod weights; -use sp_std::prelude::*; +extern crate alloc; + +use alloc::vec::Vec; use frame_support::traits::{ Currency, diff --git a/substrate/frame/collective/Cargo.toml b/substrate/frame/collective/Cargo.toml index 6fc4bb7782987f6e32faaabea1e4e661822829bb..7d9a4c41c81292f941bcb3c6cbbb0628cd4f396a 100644 --- a/substrate/frame/collective/Cargo.toml +++ b/substrate/frame/collective/Cargo.toml @@ -25,7 +25,6 @@ frame-system = { workspace = true } sp-core = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [features] default = ["std"] @@ -39,7 +38,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/collective/src/lib.rs b/substrate/frame/collective/src/lib.rs index d0009d02f68c2f0d26e5847221c85ede39e9e633..3544a8cddb45cadf022a2808f3c199651d5e6798 100644 --- a/substrate/frame/collective/src/lib.rs +++ b/substrate/frame/collective/src/lib.rs @@ -41,14 +41,17 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + +use alloc::{boxed::Box, vec, vec::Vec}; use codec::{Decode, Encode, MaxEncodedLen}; +use core::{marker::PhantomData, result}; use scale_info::TypeInfo; use sp_io::storage; use sp_runtime::{ traits::{Dispatchable, Hash}, DispatchError, RuntimeDebug, }; -use sp_std::{marker::PhantomData, prelude::*, result}; use frame_support::{ dispatch::{ @@ -239,7 +242,7 @@ pub mod pallet { #[pallet::genesis_build] impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) { - use sp_std::collections::btree_set::BTreeSet; + use alloc::collections::btree_set::BTreeSet; let members_set: BTreeSet<_> = self.members.iter().collect(); assert_eq!( members_set.len(), diff --git a/substrate/frame/contracts/fixtures/contracts/create_transient_storage_and_call.rs b/substrate/frame/contracts/fixtures/contracts/create_transient_storage_and_call.rs new file mode 100644 index 0000000000000000000000000000000000000000..6bafee5557715520dc7e3fa02de28060fd3bc561 --- /dev/null +++ b/substrate/frame/contracts/fixtures/contracts/create_transient_storage_and_call.rs @@ -0,0 +1,56 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! This calls another contract as passed as its account id. It also creates some transient storage. +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!( + buffer, + len: u32, + input: [u8; 4], + callee: [u8; 32], + ); + + let data = [0u8; 16 * 1024]; + let value = &data[..len as usize]; + #[allow(deprecated)] + api::set_transient_storage(buffer, value); + + // Call the callee + api::call_v2( + uapi::CallFlags::empty(), + callee, + 0u64, // How much ref_time weight to devote for the execution. 0 = all. + 0u64, // How much proof_size weight to devote for the execution. 0 = all. + None, + &0u64.to_le_bytes(), // Value transferred to the contract. + input, + None, + ) + .unwrap(); +} diff --git a/substrate/frame/contracts/fixtures/contracts/set_transient_storage.rs b/substrate/frame/contracts/fixtures/contracts/set_transient_storage.rs new file mode 100644 index 0000000000000000000000000000000000000000..e4fde08314ce8bc7d09168411607834044b3c467 --- /dev/null +++ b/substrate/frame/contracts/fixtures/contracts/set_transient_storage.rs @@ -0,0 +1,42 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +#![no_std] +#![no_main] + +use common::input; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + input!(len: u32, ); + + let buffer = [0u8; 16 * 1024]; + let data = &buffer[..len as usize]; + + // Place a garbage value in the transient storage, with the size specified by the call input. + let mut key = [0u8; 32]; + key[0] = 1; + + #[allow(deprecated)] + api::set_transient_storage(&key, data); +} diff --git a/substrate/frame/contracts/fixtures/contracts/transient_storage.rs b/substrate/frame/contracts/fixtures/contracts/transient_storage.rs new file mode 100644 index 0000000000000000000000000000000000000000..c797e17887bc8f4bc03418a6d3d90160efe35295 --- /dev/null +++ b/substrate/frame/contracts/fixtures/contracts/transient_storage.rs @@ -0,0 +1,58 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! This contract tests the transient storage APIs. +#![no_std] +#![no_main] + +use common::unwrap_output; +use uapi::{HostFn, HostFnImpl as api}; + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn deploy() {} + +#[no_mangle] +#[polkavm_derive::polkavm_export] +pub extern "C" fn call() { + const KEY: [u8; 32] = [1u8; 32]; + const VALUE_1: [u8; 4] = [1u8; 4]; + const VALUE_2: [u8; 4] = [2u8; 4]; + const VALUE_3: [u8; 4] = [3u8; 4]; + + #[allow(deprecated)] + { + let existing = api::set_transient_storage(&KEY, &VALUE_1); + assert_eq!(existing, None); + assert_eq!(api::contains_transient_storage(&KEY), Some(VALUE_1.len() as _)); + unwrap_output!(val, [0u8; 4], api::get_transient_storage, &KEY); + assert_eq!(**val, VALUE_1); + + let existing = api::set_transient_storage(&KEY, &VALUE_2); + assert_eq!(existing, Some(VALUE_1.len() as _)); + unwrap_output!(val, [0u8; 4], api::get_transient_storage, &KEY); + assert_eq!(**val, VALUE_2); + + api::clear_transient_storage(&KEY); + assert_eq!(api::contains_transient_storage(&KEY), None); + + let existing = api::set_transient_storage(&KEY, &VALUE_3); + assert_eq!(existing, None); + unwrap_output!(val, [0u8; 32], api::take_transient_storage, &KEY); + assert_eq!(**val, VALUE_3); + } +} diff --git a/substrate/frame/contracts/mock-network/Cargo.toml b/substrate/frame/contracts/mock-network/Cargo.toml index 7df5d304c34afa9258492a121ca23feff0318de9..85d98206ea57b4570db87c5e556059d156b4db23 100644 --- a/substrate/frame/contracts/mock-network/Cargo.toml +++ b/substrate/frame/contracts/mock-network/Cargo.toml @@ -36,7 +36,6 @@ sp-core = { workspace = true } sp-io = { workspace = true } sp-keystore = { workspace = true, default-features = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } sp-tracing = { workspace = true, default-features = true } xcm = { workspace = true } xcm-builder = { workspace = true, default-features = true } @@ -67,7 +66,6 @@ std = [ "sp-io/std", "sp-keystore/std", "sp-runtime/std", - "sp-std/std", "xcm-executor/std", "xcm/std", ] diff --git a/substrate/frame/contracts/mock-network/src/mocks/msg_queue.rs b/substrate/frame/contracts/mock-network/src/mocks/msg_queue.rs index bfdf6dd97eaf17fc0601f78c7c179e411c3a143d..6e922c16c2982b8399978511b9dd5558ba2c0ce8 100644 --- a/substrate/frame/contracts/mock-network/src/mocks/msg_queue.rs +++ b/substrate/frame/contracts/mock-network/src/mocks/msg_queue.rs @@ -25,7 +25,6 @@ use polkadot_parachain_primitives::primitives::{ use polkadot_primitives::BlockNumber as RelayBlockNumber; use sp_runtime::traits::{Get, Hash}; -use sp_std::prelude::*; use xcm::{latest::prelude::*, VersionedXcm}; #[frame_support::pallet] diff --git a/substrate/frame/contracts/mock-network/src/parachain.rs b/substrate/frame/contracts/mock-network/src/parachain.rs index f35846ba32c31e0b260ffe428f459f0a14b9256b..3579b46ea6e9c858e73cfaa879104c550042a011 100644 --- a/substrate/frame/contracts/mock-network/src/parachain.rs +++ b/substrate/frame/contracts/mock-network/src/parachain.rs @@ -35,7 +35,6 @@ use pallet_xcm::XcmPassthrough; use sp_core::{ConstU32, ConstU64, H256}; use sp_runtime::traits::{Get, IdentityLookup, MaybeEquivalence}; -use sp_std::prelude::*; use xcm::latest::prelude::*; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowTopLevelPaidExecutionFrom, diff --git a/substrate/frame/contracts/proc-macro/src/lib.rs b/substrate/frame/contracts/proc-macro/src/lib.rs index f91f8660cd315b4971eb60921d185f99c76ba9e3..84ea7de00a2f1d3a3e64404dede2cde1556d039a 100644 --- a/substrate/frame/contracts/proc-macro/src/lib.rs +++ b/substrate/frame/contracts/proc-macro/src/lib.rs @@ -649,7 +649,7 @@ fn expand_functions(def: &EnvDef, expand_mode: ExpandMode) -> TokenStream2 { quote! { let result = #body; if ::log::log_enabled!(target: "runtime::contracts::strace", ::log::Level::Trace) { - use sp_std::fmt::Write; + use core::fmt::Write; let mut w = sp_std::Writer::default(); let _ = core::write!(&mut w, #trace_fmt_str, #( #trace_fmt_args, )* result); let msg = core::str::from_utf8(&w.inner()).unwrap_or_default(); diff --git a/substrate/frame/contracts/src/benchmarking/call_builder.rs b/substrate/frame/contracts/src/benchmarking/call_builder.rs index 5d73d825fca9a76d15742c7a44b32b11a95fed51..5833639d7ce257f488187768233531d2d888ec88 100644 --- a/substrate/frame/contracts/src/benchmarking/call_builder.rs +++ b/substrate/frame/contracts/src/benchmarking/call_builder.rs @@ -17,17 +17,18 @@ use crate::{ benchmarking::{Contract, WasmModule}, - exec::Stack, + exec::{Ext, Key, Stack}, storage::meter::Meter, + transient_storage::MeterEntry, wasm::Runtime, - BalanceOf, Config, DebugBufferVec, Determinism, ExecReturnValue, GasMeter, Origin, Schedule, - TypeInfo, WasmBlob, Weight, + BalanceOf, Config, DebugBufferVec, Determinism, Error, ExecReturnValue, GasMeter, Origin, + Schedule, TypeInfo, WasmBlob, Weight, }; +use alloc::{vec, vec::Vec}; use codec::{Encode, HasCompact}; use core::fmt::Debug; use frame_benchmarking::benchmarking; use sp_core::Get; -use sp_std::prelude::*; type StackExt<'a, T> = Stack<'a, T, WasmBlob>; @@ -56,6 +57,7 @@ pub struct CallSetup { debug_message: Option>, determinism: Determinism, data: Vec, + transient_storage_size: u32, } impl Default for CallSetup @@ -103,6 +105,7 @@ where debug_message: None, determinism: Determinism::Enforced, data: vec![], + transient_storage_size: 0, } } @@ -126,6 +129,11 @@ where self.data = value; } + /// Set the transient storage size. + pub fn set_transient_storage_size(&mut self, size: u32) { + self.transient_storage_size = size; + } + /// Set the debug message. pub fn enable_debug_message(&mut self) { self.debug_message = Some(Default::default()); @@ -148,7 +156,7 @@ where /// Build the call stack. pub fn ext(&mut self) -> (StackExt<'_, T>, WasmBlob) { - StackExt::bench_new_call( + let mut ext = StackExt::bench_new_call( self.dest.clone(), self.origin.clone(), &mut self.gas_meter, @@ -157,7 +165,11 @@ where self.value, self.debug_message.as_mut(), self.determinism, - ) + ); + if self.transient_storage_size > 0 { + Self::with_transient_storage(&mut ext.0, self.transient_storage_size).unwrap(); + } + ext } /// Prepare a call to the module. @@ -169,6 +181,30 @@ where let (func, store) = module.bench_prepare_call(ext, input); PreparedCall { func, store } } + + /// Add transient_storage + fn with_transient_storage(ext: &mut StackExt, size: u32) -> Result<(), &'static str> { + let &MeterEntry { amount, limit } = ext.transient_storage().meter().current(); + ext.transient_storage().meter().current_mut().limit = size; + for i in 1u32.. { + let mut key_data = i.to_le_bytes().to_vec(); + while key_data.last() == Some(&0) { + key_data.pop(); + } + let key = Key::::try_from_var(key_data).unwrap(); + if let Err(e) = ext.set_transient_storage(&key, Some(Vec::new()), false) { + // Restore previous settings. + ext.transient_storage().meter().current_mut().limit = limit; + ext.transient_storage().meter().current_mut().amount = amount; + if e == Error::::OutOfTransientStorage.into() { + break; + } else { + return Err("Initialization of the transient storage failed"); + } + } + } + Ok(()) + } } #[macro_export] diff --git a/substrate/frame/contracts/src/benchmarking/code.rs b/substrate/frame/contracts/src/benchmarking/code.rs index 65bcf30683c05e83515815ae33ffe5d9c4aadb70..1473022b5537885ad2a068a6cf97b26e755811ef 100644 --- a/substrate/frame/contracts/src/benchmarking/code.rs +++ b/substrate/frame/contracts/src/benchmarking/code.rs @@ -25,9 +25,9 @@ //! compiles it down into a `WasmModule` that can be used as a contract's code. use crate::Config; +use alloc::{borrow::ToOwned, vec, vec::Vec}; use frame_support::traits::Get; use sp_runtime::{traits::Hash, Saturating}; -use sp_std::{borrow::ToOwned, prelude::*}; use wasm_instrument::parity_wasm::{ builder, elements::{ @@ -338,7 +338,7 @@ pub mod body { .cycle() .take(instructions.len() * usize::try_from(repetitions).unwrap()) .cloned() - .chain(sp_std::iter::once(Instruction::End)) + .chain(core::iter::once(Instruction::End)) .collect(), ); FuncBody::new(locals.to_vec(), instructions) diff --git a/substrate/frame/contracts/src/benchmarking/mod.rs b/substrate/frame/contracts/src/benchmarking/mod.rs index 80c7e863d2994020e5f79dc3364cddb25dc72890..620e6544b08f9f5d0a67731b1a95e4e373863567 100644 --- a/substrate/frame/contracts/src/benchmarking/mod.rs +++ b/substrate/frame/contracts/src/benchmarking/mod.rs @@ -31,9 +31,11 @@ use crate::{ migration::{ codegen::LATEST_MIGRATION_VERSION, v09, v10, v11, v12, v13, v14, v15, v16, MigrationStep, }, + storage::WriteOutcome, wasm::BenchEnv, Pallet as Contracts, *, }; +use alloc::{vec, vec::Vec}; use codec::{Encode, MaxEncodedLen}; use frame_benchmarking::v2::*; use frame_support::{ @@ -46,7 +48,6 @@ use frame_system::RawOrigin; use pallet_balances; use pallet_contracts_uapi::{CallFlags, ReturnErrorCode}; use sp_runtime::traits::{Bounded, Hash}; -use sp_std::prelude::*; use wasm_instrument::parity_wasm::elements::{Instruction, Local, ValueType}; /// How many runs we do per API benchmark. @@ -186,7 +187,7 @@ fn caller_funding() -> BalanceOf { #[benchmarks( where - as codec::HasCompact>::Type: Clone + Eq + PartialEq + sp_std::fmt::Debug + scale_info::TypeInfo + codec::Encode, + as codec::HasCompact>::Type: Clone + Eq + PartialEq + core::fmt::Debug + scale_info::TypeInfo + codec::Encode, T: Config + pallet_balances::Config, BalanceOf: From< as Currency>::Balance>, as Currency>::Balance: From>, @@ -1162,6 +1163,296 @@ mod benchmarks { Ok(()) } + // We use both full and empty benchmarks here instead of benchmarking transient_storage + // (BTreeMap) directly. This approach is necessary because benchmarking this BTreeMap is very + // slow. Additionally, we use linear regression for our benchmarks, and the BTreeMap's log(n) + // complexity can introduce approximation errors. + #[benchmark(pov_mode = Ignored)] + fn set_transient_storage_empty() -> Result<(), BenchmarkError> { + let max_value_len = T::Schedule::get().limits.payload_len; + let max_key_len = T::MaxStorageKeyLen::get(); + let key = Key::::try_from_var(vec![0u8; max_key_len as usize]) + .map_err(|_| "Key has wrong length")?; + let value = Some(vec![42u8; max_value_len as _]); + let mut setup = CallSetup::::default(); + let (mut ext, _) = setup.ext(); + let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![]); + runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX; + let result; + #[block] + { + result = runtime.ext().set_transient_storage(&key, value, false); + } + + assert_eq!(result, Ok(WriteOutcome::New)); + assert_eq!(runtime.ext().get_transient_storage(&key), Some(vec![42u8; max_value_len as _])); + Ok(()) + } + + #[benchmark(pov_mode = Ignored)] + fn set_transient_storage_full() -> Result<(), BenchmarkError> { + let max_value_len = T::Schedule::get().limits.payload_len; + let max_key_len = T::MaxStorageKeyLen::get(); + let key = Key::::try_from_var(vec![0u8; max_key_len as usize]) + .map_err(|_| "Key has wrong length")?; + let value = Some(vec![42u8; max_value_len as _]); + let mut setup = CallSetup::::default(); + setup.set_transient_storage_size(T::MaxTransientStorageSize::get()); + let (mut ext, _) = setup.ext(); + let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![]); + runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX; + let result; + #[block] + { + result = runtime.ext().set_transient_storage(&key, value, false); + } + + assert_eq!(result, Ok(WriteOutcome::New)); + assert_eq!(runtime.ext().get_transient_storage(&key), Some(vec![42u8; max_value_len as _])); + Ok(()) + } + + #[benchmark(pov_mode = Ignored)] + fn get_transient_storage_empty() -> Result<(), BenchmarkError> { + let max_value_len = T::Schedule::get().limits.payload_len; + let max_key_len = T::MaxStorageKeyLen::get(); + let key = Key::::try_from_var(vec![0u8; max_key_len as usize]) + .map_err(|_| "Key has wrong length")?; + + let mut setup = CallSetup::::default(); + let (mut ext, _) = setup.ext(); + let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![]); + runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX; + runtime + .ext() + .set_transient_storage(&key, Some(vec![42u8; max_value_len as _]), false) + .map_err(|_| "Failed to write to transient storage during setup.")?; + let result; + #[block] + { + result = runtime.ext().get_transient_storage(&key); + } + + assert_eq!(result, Some(vec![42u8; max_value_len as _])); + Ok(()) + } + + #[benchmark(pov_mode = Ignored)] + fn get_transient_storage_full() -> Result<(), BenchmarkError> { + let max_value_len = T::Schedule::get().limits.payload_len; + let max_key_len = T::MaxStorageKeyLen::get(); + let key = Key::::try_from_var(vec![0u8; max_key_len as usize]) + .map_err(|_| "Key has wrong length")?; + + let mut setup = CallSetup::::default(); + setup.set_transient_storage_size(T::MaxTransientStorageSize::get()); + let (mut ext, _) = setup.ext(); + let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![]); + runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX; + runtime + .ext() + .set_transient_storage(&key, Some(vec![42u8; max_value_len as _]), false) + .map_err(|_| "Failed to write to transient storage during setup.")?; + let result; + #[block] + { + result = runtime.ext().get_transient_storage(&key); + } + + assert_eq!(result, Some(vec![42u8; max_value_len as _])); + Ok(()) + } + + // The weight of journal rollbacks should be taken into account when setting storage. + #[benchmark(pov_mode = Ignored)] + fn rollback_transient_storage() -> Result<(), BenchmarkError> { + let max_value_len = T::Schedule::get().limits.payload_len; + let max_key_len = T::MaxStorageKeyLen::get(); + let key = Key::::try_from_var(vec![0u8; max_key_len as usize]) + .map_err(|_| "Key has wrong length")?; + + let mut setup = CallSetup::::default(); + setup.set_transient_storage_size(T::MaxTransientStorageSize::get()); + let (mut ext, _) = setup.ext(); + let mut runtime = crate::wasm::Runtime::new(&mut ext, vec![]); + runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX; + runtime.ext().transient_storage().start_transaction(); + runtime + .ext() + .set_transient_storage(&key, Some(vec![42u8; max_value_len as _]), false) + .map_err(|_| "Failed to write to transient storage during setup.")?; + #[block] + { + runtime.ext().transient_storage().rollback_transaction(); + } + + assert_eq!(runtime.ext().get_transient_storage(&key), None); + Ok(()) + } + + // n: new byte size + // o: old byte size + #[benchmark(pov_mode = Measured)] + fn seal_set_transient_storage( + n: Linear<0, { T::Schedule::get().limits.payload_len }>, + o: Linear<0, { T::Schedule::get().limits.payload_len }>, + ) -> Result<(), BenchmarkError> { + let max_key_len = T::MaxStorageKeyLen::get(); + let key = Key::::try_from_var(vec![0u8; max_key_len as usize]) + .map_err(|_| "Key has wrong length")?; + let value = vec![1u8; n as usize]; + build_runtime!(runtime, memory: [ key.to_vec(), value.clone(), ]); + runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX; + runtime + .ext() + .set_transient_storage(&key, Some(vec![42u8; o as usize]), false) + .map_err(|_| "Failed to write to transient storage during setup.")?; + + let result; + #[block] + { + result = BenchEnv::seal0_set_transient_storage( + &mut runtime, + &mut memory, + 0, // key_ptr + max_key_len, // key_len + max_key_len, // value_ptr + n, // value_len + ); + } + + assert_ok!(result); + assert_eq!(runtime.ext().get_transient_storage(&key).unwrap(), value); + Ok(()) + } + + #[benchmark(pov_mode = Measured)] + fn seal_clear_transient_storage( + n: Linear<0, { T::Schedule::get().limits.payload_len }>, + ) -> Result<(), BenchmarkError> { + let max_key_len = T::MaxStorageKeyLen::get(); + let key = Key::::try_from_var(vec![0u8; max_key_len as usize]) + .map_err(|_| "Key has wrong length")?; + build_runtime!(runtime, memory: [ key.to_vec(), ]); + runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX; + runtime + .ext() + .set_transient_storage(&key, Some(vec![42u8; n as usize]), false) + .map_err(|_| "Failed to write to transient storage during setup.")?; + + let result; + #[block] + { + result = + BenchEnv::seal0_clear_transient_storage(&mut runtime, &mut memory, 0, max_key_len); + } + + assert_ok!(result); + assert!(runtime.ext().get_transient_storage(&key).is_none()); + Ok(()) + } + + #[benchmark(pov_mode = Measured)] + fn seal_get_transient_storage( + n: Linear<0, { T::Schedule::get().limits.payload_len }>, + ) -> Result<(), BenchmarkError> { + let max_key_len = T::MaxStorageKeyLen::get(); + let key = Key::::try_from_var(vec![0u8; max_key_len as usize]) + .map_err(|_| "Key has wrong length")?; + build_runtime!(runtime, memory: [ key.to_vec(), n.to_le_bytes(), vec![0u8; n as _], ]); + runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX; + runtime + .ext() + .set_transient_storage(&key, Some(vec![42u8; n as usize]), false) + .map_err(|_| "Failed to write to transient storage during setup.")?; + + let out_ptr = max_key_len + 4; + let result; + #[block] + { + result = BenchEnv::seal0_get_transient_storage( + &mut runtime, + &mut memory, + 0, // key_ptr + max_key_len, // key_len + out_ptr, // out_ptr + max_key_len, // out_len_ptr + ); + } + + assert_ok!(result); + assert_eq!( + &runtime.ext().get_transient_storage(&key).unwrap(), + &memory[out_ptr as usize..] + ); + Ok(()) + } + + #[benchmark(pov_mode = Measured)] + fn seal_contains_transient_storage( + n: Linear<0, { T::Schedule::get().limits.payload_len }>, + ) -> Result<(), BenchmarkError> { + let max_key_len = T::MaxStorageKeyLen::get(); + let key = Key::::try_from_var(vec![0u8; max_key_len as usize]) + .map_err(|_| "Key has wrong length")?; + build_runtime!(runtime, memory: [ key.to_vec(), ]); + runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX; + runtime + .ext() + .set_transient_storage(&key, Some(vec![42u8; n as usize]), false) + .map_err(|_| "Failed to write to transient storage during setup.")?; + + let result; + #[block] + { + result = BenchEnv::seal0_contains_transient_storage( + &mut runtime, + &mut memory, + 0, + max_key_len, + ); + } + + assert_eq!(result.unwrap(), n); + Ok(()) + } + + #[benchmark(pov_mode = Measured)] + fn seal_take_transient_storage( + n: Linear<0, { T::Schedule::get().limits.payload_len }>, + ) -> Result<(), BenchmarkError> { + let n = T::Schedule::get().limits.payload_len; + let max_key_len = T::MaxStorageKeyLen::get(); + let key = Key::::try_from_var(vec![0u8; max_key_len as usize]) + .map_err(|_| "Key has wrong length")?; + build_runtime!(runtime, memory: [ key.to_vec(), n.to_le_bytes(), vec![0u8; n as _], ]); + runtime.ext().transient_storage().meter().current_mut().limit = u32::MAX; + let value = vec![42u8; n as usize]; + runtime + .ext() + .set_transient_storage(&key, Some(value.clone()), false) + .map_err(|_| "Failed to write to transient storage during setup.")?; + + let out_ptr = max_key_len + 4; + let result; + #[block] + { + result = BenchEnv::seal0_take_transient_storage( + &mut runtime, + &mut memory, + 0, // key_ptr + max_key_len, // key_len + out_ptr, // out_ptr + max_key_len, // out_len_ptr + ); + } + + assert_ok!(result); + assert!(&runtime.ext().get_transient_storage(&key).is_none()); + assert_eq!(&value, &memory[out_ptr as usize..]); + Ok(()) + } + // We transfer to unique accounts. #[benchmark(pov_mode = Measured)] fn seal_transfer() { diff --git a/substrate/frame/contracts/src/chain_extension.rs b/substrate/frame/contracts/src/chain_extension.rs index f3a67fcb09a086cd44a890e749ca6f209a47db80..b9bb451fd734abf9b8cd15561cd89e08980836b2 100644 --- a/substrate/frame/contracts/src/chain_extension.rs +++ b/substrate/frame/contracts/src/chain_extension.rs @@ -74,17 +74,18 @@ use crate::{ wasm::{Runtime, RuntimeCosts}, Error, }; +use alloc::vec::Vec; use codec::{Decode, MaxEncodedLen}; +use core::marker::PhantomData; use frame_support::weights::Weight; use sp_runtime::DispatchError; -use sp_std::{marker::PhantomData, vec::Vec}; pub use crate::{exec::Ext, gas::ChargedAmount, storage::meter::Diff, Config}; pub use frame_system::Config as SysConfig; pub use pallet_contracts_uapi::ReturnFlags; /// Result that returns a [`DispatchError`] on error. -pub type Result = sp_std::result::Result; +pub type Result = core::result::Result; /// A trait used to extend the set of contract callable functions. /// diff --git a/substrate/frame/contracts/src/exec.rs b/substrate/frame/contracts/src/exec.rs index 84a3f7dc2a1405626011fb1b4127ab834088e09c..31e0bf50b73e7de2131fac77487de1c421cabb3e 100644 --- a/substrate/frame/contracts/src/exec.rs +++ b/substrate/frame/contracts/src/exec.rs @@ -20,10 +20,13 @@ use crate::{ gas::GasMeter, primitives::{ExecReturnValue, StorageDeposit}, storage::{self, meter::Diff, WriteOutcome}, + transient_storage::TransientStorage, BalanceOf, CodeHash, CodeInfo, CodeInfoOf, Config, ContractInfo, ContractInfoOf, DebugBufferVec, Determinism, Error, Event, Nonce, Origin, Pallet as Contracts, Schedule, LOG_TARGET, }; +use alloc::vec::Vec; +use core::{fmt::Debug, marker::PhantomData, mem}; use frame_support::{ crypto::ecdsa::ECDSAExt, dispatch::{DispatchResult, DispatchResultWithPostInfo}, @@ -49,7 +52,6 @@ use sp_runtime::{ traits::{Convert, Dispatchable, Zero}, DispatchError, }; -use sp_std::{fmt::Debug, marker::PhantomData, mem, prelude::*, vec::Vec}; pub type AccountIdOf = ::AccountId; pub type MomentOf = <::Time as Time>::Moment; @@ -209,6 +211,27 @@ pub trait Ext: sealing::Sealed { take_old: bool, ) -> Result; + /// Returns the transient storage entry of the executing account for the given `key`. + /// + /// Returns `None` if the `key` wasn't previously set by `set_transient_storage` or + /// was deleted. + fn get_transient_storage(&self, key: &Key) -> Option>; + + /// Returns `Some(len)` (in bytes) if a transient storage item exists at `key`. + /// + /// Returns `None` if the `key` wasn't previously set by `set_transient_storage` or + /// was deleted. + fn get_transient_storage_size(&self, key: &Key) -> Option; + + /// Sets the transient storage entry for the given key to the specified value. If `value` is + /// `None` then the storage entry is deleted. + fn set_transient_storage( + &mut self, + key: &Key, + value: Option>, + take_old: bool, + ) -> Result; + /// Returns the caller. fn caller(&self) -> Origin; @@ -307,6 +330,12 @@ pub trait Ext: sealing::Sealed { #[cfg(any(test, feature = "runtime-benchmarks"))] fn contract_info(&mut self) -> &mut ContractInfo; + /// Get a mutable reference to the transient storage. + /// Useful in benchmarks when it is sometimes necessary to modify and inspect the transient + /// storage directly. + #[cfg(feature = "runtime-benchmarks")] + fn transient_storage(&mut self) -> &mut TransientStorage; + /// Sets new code hash for existing contract. fn set_code_hash(&mut self, hash: CodeHash) -> DispatchResult; @@ -473,6 +502,8 @@ pub struct Stack<'a, T: Config, E> { debug_message: Option<&'a mut DebugBufferVec>, /// The determinism requirement of this call stack. determinism: Determinism, + /// Transient storage used to store data, which is kept for the duration of a transaction. + transient_storage: TransientStorage, /// No executable is held by the struct but influences its behaviour. _phantom: PhantomData, } @@ -796,6 +827,7 @@ where frames: Default::default(), debug_message, determinism, + transient_storage: TransientStorage::new(T::MaxTransientStorageSize::get()), _phantom: Default::default(), }; @@ -926,6 +958,9 @@ where let entry_point = frame.entry_point; let delegated_code_hash = if frame.delegate_caller.is_some() { Some(*executable.code_hash()) } else { None }; + + self.transient_storage.start_transaction(); + let do_transaction = || { // We need to charge the storage deposit before the initial transfer so that // it can create the account in case the initial transfer is < ed. @@ -1046,6 +1081,12 @@ where Err(error) => (false, Err(error.into())), }; + if success { + self.transient_storage.commit_transaction(); + } else { + self.transient_storage.rollback_transaction(); + } + self.pop_frame(success); output } @@ -1185,12 +1226,12 @@ where /// /// The iterator starts with the top frame and ends with the root frame. fn frames(&self) -> impl Iterator> { - sp_std::iter::once(&self.first_frame).chain(&self.frames).rev() + core::iter::once(&self.first_frame).chain(&self.frames).rev() } /// Same as `frames` but with a mutable reference as iterator item. fn frames_mut(&mut self) -> impl Iterator> { - sp_std::iter::once(&mut self.first_frame).chain(&mut self.frames).rev() + core::iter::once(&mut self.first_frame).chain(&mut self.frames).rev() } /// Returns whether the current contract is on the stack multiple times. @@ -1374,6 +1415,24 @@ where ) } + fn get_transient_storage(&self, key: &Key) -> Option> { + self.transient_storage.read(self.address(), key) + } + + fn get_transient_storage_size(&self, key: &Key) -> Option { + self.transient_storage.read(self.address(), key).map(|value| value.len() as _) + } + + fn set_transient_storage( + &mut self, + key: &Key, + value: Option>, + take_old: bool, + ) -> Result { + let account_id = self.address().clone(); + self.transient_storage.write(&account_id, key, value, take_old) + } + fn address(&self) -> &T::AccountId { &self.top_frame().account_id } @@ -1518,6 +1577,11 @@ where self.top_frame_mut().contract_info() } + #[cfg(feature = "runtime-benchmarks")] + fn transient_storage(&mut self) -> &mut TransientStorage { + &mut self.transient_storage + } + fn set_code_hash(&mut self, hash: CodeHash) -> DispatchResult { let frame = top_frame_mut!(self); if !E::from_storage(hash, &mut frame.nested_gas)?.is_deterministic() { @@ -3826,6 +3890,262 @@ mod tests { }); } + #[test] + fn set_transient_storage_works() { + let code_hash = MockLoader::insert(Call, |ctx, _| { + // Write + assert_eq!( + ctx.ext.set_transient_storage(&Key::Fix([1; 32]), Some(vec![1, 2, 3]), false), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_transient_storage(&Key::Fix([2; 32]), Some(vec![4, 5, 6]), true), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_transient_storage(&Key::Fix([3; 32]), None, false), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_transient_storage(&Key::Fix([4; 32]), None, true), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_transient_storage(&Key::Fix([5; 32]), Some(vec![]), false), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_transient_storage(&Key::Fix([6; 32]), Some(vec![]), true), + Ok(WriteOutcome::New) + ); + + // Overwrite + assert_eq!( + ctx.ext.set_transient_storage(&Key::Fix([1; 32]), Some(vec![42]), false), + Ok(WriteOutcome::Overwritten(3)) + ); + assert_eq!( + ctx.ext.set_transient_storage(&Key::Fix([2; 32]), Some(vec![48]), true), + Ok(WriteOutcome::Taken(vec![4, 5, 6])) + ); + assert_eq!( + ctx.ext.set_transient_storage(&Key::Fix([3; 32]), None, false), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_transient_storage(&Key::Fix([4; 32]), None, true), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_transient_storage(&Key::Fix([5; 32]), Some(vec![]), false), + Ok(WriteOutcome::Overwritten(0)) + ); + assert_eq!( + ctx.ext.set_transient_storage(&Key::Fix([6; 32]), Some(vec![]), true), + Ok(WriteOutcome::Taken(vec![])) + ); + + exec_success() + }); + + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&BOB, code_hash); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = storage::meter::Meter::new(&contract_origin, None, 0).unwrap(); + assert_ok!(MockStack::run_call( + contract_origin, + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + vec![], + None, + Determinism::Enforced + )); + }); + } + + #[test] + fn get_transient_storage_works() { + // Call stack: BOB -> CHARLIE(success) -> BOB' (success) + let storage_key_1 = &Key::Fix([1; 32]); + let storage_key_2 = &Key::Fix([2; 32]); + let storage_key_3 = &Key::Fix([3; 32]); + let code_bob = MockLoader::insert(Call, |ctx, _| { + if ctx.input_data[0] == 0 { + assert_eq!( + ctx.ext.set_transient_storage(storage_key_1, Some(vec![1, 2]), false), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.call( + Weight::zero(), + BalanceOf::::zero(), + CHARLIE, + 0, + vec![], + true, + false, + ), + exec_success() + ); + assert_eq!(ctx.ext.get_transient_storage(storage_key_1), Some(vec![3])); + assert_eq!(ctx.ext.get_transient_storage(storage_key_2), Some(vec![])); + assert_eq!(ctx.ext.get_transient_storage(storage_key_3), None); + } else { + assert_eq!( + ctx.ext.set_transient_storage(storage_key_1, Some(vec![3]), true), + Ok(WriteOutcome::Taken(vec![1, 2])) + ); + assert_eq!( + ctx.ext.set_transient_storage(storage_key_2, Some(vec![]), false), + Ok(WriteOutcome::New) + ); + } + exec_success() + }); + let code_charlie = MockLoader::insert(Call, |ctx, _| { + assert!(ctx + .ext + .call(Weight::zero(), BalanceOf::::zero(), BOB, 0, vec![99], true, false) + .is_ok()); + // CHARLIE can not read BOB`s storage. + assert_eq!(ctx.ext.get_transient_storage(storage_key_1), None); + exec_success() + }); + + // This one tests passing the input data into a contract via call. + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&BOB, code_bob); + place_contract(&CHARLIE, code_charlie); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + + let result = MockStack::run_call( + contract_origin, + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + vec![0], + None, + Determinism::Enforced, + ); + assert_matches!(result, Ok(_)); + }); + } + + #[test] + fn get_transient_storage_size_works() { + let storage_key_1 = &Key::Fix([1; 32]); + let storage_key_2 = &Key::Fix([2; 32]); + let storage_key_3 = &Key::Fix([3; 32]); + let code_hash = MockLoader::insert(Call, |ctx, _| { + assert_eq!( + ctx.ext.set_transient_storage(storage_key_1, Some(vec![1, 2, 3]), false), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.set_transient_storage(storage_key_2, Some(vec![]), false), + Ok(WriteOutcome::New) + ); + assert_eq!(ctx.ext.get_transient_storage_size(storage_key_1), Some(3)); + assert_eq!(ctx.ext.get_transient_storage_size(storage_key_2), Some(0)); + assert_eq!(ctx.ext.get_transient_storage_size(storage_key_3), None); + + exec_success() + }); + + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&BOB, code_hash); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + assert_ok!(MockStack::run_call( + contract_origin, + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + vec![], + None, + Determinism::Enforced + )); + }); + } + + #[test] + fn rollback_transient_storage_works() { + // Call stack: BOB -> CHARLIE (trap) -> BOB' (success) + let storage_key = &Key::Fix([1; 32]); + let code_bob = MockLoader::insert(Call, |ctx, _| { + if ctx.input_data[0] == 0 { + assert_eq!( + ctx.ext.set_transient_storage(storage_key, Some(vec![1, 2]), false), + Ok(WriteOutcome::New) + ); + assert_eq!( + ctx.ext.call( + Weight::zero(), + BalanceOf::::zero(), + CHARLIE, + 0, + vec![], + true, + false + ), + exec_trapped() + ); + assert_eq!(ctx.ext.get_transient_storage(storage_key), Some(vec![1, 2])); + } else { + let overwritten_length = ctx.ext.get_transient_storage_size(storage_key).unwrap(); + assert_eq!( + ctx.ext.set_transient_storage(storage_key, Some(vec![3]), false), + Ok(WriteOutcome::Overwritten(overwritten_length)) + ); + assert_eq!(ctx.ext.get_transient_storage(storage_key), Some(vec![3])); + } + exec_success() + }); + let code_charlie = MockLoader::insert(Call, |ctx, _| { + assert!(ctx + .ext + .call(Weight::zero(), BalanceOf::::zero(), BOB, 0, vec![99], true, false) + .is_ok()); + exec_trapped() + }); + + // This one tests passing the input data into a contract via call. + ExtBuilder::default().build().execute_with(|| { + let schedule = ::Schedule::get(); + place_contract(&BOB, code_bob); + place_contract(&CHARLIE, code_charlie); + let contract_origin = Origin::from_account_id(ALICE); + let mut storage_meter = + storage::meter::Meter::new(&contract_origin, Some(0), 0).unwrap(); + + let result = MockStack::run_call( + contract_origin, + BOB, + &mut GasMeter::::new(GAS_LIMIT), + &mut storage_meter, + &schedule, + 0, + vec![0], + None, + Determinism::Enforced, + ); + assert_matches!(result, Ok(_)); + }); + } + #[test] fn ecdsa_to_eth_address_returns_proper_value() { let bob_ch = MockLoader::insert(Call, |ctx, _| { diff --git a/substrate/frame/contracts/src/lib.rs b/substrate/frame/contracts/src/lib.rs index 47772e0a5a0bc34ff3662cdb1bc5211b44032e40..093adc07ab48b49d5d08f70c9cb6745d36c77906 100644 --- a/substrate/frame/contracts/src/lib.rs +++ b/substrate/frame/contracts/src/lib.rs @@ -87,6 +87,7 @@ #![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(feature = "runtime-benchmarks", recursion_limit = "1024")] +extern crate alloc; mod address; mod benchmarking; mod exec; @@ -96,6 +97,7 @@ pub use primitives::*; mod schedule; mod storage; +mod transient_storage; mod wasm; pub mod chain_extension; @@ -115,11 +117,11 @@ use crate::{ wasm::{CodeInfo, WasmBlob}, }; use codec::{Codec, Decode, Encode, HasCompact, MaxEncodedLen}; +use core::fmt::Debug; use environmental::*; use frame_support::{ dispatch::{GetDispatchInfo, Pays, PostDispatchInfo, RawOrigin, WithPostDispatchInfo}, ensure, - error::BadOrigin, traits::{ fungible::{Inspect, Mutate, MutateHold}, ConstU32, Contains, Get, Randomness, Time, @@ -135,10 +137,9 @@ use frame_system::{ use scale_info::TypeInfo; use smallvec::Array; use sp_runtime::{ - traits::{Convert, Dispatchable, Saturating, StaticLookup, Zero}, + traits::{BadOrigin, Convert, Dispatchable, Saturating, StaticLookup, Zero}, DispatchError, RuntimeDebug, }; -use sp_std::{fmt::Debug, prelude::*}; pub use crate::{ address::{AddressGenerator, DefaultAddressGenerator}, @@ -388,6 +389,11 @@ pub mod pallet { #[pallet::constant] type MaxStorageKeyLen: Get; + /// The maximum size of the transient storage in bytes. + /// This includes keys, values, and previous entries used for storage rollback. + #[pallet::constant] + type MaxTransientStorageSize: Get; + /// The maximum number of delegate_dependencies that a contract can lock with /// [`chain_extension::Ext::lock_delegate_dependency`]. #[pallet::constant] @@ -554,6 +560,7 @@ pub mod pallet { type MaxDebugBufferLen = ConstU32<{ 2 * 1024 * 1024 }>; type MaxDelegateDependencies = MaxDelegateDependencies; type MaxStorageKeyLen = ConstU32<128>; + type MaxTransientStorageSize = ConstU32<{ 1 * 1024 * 1024 }>; type Migrations = (); type Time = Self; type Randomness = Self; @@ -605,7 +612,11 @@ pub mod pallet { // Max call depth is CallStack::size() + 1 let max_call_depth = u32::try_from(T::CallStack::size().saturating_add(1)) .expect("CallStack size is too big"); - + // Transient storage uses a BTreeMap, which has overhead compared to the raw size of + // key-value data. To ensure safety, a margin of 2x the raw key-value size is used. + let max_transient_storage_size = T::MaxTransientStorageSize::get() + .checked_mul(2) + .expect("MaxTransientStorageSize is too large"); // Check that given configured `MaxCodeLen`, runtime heap memory limit can't be broken. // // In worst case, the decoded Wasm contract code would be `x16` times larger than the @@ -615,7 +626,7 @@ pub mod pallet { // Next, the pallet keeps the Wasm blob for each // contract, hence we add up `MaxCodeLen` to the safety margin. // - // Finally, the inefficiencies of the freeing-bump allocator + // The inefficiencies of the freeing-bump allocator // being used in the client for the runtime memory allocations, could lead to possible // memory allocations for contract code grow up to `x4` times in some extreme cases, // which gives us total multiplier of `17*4` for `MaxCodeLen`. @@ -624,17 +635,20 @@ pub mod pallet { // memory should be available. Note that maximum allowed heap memory and stack size per // each contract (stack frame) should also be counted. // + // The pallet holds transient storage with a size up to `max_transient_storage_size`. + // // Finally, we allow 50% of the runtime memory to be utilized by the contracts call // stack, keeping the rest for other facilities, such as PoV, etc. // // This gives us the following formula: // - // `(MaxCodeLen * 17 * 4 + MAX_STACK_SIZE + max_heap_size) * max_call_depth < - // max_runtime_mem/2` + // `(MaxCodeLen * 17 * 4 + MAX_STACK_SIZE + max_heap_size) * max_call_depth + + // max_transient_storage_size < max_runtime_mem/2` // // Hence the upper limit for the `MaxCodeLen` can be defined as follows: let code_len_limit = max_runtime_mem .saturating_div(2) + .saturating_sub(max_transient_storage_size) .saturating_div(max_call_depth) .saturating_sub(max_heap_size) .saturating_sub(MAX_STACK_SIZE) @@ -1235,6 +1249,8 @@ pub mod pallet { DelegateDependencyAlreadyExists, /// Can not add a delegate dependency to the code hash of the contract itself. CannotAddSelfAsDelegateDependency, + /// Can not add more data to transient storage. + OutOfTransientStorage, } /// A reason for the pallet contracts placing a hold on funds. diff --git a/substrate/frame/contracts/src/migration.rs b/substrate/frame/contracts/src/migration.rs index c633ba9c2d50d6bf31da965cd6cd4638d048fb6b..29ac74d0d50a972f746c9219bff7f8d2f277b1fa 100644 --- a/substrate/frame/contracts/src/migration.rs +++ b/substrate/frame/contracts/src/migration.rs @@ -69,17 +69,16 @@ include!(concat!(env!("OUT_DIR"), "/migration_codegen.rs")); use crate::{weights::WeightInfo, Config, Error, MigrationInProgress, Pallet, Weight, LOG_TARGET}; use codec::{Codec, Decode}; +use core::marker::PhantomData; use frame_support::{ pallet_prelude::*, traits::{ConstU32, OnRuntimeUpgrade}, weights::WeightMeter, }; use sp_runtime::Saturating; -use sp_std::marker::PhantomData; #[cfg(feature = "try-runtime")] -use sp_std::prelude::*; - +use alloc::vec::Vec; #[cfg(feature = "try-runtime")] use sp_runtime::TryRuntimeError; @@ -604,7 +603,7 @@ mod test { let mut meter = WeightMeter::with_limit(Weight::from_all(1)); let result = Migrations::steps(version, &cursor, &mut meter); - cursor = vec![1u8, 0].try_into().unwrap(); + cursor = alloc::vec![1u8, 0].try_into().unwrap(); assert_eq!(result, StepResult::InProgress { cursor: cursor.clone(), steps_done: 1 }); assert_eq!(meter.consumed(), Weight::from_all(1)); diff --git a/substrate/frame/contracts/src/migration/v09.rs b/substrate/frame/contracts/src/migration/v09.rs index 7e84191910d9f244d8b3ec98439835f311fbfe10..6a67395174f5d002f3a9bc4b1a563000df271571 100644 --- a/substrate/frame/contracts/src/migration/v09.rs +++ b/substrate/frame/contracts/src/migration/v09.rs @@ -22,13 +22,13 @@ use crate::{ weights::WeightInfo, CodeHash, Config, Determinism, Pallet, Weight, LOG_TARGET, }; +use alloc::vec::Vec; use codec::{Decode, Encode}; use frame_support::{ pallet_prelude::*, storage_alias, weights::WeightMeter, DefaultNoBound, Identity, }; #[cfg(feature = "try-runtime")] use sp_runtime::TryRuntimeError; -use sp_std::prelude::*; mod v8 { use super::*; @@ -56,7 +56,7 @@ pub fn store_old_dummy_code(len: usize) { instruction_weights_version: 0, initial: 0, maximum: 0, - code: vec![42u8; len], + code: alloc::vec![42u8; len], }; let hash = T::Hashing::hash(&module.code); v8::CodeStorage::::insert(hash, module); diff --git a/substrate/frame/contracts/src/migration/v10.rs b/substrate/frame/contracts/src/migration/v10.rs index 61632a1fd1bad99fd3f80972f2b1defddb6d4462..23e7fd238bb7c6310fb0f047ab5e42f2c7c58121 100644 --- a/substrate/frame/contracts/src/migration/v10.rs +++ b/substrate/frame/contracts/src/migration/v10.rs @@ -40,13 +40,15 @@ use frame_support::{ DefaultNoBound, }; use sp_core::hexdisplay::HexDisplay; -#[cfg(feature = "try-runtime")] -use sp_runtime::TryRuntimeError; use sp_runtime::{ traits::{Hash, TrailingZeroInput, Zero}, Perbill, Saturating, }; -use sp_std::prelude::*; + +#[cfg(feature = "try-runtime")] +use alloc::vec::Vec; +#[cfg(feature = "try-runtime")] +use sp_runtime::TryRuntimeError; mod v9 { use super::*; diff --git a/substrate/frame/contracts/src/migration/v11.rs b/substrate/frame/contracts/src/migration/v11.rs index 9b4316162ca62a9a9d4e1c3f9b1a912f97122293..bd128e22869f43d8002d155e4f665f7aa7628368 100644 --- a/substrate/frame/contracts/src/migration/v11.rs +++ b/substrate/frame/contracts/src/migration/v11.rs @@ -23,11 +23,13 @@ use crate::{ weights::WeightInfo, Config, Pallet, TrieId, Weight, LOG_TARGET, }; +use alloc::vec::Vec; use codec::{Decode, Encode}; +use core::marker::PhantomData; use frame_support::{pallet_prelude::*, storage_alias, weights::WeightMeter, DefaultNoBound}; #[cfg(feature = "try-runtime")] use sp_runtime::TryRuntimeError; -use sp_std::{marker::PhantomData, prelude::*}; + mod v10 { use super::*; diff --git a/substrate/frame/contracts/src/migration/v12.rs b/substrate/frame/contracts/src/migration/v12.rs index aad51a9edcab21ba408065ab5ddce75561f97f79..3c33591e435147abf2fbacc7013d2c40cadf33b2 100644 --- a/substrate/frame/contracts/src/migration/v12.rs +++ b/substrate/frame/contracts/src/migration/v12.rs @@ -23,6 +23,7 @@ use crate::{ weights::WeightInfo, AccountIdOf, BalanceOf, CodeHash, Config, Determinism, Pallet, Weight, LOG_TARGET, }; +use alloc::vec::Vec; use codec::{Decode, Encode}; use frame_support::{ pallet_prelude::*, storage_alias, traits::ReservableCurrency, weights::WeightMeter, @@ -33,7 +34,6 @@ use sp_core::hexdisplay::HexDisplay; #[cfg(feature = "try-runtime")] use sp_runtime::TryRuntimeError; use sp_runtime::{traits::Zero, FixedPointNumber, FixedU128, Saturating}; -use sp_std::prelude::*; mod v11 { use super::*; @@ -109,7 +109,7 @@ where { use sp_runtime::traits::Hash; - let code = vec![42u8; len]; + let code = alloc::vec![42u8; len]; let hash = T::Hashing::hash(&code); PristineCode::::insert(hash, code.clone()); diff --git a/substrate/frame/contracts/src/migration/v13.rs b/substrate/frame/contracts/src/migration/v13.rs index 6929bbce28e59f9032722b43b335a31da5cf485c..d1888b338dac74e87821d08b9b359841654e730e 100644 --- a/substrate/frame/contracts/src/migration/v13.rs +++ b/substrate/frame/contracts/src/migration/v13.rs @@ -26,7 +26,6 @@ use crate::{ use codec::{Decode, Encode}; use frame_support::{pallet_prelude::*, storage_alias, weights::WeightMeter, DefaultNoBound}; use sp_runtime::BoundedBTreeMap; -use sp_std::prelude::*; mod v12 { use super::*; diff --git a/substrate/frame/contracts/src/migration/v14.rs b/substrate/frame/contracts/src/migration/v14.rs index 017fd6d0c15b74cc8f4fe95d1faa23e91c3e6d5a..11336fe2e7d35828fbe2b548bc882273d44b8a03 100644 --- a/substrate/frame/contracts/src/migration/v14.rs +++ b/substrate/frame/contracts/src/migration/v14.rs @@ -26,6 +26,8 @@ use crate::{ weights::WeightInfo, BalanceOf, CodeHash, Config, Determinism, HoldReason, Pallet, Weight, LOG_TARGET, }; +#[cfg(feature = "try-runtime")] +use alloc::collections::btree_map::BTreeMap; use codec::{Decode, Encode}; #[cfg(feature = "try-runtime")] use environmental::Vec; @@ -42,8 +44,6 @@ use sp_core::hexdisplay::HexDisplay; #[cfg(feature = "try-runtime")] use sp_runtime::TryRuntimeError; use sp_runtime::{traits::Zero, Saturating}; -#[cfg(feature = "try-runtime")] -use sp_std::collections::btree_map::BTreeMap; mod v13 { use super::*; @@ -80,8 +80,8 @@ where T: Config, OldCurrency: ReservableCurrency<::AccountId> + 'static, { + use alloc::vec; use sp_runtime::traits::Hash; - use sp_std::vec; let len = T::MaxCodeLen::get(); let code = vec![42u8; len as usize]; diff --git a/substrate/frame/contracts/src/migration/v15.rs b/substrate/frame/contracts/src/migration/v15.rs index 3c700d1c0b021e1f4066d2c5993e39589924e6b7..11f07282d5614547713a863dd344d11ef4fc4b2f 100644 --- a/substrate/frame/contracts/src/migration/v15.rs +++ b/substrate/frame/contracts/src/migration/v15.rs @@ -28,6 +28,8 @@ use crate::{ AccountIdOf, BalanceOf, CodeHash, Config, HoldReason, Pallet, TrieId, Weight, LOG_TARGET, }; #[cfg(feature = "try-runtime")] +use alloc::vec::Vec; +#[cfg(feature = "try-runtime")] use frame_support::traits::fungible::InspectHold; use frame_support::{ pallet_prelude::*, @@ -44,8 +46,6 @@ use sp_core::hexdisplay::HexDisplay; #[cfg(feature = "try-runtime")] use sp_runtime::TryRuntimeError; use sp_runtime::{traits::Zero, Saturating}; -#[cfg(feature = "try-runtime")] -use sp_std::vec::Vec; mod v14 { use super::*; diff --git a/substrate/frame/contracts/src/migration/v16.rs b/substrate/frame/contracts/src/migration/v16.rs index 74fbc997718d6fb6e13193c5735ea3aa074dfd79..3d5b2d2a85fcd4689279cedf376b65c5f15b9eff 100644 --- a/substrate/frame/contracts/src/migration/v16.rs +++ b/substrate/frame/contracts/src/migration/v16.rs @@ -26,7 +26,6 @@ use crate::{ use codec::{Decode, Encode}; use frame_support::{pallet_prelude::*, storage_alias, DefaultNoBound}; use sp_runtime::{BoundedBTreeMap, Saturating}; -use sp_std::prelude::*; #[cfg(feature = "runtime-benchmarks")] pub fn store_old_contract_info( diff --git a/substrate/frame/contracts/src/primitives.rs b/substrate/frame/contracts/src/primitives.rs index ab73b28e8c49ffc0076d0b0792b5750e41be74f3..622a69f529fb50f501fd53da826fc465d3915e2d 100644 --- a/substrate/frame/contracts/src/primitives.rs +++ b/substrate/frame/contracts/src/primitives.rs @@ -17,6 +17,7 @@ //! A crate that hosts a common definitions that are relevant for the pallet-contracts. +use alloc::vec::Vec; use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::weights::Weight; use pallet_contracts_uapi::ReturnFlags; @@ -25,7 +26,6 @@ use sp_runtime::{ traits::{Saturating, Zero}, DispatchError, RuntimeDebug, }; -use sp_std::prelude::*; /// Result type of a `bare_call` or `bare_instantiate` call as well as `ContractsApi::call` and /// `ContractsApi::instantiate`. diff --git a/substrate/frame/contracts/src/storage.rs b/substrate/frame/contracts/src/storage.rs index 1e9739a1599eb8cc8137f2f0fabec8dd14d64b3a..65e7129cdf8456b934df582327da0d691c0c16b4 100644 --- a/substrate/frame/contracts/src/storage.rs +++ b/substrate/frame/contracts/src/storage.rs @@ -25,7 +25,9 @@ use crate::{ BalanceOf, CodeHash, CodeInfo, Config, ContractInfoOf, DeletionQueue, DeletionQueueCounter, Error, TrieId, SENTINEL, }; +use alloc::vec::Vec; use codec::{Decode, Encode, MaxEncodedLen}; +use core::marker::PhantomData; use frame_support::{ storage::child::{self, ChildInfo}, weights::{Weight, WeightMeter}, @@ -38,7 +40,6 @@ use sp_runtime::{ traits::{Hash, Saturating, Zero}, BoundedBTreeMap, DispatchError, DispatchResult, RuntimeDebug, }; -use sp_std::{marker::PhantomData, prelude::*}; use self::meter::Diff; @@ -334,7 +335,7 @@ impl ContractInfo { } /// Information about what happened to the pre-existing value when calling [`ContractInfo::write`]. -#[cfg_attr(test, derive(Debug, PartialEq))] +#[cfg_attr(any(test, feature = "runtime-benchmarks"), derive(Debug, PartialEq))] pub enum WriteOutcome { /// No value existed at the specified key. New, diff --git a/substrate/frame/contracts/src/storage/meter.rs b/substrate/frame/contracts/src/storage/meter.rs index 7c55ce5d3f0c4acda7af2d35741a7b155933b11f..951cb25994e1f7b517fb93e7f4817c3bbf8d2a17 100644 --- a/substrate/frame/contracts/src/storage/meter.rs +++ b/substrate/frame/contracts/src/storage/meter.rs @@ -22,6 +22,8 @@ use crate::{ Inspect, Origin, Pallet, StorageDeposit as Deposit, System, LOG_TARGET, }; +use alloc::vec::Vec; +use core::{fmt::Debug, marker::PhantomData}; use frame_support::{ ensure, traits::{ @@ -37,7 +39,6 @@ use sp_runtime::{ traits::{Saturating, Zero}, DispatchError, FixedPointNumber, FixedU128, }; -use sp_std::{fmt::Debug, marker::PhantomData, vec::Vec}; /// Deposit that uses the native fungible's balance type. pub type DepositOf = Deposit>; diff --git a/substrate/frame/contracts/src/tests.rs b/substrate/frame/contracts/src/tests.rs index c20577a3f6458ef66886b6c1f29346ad31fb049c..cc2a69b5c419654ce45aacf8f9d5775546d7f19f 100644 --- a/substrate/frame/contracts/src/tests.rs +++ b/substrate/frame/contracts/src/tests.rs @@ -411,6 +411,7 @@ parameter_types! { pub static DepositPerByte: BalanceOf = 1; pub const DepositPerItem: BalanceOf = 2; pub static MaxDelegateDependencies: u32 = 32; + pub static MaxTransientStorageSize: u32 = 4 * 1024; pub static CodeHashLockupDepositPercent: Perbill = Perbill::from_percent(0); // We need this one set high enough for running benchmarks. @@ -458,7 +459,7 @@ parameter_types! { pub static InstantiateAccount: Option<::AccountId> = None; } -pub struct EnsureAccount(sp_std::marker::PhantomData<(T, A)>); +pub struct EnsureAccount(core::marker::PhantomData<(T, A)>); impl>>> EnsureOrigin<::RuntimeOrigin> for EnsureAccount where @@ -504,6 +505,7 @@ impl Config for Test { type Migrations = crate::migration::codegen::BenchMigrations; type CodeHashLockupDepositPercent = CodeHashLockupDepositPercent; type MaxDelegateDependencies = MaxDelegateDependencies; + type MaxTransientStorageSize = MaxTransientStorageSize; type Debug = TestDebug; } @@ -962,6 +964,68 @@ fn storage_max_value_limit() { }); } +#[test] +fn transient_storage_work() { + let (code, _code_hash) = compile_module::("transient_storage").unwrap(); + + ExtBuilder::default().build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let min_balance = Contracts::min_balance(); + let addr = builder::bare_instantiate(Code::Upload(code)) + .value(min_balance * 100) + .build_and_unwrap_account_id(); + + builder::bare_call(addr).build_and_unwrap_result(); + }); +} + +#[test] +fn transient_storage_limit_in_call() { + let (wasm_caller, _code_hash_caller) = + compile_module::("create_transient_storage_and_call").unwrap(); + let (wasm_callee, _code_hash_callee) = compile_module::("set_transient_storage").unwrap(); + ExtBuilder::default().build().execute_with(|| { + let _ = ::Currency::set_balance(&ALICE, 1_000_000); + let min_balance = Contracts::min_balance(); + + // Create both contracts: Constructors do nothing. + let addr_caller = builder::bare_instantiate(Code::Upload(wasm_caller)) + .value(min_balance * 100) + .build_and_unwrap_account_id(); + let addr_callee = builder::bare_instantiate(Code::Upload(wasm_callee)) + .value(min_balance * 100) + .build_and_unwrap_account_id(); + + let storage_value_size = 1000; + MaxTransientStorageSize::set(4 * 1024); + // Call contracts with storage values within the limit. + // Caller and Callee contracts each set a transient storage value of size 1000. + assert_ok!(builder::call(addr_caller.clone()) + .data((storage_value_size, storage_value_size, &addr_callee).encode()) + .build(),); + + MaxTransientStorageSize::set(512); + // Call a contract with a storage value that is too large. + // Limit exceeded in the caller contract. + assert_err_ignore_postinfo!( + builder::call(addr_caller.clone()) + .data((storage_value_size, storage_value_size, &addr_callee).encode()) + .build(), + >::OutOfTransientStorage, + ); + + MaxTransientStorageSize::set(1536); + // Call a contract with a storage value that is too large. + // Limit exceeded in the callee contract. + assert_err_ignore_postinfo!( + builder::call(addr_caller) + .data((storage_value_size, storage_value_size, &addr_callee).encode()) + .build(), + >::ContractTrapped + ); + }); +} + #[test] fn deploy_and_call_other_contract() { let (caller_wasm, _caller_code_hash) = compile_module::("caller_contract").unwrap(); diff --git a/substrate/frame/contracts/src/transient_storage.rs b/substrate/frame/contracts/src/transient_storage.rs new file mode 100644 index 0000000000000000000000000000000000000000..c795a966385a92572958cf67202e4d7f5b36e85c --- /dev/null +++ b/substrate/frame/contracts/src/transient_storage.rs @@ -0,0 +1,698 @@ +// This file is part of Substrate. + +// Copyright (C) Parity Technologies (UK) Ltd. +// SPDX-License-Identifier: Apache-2.0 + +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! This module contains routines for accessing and altering a contract transient storage. + +use crate::{ + exec::{AccountIdOf, Key}, + storage::WriteOutcome, + Config, Error, +}; +use codec::Encode; +use core::marker::PhantomData; +use frame_support::DefaultNoBound; +use sp_runtime::{DispatchError, DispatchResult, Saturating}; +use sp_std::{collections::btree_map::BTreeMap, mem, vec::Vec}; + +/// Meter entry tracks transaction allocations. +#[derive(Default, Debug)] +pub struct MeterEntry { + /// Allocations made in the current transaction. + pub amount: u32, + /// Allocations limit in the current transaction. + pub limit: u32, +} + +impl MeterEntry { + /// Create a new entry. + fn new(limit: u32) -> Self { + Self { limit, amount: Default::default() } + } + + /// Check if the allocated amount exceeds the limit. + fn exceeds_limit(&self, amount: u32) -> bool { + self.amount.saturating_add(amount) > self.limit + } + + /// Absorb the allocation amount of the nested entry into the current entry. + fn absorb(&mut self, rhs: Self) { + self.amount.saturating_accrue(rhs.amount) + } +} + +// The storage meter enforces a limit for each transaction, +// which is calculated as free_storage * (1 - 1/16) for each subsequent frame. +#[derive(DefaultNoBound)] +pub struct StorageMeter { + nested_meters: Vec, + root_meter: MeterEntry, + _phantom: PhantomData, +} + +impl StorageMeter { + const STORAGE_FRACTION_DENOMINATOR: u32 = 16; + /// Create a new storage allocation meter. + fn new(memory_limit: u32) -> Self { + Self { root_meter: MeterEntry::new(memory_limit), ..Default::default() } + } + + /// Charge the allocated amount of transaction storage from the meter. + fn charge(&mut self, amount: u32) -> DispatchResult { + let meter = self.current_mut(); + if meter.exceeds_limit(amount) { + return Err(Error::::OutOfTransientStorage.into()); + } + meter.amount.saturating_accrue(amount); + Ok(()) + } + + /// Revert a transaction meter. + fn revert(&mut self) { + self.nested_meters.pop().expect( + "A call to revert a meter must be preceded by a corresponding call to start a meter; + the code within this crate makes sure that this is always the case; qed", + ); + } + + /// Start a transaction meter. + fn start(&mut self) { + let meter = self.current(); + let mut transaction_limit = meter.limit.saturating_sub(meter.amount); + if !self.nested_meters.is_empty() { + // Allow use of (1 - 1/STORAGE_FRACTION_DENOMINATOR) of free storage for subsequent + // calls. + transaction_limit.saturating_reduce( + transaction_limit.saturating_div(Self::STORAGE_FRACTION_DENOMINATOR), + ); + } + + self.nested_meters.push(MeterEntry::new(transaction_limit)); + } + + /// Commit a transaction meter. + fn commit(&mut self) { + let transaction_meter = self.nested_meters.pop().expect( + "A call to commit a meter must be preceded by a corresponding call to start a meter; + the code within this crate makes sure that this is always the case; qed", + ); + self.current_mut().absorb(transaction_meter) + } + + /// The total allocated amount of memory. + #[cfg(test)] + fn total_amount(&self) -> u32 { + self.nested_meters + .iter() + .fold(self.root_meter.amount, |acc, e| acc.saturating_add(e.amount)) + } + + /// A mutable reference to the current meter entry. + pub fn current_mut(&mut self) -> &mut MeterEntry { + self.nested_meters.last_mut().unwrap_or(&mut self.root_meter) + } + + /// A reference to the current meter entry. + pub fn current(&self) -> &MeterEntry { + self.nested_meters.last().unwrap_or(&self.root_meter) + } +} + +/// An entry representing a journal change. +struct JournalEntry { + key: Vec, + prev_value: Option>, +} + +impl JournalEntry { + /// Create a new change. + fn new(key: Vec, prev_value: Option>) -> Self { + Self { key, prev_value } + } + + /// Revert the change. + fn revert(self, storage: &mut Storage) { + storage.write(&self.key, self.prev_value); + } +} + +/// A journal containing transient storage modifications. +struct Journal(Vec); + +impl Journal { + /// Create a new journal. + fn new() -> Self { + Self(Default::default()) + } + + /// Add a change to the journal. + fn push(&mut self, entry: JournalEntry) { + self.0.push(entry); + } + + /// Length of the journal. + fn len(&self) -> usize { + self.0.len() + } + + /// Roll back all journal changes until the chackpoint + fn rollback(&mut self, storage: &mut Storage, checkpoint: usize) { + self.0.drain(checkpoint..).rev().for_each(|entry| entry.revert(storage)); + } +} + +/// Storage for maintaining the current transaction state. +#[derive(Default)] +struct Storage(BTreeMap, Vec>); + +impl Storage { + /// Read the storage entry. + fn read(&self, key: &Vec) -> Option> { + self.0.get(key).cloned() + } + + /// Write the storage entry. + fn write(&mut self, key: &Vec, value: Option>) -> Option> { + if let Some(value) = value { + // Insert storage entry. + self.0.insert(key.clone(), value) + } else { + // Remove storage entry. + self.0.remove(key) + } + } +} + +/// Transient storage behaves almost identically to regular storage but is discarded after each +/// transaction. It consists of a `BTreeMap` for the current state, a journal of all changes, and a +/// list of checkpoints. On entry to the `start_transaction` function, a marker (checkpoint) is +/// added to the list. New values are written to the current state, and the previous value is +/// recorded in the journal (`write`). When the `commit_transaction` function is called, the marker +/// to the journal index (checkpoint) of when that call was entered is discarded. +/// On `rollback_transaction`, all entries are reverted up to the last checkpoint. +pub struct TransientStorage { + // The storage and journal size is limited by the storage meter. + storage: Storage, + journal: Journal, + // The size of the StorageMeter is limited by the stack depth. + meter: StorageMeter, + // The size of the checkpoints is limited by the stack depth. + checkpoints: Vec, +} + +impl TransientStorage { + /// Create new transient storage with the supplied memory limit. + pub fn new(memory_limit: u32) -> Self { + TransientStorage { + storage: Default::default(), + journal: Journal::new(), + checkpoints: Default::default(), + meter: StorageMeter::new(memory_limit), + } + } + + /// Read the storage value. If the entry does not exist, `None` is returned. + pub fn read(&self, account: &AccountIdOf, key: &Key) -> Option> { + self.storage.read(&Self::storage_key(&account.encode(), &key.hash())) + } + + /// Write a value to storage. + /// + /// If the `value` is `None`, then the entry is removed. If `take` is true, + /// a [`WriteOutcome::Taken`] is returned instead of a [`WriteOutcome::Overwritten`]. + /// If the entry did not exist, [`WriteOutcome::New`] is returned. + pub fn write( + &mut self, + account: &AccountIdOf, + key: &Key, + value: Option>, + take: bool, + ) -> Result { + let key = Self::storage_key(&account.encode(), &key.hash()); + let prev_value = self.storage.read(&key); + // Skip if the same value is being set. + if prev_value != value { + // Calculate the allocation size. + if let Some(value) = &value { + // Charge the key, value and journal entry. + // If a new value is written, a new journal entry is created. The previous value is + // moved to the journal along with its key, and the new value is written to + // storage. + let key_len = key.capacity(); + let mut amount = value + .capacity() + .saturating_add(key_len) + .saturating_add(mem::size_of::()); + if prev_value.is_none() { + // Charge a new storage entry. + // If there was no previous value, a new entry is added to storage (BTreeMap) + // containing a Vec for the key and a Vec for the value. The value was already + // included in the amount. + amount.saturating_accrue(key_len.saturating_add(mem::size_of::>())); + } + self.meter.charge(amount as _)?; + } + self.storage.write(&key, value); + // Update the journal. + self.journal.push(JournalEntry::new(key, prev_value.clone())); + } + + Ok(match (take, prev_value) { + (_, None) => WriteOutcome::New, + (false, Some(prev_value)) => WriteOutcome::Overwritten(prev_value.len() as _), + (true, Some(prev_value)) => WriteOutcome::Taken(prev_value), + }) + } + + /// Start a new nested transaction. + /// + /// This allows to either commit or roll back all changes that are made after this call. + /// For every transaction there must be a matching call to either `rollback_transaction` + /// or `commit_transaction`. + pub fn start_transaction(&mut self) { + self.meter.start(); + self.checkpoints.push(self.journal.len()); + } + + /// Rollback the last transaction started by `start_transaction`. + /// + /// Any changes made during that transaction are discarded. + /// + /// # Panics + /// + /// Will panic if there is no open transaction. + pub fn rollback_transaction(&mut self) { + let checkpoint = self + .checkpoints + .pop() + .expect( + "A call to rollback_transaction must be preceded by a corresponding call to start_transaction; + the code within this crate makes sure that this is always the case; qed" + ); + self.meter.revert(); + self.journal.rollback(&mut self.storage, checkpoint); + } + + /// Commit the last transaction started by `start_transaction`. + /// + /// Any changes made during that transaction are committed. + /// + /// # Panics + /// + /// Will panic if there is no open transaction. + pub fn commit_transaction(&mut self) { + self.checkpoints + .pop() + .expect( + "A call to commit_transaction must be preceded by a corresponding call to start_transaction; + the code within this crate makes sure that this is always the case; qed" + ); + self.meter.commit(); + } + + /// The storage allocation meter used for transaction metering. + #[cfg(any(test, feature = "runtime-benchmarks"))] + pub fn meter(&mut self) -> &mut StorageMeter { + return &mut self.meter + } + + fn storage_key(account: &[u8], key: &[u8]) -> Vec { + let mut storage_key = Vec::with_capacity(account.len() + key.len()); + storage_key.extend_from_slice(&account); + storage_key.extend_from_slice(&key); + storage_key + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + tests::{Test, ALICE, BOB, CHARLIE}, + Error, + }; + use core::u32::MAX; + + // Calculate the allocation size for the given entry. + fn allocation_size( + account: &AccountIdOf, + key: &Key, + value: Option>, + ) -> u32 { + let mut storage: TransientStorage = TransientStorage::::new(MAX); + storage + .write(account, key, value, false) + .expect("Could not write to transient storage."); + storage.meter().current().amount + } + + #[test] + fn read_write_works() { + let mut storage: TransientStorage = TransientStorage::::new(2048); + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1]), false), + Ok(WriteOutcome::New) + ); + assert_eq!( + storage.write(&ALICE, &Key::Fix([2; 32]), Some(vec![2]), true), + Ok(WriteOutcome::New) + ); + assert_eq!( + storage.write(&BOB, &Key::Fix([3; 32]), Some(vec![3]), false), + Ok(WriteOutcome::New) + ); + assert_eq!(storage.read(&ALICE, &Key::Fix([1; 32])), Some(vec![1])); + assert_eq!(storage.read(&ALICE, &Key::Fix([2; 32])), Some(vec![2])); + assert_eq!(storage.read(&BOB, &Key::Fix([3; 32])), Some(vec![3])); + // Overwrite values. + assert_eq!( + storage.write(&ALICE, &Key::Fix([2; 32]), Some(vec![4, 5]), false), + Ok(WriteOutcome::Overwritten(1)) + ); + assert_eq!( + storage.write(&BOB, &Key::Fix([3; 32]), Some(vec![6, 7]), true), + Ok(WriteOutcome::Taken(vec![3])) + ); + assert_eq!(storage.read(&ALICE, &Key::Fix([1; 32])), Some(vec![1])); + assert_eq!(storage.read(&ALICE, &Key::Fix([2; 32])), Some(vec![4, 5])); + assert_eq!(storage.read(&BOB, &Key::Fix([3; 32])), Some(vec![6, 7])); + + // Check for an empty value. + assert_eq!( + storage.write(&BOB, &Key::Fix([3; 32]), Some(vec![]), true), + Ok(WriteOutcome::Taken(vec![6, 7])) + ); + assert_eq!(storage.read(&BOB, &Key::Fix([3; 32])), Some(vec![])); + + assert_eq!( + storage.write(&BOB, &Key::Fix([3; 32]), None, true), + Ok(WriteOutcome::Taken(vec![])) + ); + assert_eq!(storage.read(&BOB, &Key::Fix([3; 32])), None); + } + + #[test] + fn read_write_with_var_sized_keys_works() { + let mut storage = TransientStorage::::new(2048); + assert_eq!( + storage.write( + &ALICE, + &Key::::try_from_var([1; 64].to_vec()).unwrap(), + Some(vec![1]), + false + ), + Ok(WriteOutcome::New) + ); + assert_eq!( + storage.write( + &BOB, + &Key::::try_from_var([2; 64].to_vec()).unwrap(), + Some(vec![2, 3]), + false + ), + Ok(WriteOutcome::New) + ); + assert_eq!( + storage.read(&ALICE, &Key::::try_from_var([1; 64].to_vec()).unwrap()), + Some(vec![1]) + ); + assert_eq!( + storage.read(&BOB, &Key::::try_from_var([2; 64].to_vec()).unwrap()), + Some(vec![2, 3]) + ); + // Overwrite values. + assert_eq!( + storage.write( + &ALICE, + &Key::::try_from_var([1; 64].to_vec()).unwrap(), + Some(vec![4, 5]), + false + ), + Ok(WriteOutcome::Overwritten(1)) + ); + assert_eq!( + storage.read(&ALICE, &Key::::try_from_var([1; 64].to_vec()).unwrap()), + Some(vec![4, 5]) + ); + } + + #[test] + fn rollback_transaction_works() { + let mut storage = TransientStorage::::new(1024); + + storage.start_transaction(); + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1]), false), + Ok(WriteOutcome::New) + ); + storage.rollback_transaction(); + assert_eq!(storage.read(&ALICE, &Key::Fix([1; 32])), None) + } + + #[test] + fn commit_transaction_works() { + let mut storage = TransientStorage::::new(1024); + + storage.start_transaction(); + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1]), false), + Ok(WriteOutcome::New) + ); + storage.commit_transaction(); + assert_eq!(storage.read(&ALICE, &Key::Fix([1; 32])), Some(vec![1])) + } + + #[test] + fn overwrite_and_commmit_transaction_works() { + let mut storage = TransientStorage::::new(1024); + storage.start_transaction(); + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1]), false), + Ok(WriteOutcome::New) + ); + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1, 2]), false), + Ok(WriteOutcome::Overwritten(1)) + ); + storage.commit_transaction(); + assert_eq!(storage.read(&ALICE, &Key::Fix([1; 32])), Some(vec![1, 2])) + } + + #[test] + fn rollback_in_nested_transaction_works() { + let mut storage = TransientStorage::::new(1024); + storage.start_transaction(); + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1]), false), + Ok(WriteOutcome::New) + ); + storage.start_transaction(); + assert_eq!( + storage.write(&BOB, &Key::Fix([1; 32]), Some(vec![1]), false), + Ok(WriteOutcome::New) + ); + storage.rollback_transaction(); + storage.commit_transaction(); + assert_eq!(storage.read(&ALICE, &Key::Fix([1; 32])), Some(vec![1])); + assert_eq!(storage.read(&BOB, &Key::Fix([1; 32])), None) + } + + #[test] + fn commit_in_nested_transaction_works() { + let mut storage = TransientStorage::::new(1024); + storage.start_transaction(); + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1]), false), + Ok(WriteOutcome::New) + ); + storage.start_transaction(); + assert_eq!( + storage.write(&BOB, &Key::Fix([1; 32]), Some(vec![2]), false), + Ok(WriteOutcome::New) + ); + storage.start_transaction(); + assert_eq!( + storage.write(&CHARLIE, &Key::Fix([1; 32]), Some(vec![3]), false), + Ok(WriteOutcome::New) + ); + storage.commit_transaction(); + storage.commit_transaction(); + storage.commit_transaction(); + assert_eq!(storage.read(&ALICE, &Key::Fix([1; 32])), Some(vec![1])); + assert_eq!(storage.read(&BOB, &Key::Fix([1; 32])), Some(vec![2])); + assert_eq!(storage.read(&CHARLIE, &Key::Fix([1; 32])), Some(vec![3])); + } + + #[test] + fn rollback_all_transactions_works() { + let mut storage = TransientStorage::::new(1024); + storage.start_transaction(); + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1]), false), + Ok(WriteOutcome::New) + ); + storage.start_transaction(); + assert_eq!( + storage.write(&BOB, &Key::Fix([1; 32]), Some(vec![2]), false), + Ok(WriteOutcome::New) + ); + storage.start_transaction(); + assert_eq!( + storage.write(&CHARLIE, &Key::Fix([1; 32]), Some(vec![3]), false), + Ok(WriteOutcome::New) + ); + storage.commit_transaction(); + storage.commit_transaction(); + storage.rollback_transaction(); + assert_eq!(storage.read(&ALICE, &Key::Fix([1; 32])), None); + assert_eq!(storage.read(&BOB, &Key::Fix([1; 32])), None); + assert_eq!(storage.read(&CHARLIE, &Key::Fix([1; 32])), None); + } + + #[test] + fn metering_transactions_works() { + let size = allocation_size(&ALICE, &Key::Fix([1; 32]), Some(vec![1u8; 4096])); + let mut storage = TransientStorage::::new(size * 2); + storage.start_transaction(); + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1u8; 4096]), false), + Ok(WriteOutcome::New) + ); + let limit = storage.meter().current().limit; + storage.commit_transaction(); + + storage.start_transaction(); + assert_eq!(storage.meter().current().limit, limit - size); + assert_eq!(storage.meter().current().limit - storage.meter().current().amount, size); + assert_eq!( + storage.write(&ALICE, &Key::Fix([2; 32]), Some(vec![1u8; 4096]), false), + Ok(WriteOutcome::New) + ); + assert_eq!(storage.meter().current().amount, size); + storage.commit_transaction(); + assert_eq!(storage.meter().total_amount(), size * 2); + } + + #[test] + fn metering_nested_transactions_works() { + let size = allocation_size(&ALICE, &Key::Fix([1; 32]), Some(vec![1u8; 4096])); + let mut storage = TransientStorage::::new(size * 3); + + storage.start_transaction(); + let limit = storage.meter().current().limit; + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1u8; 4096]), false), + Ok(WriteOutcome::New) + ); + storage.start_transaction(); + assert_eq!(storage.meter().total_amount(), size); + assert!(storage.meter().current().limit < limit - size); + assert_eq!( + storage.write(&ALICE, &Key::Fix([2; 32]), Some(vec![1u8; 4096]), false), + Ok(WriteOutcome::New) + ); + storage.commit_transaction(); + assert_eq!(storage.meter().current().limit, limit); + assert_eq!(storage.meter().total_amount(), storage.meter().current().amount); + storage.commit_transaction(); + } + + #[test] + fn metering_transaction_fails() { + let size = allocation_size(&ALICE, &Key::Fix([1; 32]), Some(vec![1u8; 4096])); + let mut storage = TransientStorage::::new(size - 1); + storage.start_transaction(); + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1u8; 4096]), false), + Err(Error::::OutOfTransientStorage.into()) + ); + assert_eq!(storage.meter.current().amount, 0); + storage.commit_transaction(); + assert_eq!(storage.meter.total_amount(), 0); + } + + #[test] + fn metering_nested_transactions_fails() { + let size = allocation_size(&ALICE, &Key::Fix([1; 32]), Some(vec![1u8; 4096])); + let mut storage = TransientStorage::::new(size * 2); + + storage.start_transaction(); + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1u8; 4096]), false), + Ok(WriteOutcome::New) + ); + storage.start_transaction(); + assert_eq!( + storage.write(&ALICE, &Key::Fix([2; 32]), Some(vec![1u8; 4096]), false), + Err(Error::::OutOfTransientStorage.into()) + ); + storage.commit_transaction(); + storage.commit_transaction(); + assert_eq!(storage.meter.total_amount(), size); + } + + #[test] + fn metering_nested_transaction_with_rollback_works() { + let size = allocation_size(&ALICE, &Key::Fix([1; 32]), Some(vec![1u8; 4096])); + let mut storage = TransientStorage::::new(size * 2); + + storage.start_transaction(); + let limit = storage.meter.current().limit; + storage.start_transaction(); + assert_eq!( + storage.write(&ALICE, &Key::Fix([2; 32]), Some(vec![1u8; 4096]), false), + Ok(WriteOutcome::New) + ); + storage.rollback_transaction(); + + assert_eq!(storage.meter.total_amount(), 0); + assert_eq!(storage.meter.current().limit, limit); + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1u8; 4096]), false), + Ok(WriteOutcome::New) + ); + let amount = storage.meter().current().amount; + assert_eq!(storage.meter().total_amount(), amount); + storage.commit_transaction(); + } + + #[test] + fn metering_with_rollback_works() { + let size = allocation_size(&ALICE, &Key::Fix([1; 32]), Some(vec![1u8; 4096])); + let mut storage = TransientStorage::::new(size * 5); + + storage.start_transaction(); + assert_eq!( + storage.write(&ALICE, &Key::Fix([1; 32]), Some(vec![1u8; 4096]), false), + Ok(WriteOutcome::New) + ); + let amount = storage.meter.total_amount(); + storage.start_transaction(); + assert_eq!( + storage.write(&ALICE, &Key::Fix([2; 32]), Some(vec![1u8; 4096]), false), + Ok(WriteOutcome::New) + ); + storage.start_transaction(); + assert_eq!( + storage.write(&BOB, &Key::Fix([1; 32]), Some(vec![1u8; 4096]), false), + Ok(WriteOutcome::New) + ); + storage.commit_transaction(); + storage.rollback_transaction(); + assert_eq!(storage.meter.total_amount(), amount); + storage.commit_transaction(); + } +} diff --git a/substrate/frame/contracts/src/wasm/mod.rs b/substrate/frame/contracts/src/wasm/mod.rs index 0d65d696758d0f3af8a12df0623b853f73b193f2..f4ee76459c4eaa7fc117baece31b10333173cf41 100644 --- a/substrate/frame/contracts/src/wasm/mod.rs +++ b/substrate/frame/contracts/src/wasm/mod.rs @@ -48,6 +48,7 @@ use crate::{ AccountIdOf, BadOrigin, BalanceOf, CodeHash, CodeInfoOf, CodeVec, Config, Error, Event, HoldReason, Pallet, PristineCode, Schedule, Weight, LOG_TARGET, }; +use alloc::vec::Vec; use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{ dispatch::DispatchResult, @@ -56,7 +57,6 @@ use frame_support::{ }; use sp_core::Get; use sp_runtime::{DispatchError, RuntimeDebug}; -use sp_std::prelude::*; use wasmi::{CompilationMode, InstancePre, Linker, Memory, MemoryType, StackLimits, Store}; const BYTES_PER_PAGE: usize = 64 * 1024; @@ -506,6 +506,7 @@ mod tests { primitives::ExecReturnValue, storage::WriteOutcome, tests::{RuntimeCall, Test, ALICE, BOB}, + transient_storage::TransientStorage, BalanceOf, CodeHash, Error, Origin, Pallet as Contracts, }; use assert_matches::assert_matches; @@ -563,6 +564,7 @@ mod tests { pub struct MockExt { storage: HashMap, Vec>, + transient_storage: TransientStorage, instantiates: Vec, terminations: Vec, calls: Vec, @@ -591,6 +593,7 @@ mod tests { Self { code_hashes: Default::default(), storage: Default::default(), + transient_storage: TransientStorage::new(1024 * 1024), instantiates: Default::default(), terminations: Default::default(), calls: Default::default(), @@ -691,6 +694,21 @@ mod tests { } Ok(result) } + fn get_transient_storage(&self, key: &Key) -> Option> { + self.transient_storage.read(self.address(), key) + } + fn get_transient_storage_size(&self, key: &Key) -> Option { + self.transient_storage.read(self.address(), key).map(|value| value.len() as _) + } + fn set_transient_storage( + &mut self, + key: &Key, + value: Option>, + take_old: bool, + ) -> Result { + let account_id = self.address().clone(); + self.transient_storage.write(&account_id, key, value, take_old) + } fn caller(&self) -> Origin { self.caller.clone() } @@ -784,6 +802,10 @@ mod tests { fn contract_info(&mut self) -> &mut crate::ContractInfo { unimplemented!() } + #[cfg(feature = "runtime-benchmarks")] + fn transient_storage(&mut self) -> &mut TransientStorage { + unimplemented!() + } fn ecdsa_to_eth_address(&self, _pk: &[u8; 33]) -> Result<[u8; 20], ()> { Ok([2u8; 20]) } @@ -3046,6 +3068,337 @@ mod tests { assert_eq!(&result.data[4..], &[0u8; 0]); } + #[test] + fn set_transient_storage_works() { + const CODE: &str = r#" +(module + (import "seal0" "seal_input" (func $seal_input (param i32 i32))) + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "seal0" "set_transient_storage" (func $set_transient_storage (param i32 i32 i32 i32) (result i32))) + (import "env" "memory" (memory 1 1)) + + ;; [0, 4) size of input buffer + ;; 4k in little endian + (data (i32.const 0) "\00\10") + + ;; [4, 4100) input buffer + + (func (export "call") + ;; Receive (key ++ value_to_write) + (call $seal_input + (i32.const 4) ;; Pointer to the input buffer + (i32.const 0) ;; Size of the input buffer + ) + ;; Store the passed value to the passed key and store result to memory + (i32.store (i32.const 168) + (call $set_transient_storage + (i32.const 8) ;; key_ptr + (i32.load (i32.const 4)) ;; key_len + (i32.add ;; value_ptr = 8 + key_len + (i32.const 8) + (i32.load (i32.const 4))) + (i32.sub ;; value_len (input_size - (key_len + key_len_len)) + (i32.load (i32.const 0)) + (i32.add + (i32.load (i32.const 4)) + (i32.const 4) + ) + ) + ) + ) + (call $seal_return + (i32.const 0) ;; flags + (i32.const 168) ;; ptr to returned value + (i32.const 4) ;; length of returned value + ) + ) + + (func (export "deploy")) +) +"#; + + let mut ext = MockExt::default(); + + // value did not exist before -> sentinel returned + let input = (32, [1u8; 32], [42u8, 48]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), crate::SENTINEL); + assert_eq!( + ext.get_transient_storage(&Key::::try_from_var([1u8; 32].to_vec()).unwrap()), + Some(vec![42, 48]) + ); + + // value do exist -> length of old value returned + let input = (32, [1u8; 32], [0u8; 0]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), 2); + assert_eq!( + ext.get_transient_storage(&Key::::try_from_var([1u8; 32].to_vec()).unwrap()), + Some(vec![]) + ); + + // value do exist -> length of old value returned (test for zero sized val) + let input = (32, [1u8; 32], [99u8]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), 0); + assert_eq!( + ext.get_transient_storage(&Key::::try_from_var([1u8; 32].to_vec()).unwrap()), + Some(vec![99]) + ); + } + + #[test] + fn get_transient_storage_works() { + const CODE: &str = r#" +(module + (import "seal0" "seal_input" (func $seal_input (param i32 i32))) + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "seal0" "get_transient_storage" (func $get_transient_storage (param i32 i32 i32 i32) (result i32))) + (import "env" "memory" (memory 1 1)) + + ;; [0, 4) size of input buffer (160 bytes as we copy the key+len here) + (data (i32.const 0) "\A0") + + ;; [4, 8) size of output buffer + ;; 4k in little endian + (data (i32.const 4) "\00\10") + + ;; [8, 168) input buffer + ;; [168, 4264) output buffer + + (func (export "call") + ;; Receive (key ++ value_to_write) + (call $seal_input + (i32.const 8) ;; Pointer to the input buffer + (i32.const 0) ;; Size of the input buffer + ) + ;; Load a storage value and result of this call into the output buffer + (i32.store (i32.const 168) + (call $get_transient_storage + (i32.const 12) ;; key_ptr + (i32.load (i32.const 8)) ;; key_len + (i32.const 172) ;; Pointer to the output buffer + (i32.const 4) ;; Pointer to the size of the buffer + ) + ) + (call $seal_return + (i32.const 0) ;; flags + (i32.const 168) ;; output buffer ptr + (i32.add ;; length: output size + 4 (retval) + (i32.load (i32.const 4)) + (i32.const 4) + ) + ) + ) + + (func (export "deploy")) +) +"#; + + let mut ext = MockExt::default(); + + assert_ok!(ext.set_transient_storage( + &Key::::try_from_var([1u8; 64].to_vec()).unwrap(), + Some(vec![42u8]), + false + )); + assert_ok!(ext.set_transient_storage( + &Key::::try_from_var([2u8; 19].to_vec()).unwrap(), + Some(vec![]), + false + )); + + // value does not exist + let input = (63, [1u8; 64]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + assert_eq!( + u32::from_le_bytes(result.data[0..4].try_into().unwrap()), + ReturnErrorCode::KeyNotFound as u32 + ); + + // value exists + let input = (64, [1u8; 64]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + assert_eq!( + u32::from_le_bytes(result.data[0..4].try_into().unwrap()), + ReturnErrorCode::Success as u32 + ); + assert_eq!(&result.data[4..], &[42u8]); + + // value exists (test for 0 sized) + let input = (19, [2u8; 19]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + assert_eq!( + u32::from_le_bytes(result.data[0..4].try_into().unwrap()), + ReturnErrorCode::Success as u32 + ); + assert_eq!(&result.data[4..], &([] as [u8; 0])); + } + + #[test] + fn clear_transient_storage_works() { + const CODE: &str = r#" +(module + (import "seal0" "seal_input" (func $seal_input (param i32 i32))) + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "seal0" "clear_transient_storage" (func $clear_transient_storage (param i32 i32) (result i32))) + (import "env" "memory" (memory 1 1)) + + ;; size of input buffer + ;; [0, 4) size of input buffer (128+32 = 160 bytes = 0xA0) + (data (i32.const 0) "\A0") + + ;; [4, 164) input buffer + + (func (export "call") + ;; Receive key + (call $seal_input + (i32.const 4) ;; Where we take input and store it + (i32.const 0) ;; Where we take and store the length of thedata + ) + ;; Call seal_clear_storage and save what it returns at 0 + (i32.store (i32.const 0) + (call $clear_transient_storage + (i32.const 8) ;; key_ptr + (i32.load (i32.const 4)) ;; key_len + ) + ) + (call $seal_return + (i32.const 0) ;; flags + (i32.const 0) ;; returned value + (i32.const 4) ;; length of returned value + ) + ) + + (func (export "deploy")) +) +"#; + + let mut ext = MockExt::default(); + + assert_ok!(ext.set_transient_storage( + &Key::::try_from_var([1u8; 64].to_vec()).unwrap(), + Some(vec![42u8]), + false + )); + + // value did not exist + let input = (32, [3u8; 32]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + // sentinel returned + assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), crate::SENTINEL); + + // value did exist + let input = (64, [1u8; 64]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + // length returned + assert_eq!(u32::from_le_bytes(result.data.try_into().unwrap()), 1); + // value cleared + assert_eq!( + ext.get_transient_storage(&Key::::try_from_var([1u8; 64].to_vec()).unwrap()), + None + ); + } + + #[test] + fn take_transient_storage_works() { + const CODE: &str = r#" +(module + (import "seal0" "seal_return" (func $seal_return (param i32 i32 i32))) + (import "seal0" "seal_input" (func $seal_input (param i32 i32))) + (import "seal0" "take_transient_storage" (func $take_transient_storage (param i32 i32 i32 i32) (result i32))) + (import "env" "memory" (memory 1 1)) + + ;; [0, 4) size of input buffer (160 bytes as we copy the key+len here) + (data (i32.const 0) "\A0") + + ;; [4, 8) size of output buffer + ;; 4k in little endian + (data (i32.const 4) "\00\10") + + ;; [8, 168) input buffer + ;; [168, 4264) output buffer + + (func (export "call") + ;; Receive key + (call $seal_input + (i32.const 8) ;; Pointer to the input buffer + (i32.const 0) ;; Size of the length buffer + ) + + ;; Load a storage value and result of this call into the output buffer + (i32.store (i32.const 168) + (call $take_transient_storage + (i32.const 12) ;; key_ptr + (i32.load (i32.const 8)) ;; key_len + (i32.const 172) ;; Pointer to the output buffer + (i32.const 4) ;; Pointer to the size of the buffer + ) + ) + + ;; Return the contents of the buffer + (call $seal_return + (i32.const 0) ;; flags + (i32.const 168) ;; output buffer ptr + (i32.add ;; length: storage size + 4 (retval) + (i32.load (i32.const 4)) + (i32.const 4) + ) + ) + ) + + (func (export "deploy")) +) +"#; + + let mut ext = MockExt::default(); + + assert_ok!(ext.set_transient_storage( + &Key::::try_from_var([1u8; 64].to_vec()).unwrap(), + Some(vec![42u8]), + false + )); + assert_ok!(ext.set_transient_storage( + &Key::::try_from_var([2u8; 19].to_vec()).unwrap(), + Some(vec![]), + false + )); + + // value does not exist -> error returned + let input = (63, [1u8; 64]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + assert_eq!( + u32::from_le_bytes(result.data[0..4].try_into().unwrap()), + ReturnErrorCode::KeyNotFound as u32 + ); + + // value did exist -> value returned + let input = (64, [1u8; 64]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + assert_eq!( + u32::from_le_bytes(result.data[0..4].try_into().unwrap()), + ReturnErrorCode::Success as u32 + ); + assert_eq!( + ext.get_transient_storage(&Key::::try_from_var([1u8; 64].to_vec()).unwrap()), + None + ); + assert_eq!(&result.data[4..], &[42u8]); + + // value did exist -> length returned (test for 0 sized) + let input = (19, [2u8; 19]).encode(); + let result = execute(CODE, input, &mut ext).unwrap(); + assert_eq!( + u32::from_le_bytes(result.data[0..4].try_into().unwrap()), + ReturnErrorCode::Success as u32 + ); + assert_eq!( + ext.get_transient_storage(&Key::::try_from_var([2u8; 19].to_vec()).unwrap()), + None + ); + assert_eq!(&result.data[4..], &[0u8; 0]); + } + #[test] fn is_contract_works() { const CODE_IS_CONTRACT: &str = r#" diff --git a/substrate/frame/contracts/src/wasm/prepare.rs b/substrate/frame/contracts/src/wasm/prepare.rs index 50eb6d625321abc0961ce4c1c0b66001dd00b1fa..93fe3080d22db712055d890883d78cea81fb5a9b 100644 --- a/substrate/frame/contracts/src/wasm/prepare.rs +++ b/substrate/frame/contracts/src/wasm/prepare.rs @@ -28,10 +28,10 @@ use crate::{ }, AccountIdOf, CodeVec, Config, Error, Schedule, LOG_TARGET, }; +#[cfg(any(test, feature = "runtime-benchmarks"))] +use alloc::vec::Vec; use codec::MaxEncodedLen; use sp_runtime::{traits::Hash, DispatchError}; -#[cfg(any(test, feature = "runtime-benchmarks"))] -use sp_std::prelude::Vec; use wasmi::{ core::ValType as WasmiValueType, CompilationMode, Config as WasmiConfig, Engine, ExternType, Module, StackLimits, @@ -56,7 +56,7 @@ pub enum LoadingMode { #[cfg(test)] pub mod tracker { - use sp_std::cell::RefCell; + use core::cell::RefCell; thread_local! { pub static LOADED_MODULE: RefCell> = RefCell::new(Vec::new()); } diff --git a/substrate/frame/contracts/src/wasm/runtime.rs b/substrate/frame/contracts/src/wasm/runtime.rs index 5f50dbf391a2822d66a8930eac12bea4a45ccdd4..982d28540ec1eb51a92377dd2abc09805b79344a 100644 --- a/substrate/frame/contracts/src/wasm/runtime.rs +++ b/substrate/frame/contracts/src/wasm/runtime.rs @@ -24,7 +24,9 @@ use crate::{ weights::WeightInfo, BalanceOf, CodeHash, Config, DebugBufferVec, Error, SENTINEL, }; +use alloc::{boxed::Box, vec, vec::Vec}; use codec::{Decode, DecodeLimit, Encode, MaxEncodedLen}; +use core::fmt; use frame_support::{ dispatch::DispatchInfo, ensure, pallet_prelude::DispatchResultWithPostInfo, parameter_types, traits::Get, weights::Weight, @@ -36,7 +38,6 @@ use sp_runtime::{ traits::{Bounded, Zero}, DispatchError, RuntimeDebug, }; -use sp_std::{fmt, prelude::*}; use wasmi::{core::HostError, errors::LinkerError, Linker, Memory, Store}; type CallOf = ::RuntimeCall; @@ -198,6 +199,16 @@ pub enum RuntimeCosts { GetStorage(u32), /// Weight of calling `seal_take_storage` for the given size. TakeStorage(u32), + /// Weight of calling `seal_set_transient_storage` for the given storage item sizes. + SetTransientStorage { old_bytes: u32, new_bytes: u32 }, + /// Weight of calling `seal_clear_transient_storage` per cleared byte. + ClearTransientStorage(u32), + /// Weight of calling `seal_contains_transient_storage` per byte of the checked item. + ContainsTransientStorage(u32), + /// Weight of calling `seal_get_transient_storage` with the specified size in storage. + GetTransientStorage(u32), + /// Weight of calling `seal_take_transient_storage` for the given size. + TakeTransientStorage(u32), /// Weight of calling `seal_transfer`. Transfer, /// Base weight of calling `seal_call`. @@ -244,6 +255,34 @@ pub enum RuntimeCosts { UnlockDelegateDependency, } +// For the function that modifies the storage, the benchmarks are done with one item in the +// transient_storage (BTreeMap). To consider the worst-case scenario, the weight of the overhead of +// writing to a full BTreeMap should be included. On top of that, the rollback weight is added, +// which is the worst scenario. +macro_rules! cost_write { + // cost_write!(name, a, b, c) -> T::WeightInfo::name(a, b, c).saturating_add(T::WeightInfo::rollback_transient_storage()) + // .saturating_add(T::WeightInfo::set_transient_storage_full().saturating_sub(T::WeightInfo::set_transient_storage_empty()) + ($name:ident $(, $arg:expr )*) => { + (T::WeightInfo::$name($( $arg ),*).saturating_add(T::WeightInfo::rollback_transient_storage()).saturating_add(cost_write!(@cost_storage))) + }; + + (@cost_storage) => { + T::WeightInfo::set_transient_storage_full().saturating_sub(T::WeightInfo::set_transient_storage_empty()) + }; +} + +macro_rules! cost_read { + // cost_read!(name, a, b, c) -> T::WeightInfo::name(a, b, c).saturating_add(T::WeightInfo::get_transient_storage_full() + // .saturating_sub(T::WeightInfo::get_transient_storage_empty()) + ($name:ident $(, $arg:expr )*) => { + (T::WeightInfo::$name($( $arg ),*).saturating_add(cost_read!(@cost_storage))) + }; + + (@cost_storage) => { + T::WeightInfo::get_transient_storage_full().saturating_sub(T::WeightInfo::get_transient_storage_empty()) + }; +} + macro_rules! cost_args { // cost_args!(name, a, b, c) -> T::WeightInfo::name(a, b, c).saturating_sub(T::WeightInfo::name(0, 0, 0)) ($name:ident, $( $arg: expr ),+) => { @@ -295,6 +334,12 @@ impl Token for RuntimeCosts { ContainsStorage(len) => T::WeightInfo::seal_contains_storage(len), GetStorage(len) => T::WeightInfo::seal_get_storage(len), TakeStorage(len) => T::WeightInfo::seal_take_storage(len), + SetTransientStorage { new_bytes, old_bytes } => + cost_write!(seal_set_transient_storage, new_bytes, old_bytes), + ClearTransientStorage(len) => cost_write!(seal_clear_transient_storage, len), + ContainsTransientStorage(len) => cost_read!(seal_contains_transient_storage, len), + GetTransientStorage(len) => cost_read!(seal_get_transient_storage, len), + TakeTransientStorage(len) => cost_write!(seal_take_transient_storage, len), Transfer => T::WeightInfo::seal_transfer(), CallBase => T::WeightInfo::seal_call(0, 0), DelegateCallBase => T::WeightInfo::seal_delegate_call(), @@ -791,10 +836,129 @@ impl<'a, E: Ext + 'a> Runtime<'a, E> { let key = self.decode_key(memory, key_type, key_ptr)?; let outcome = self.ext.get_storage_size(&key); - self.adjust_gas(charged, RuntimeCosts::ClearStorage(outcome.unwrap_or(0))); + self.adjust_gas(charged, RuntimeCosts::ContainsStorage(outcome.unwrap_or(0))); Ok(outcome.unwrap_or(SENTINEL)) } + fn set_transient_storage( + &mut self, + memory: &[u8], + key_type: KeyType, + key_ptr: u32, + value_ptr: u32, + value_len: u32, + ) -> Result { + let max_size = self.ext.max_value_size(); + let charged = self.charge_gas(RuntimeCosts::SetTransientStorage { + new_bytes: value_len, + old_bytes: max_size, + })?; + if value_len > max_size { + return Err(Error::::ValueTooLarge.into()) + } + let key = self.decode_key(memory, key_type, key_ptr)?; + let value = Some(self.read_sandbox_memory(memory, value_ptr, value_len)?); + let write_outcome = self.ext.set_transient_storage(&key, value, false)?; + self.adjust_gas( + charged, + RuntimeCosts::SetTransientStorage { + new_bytes: value_len, + old_bytes: write_outcome.old_len(), + }, + ); + Ok(write_outcome.old_len_with_sentinel()) + } + + fn clear_transient_storage( + &mut self, + memory: &[u8], + key_type: KeyType, + key_ptr: u32, + ) -> Result { + let charged = + self.charge_gas(RuntimeCosts::ClearTransientStorage(self.ext.max_value_size()))?; + let key = self.decode_key(memory, key_type, key_ptr)?; + let outcome = self.ext.set_transient_storage(&key, None, false)?; + + self.adjust_gas(charged, RuntimeCosts::ClearTransientStorage(outcome.old_len())); + Ok(outcome.old_len_with_sentinel()) + } + + fn get_transient_storage( + &mut self, + memory: &mut [u8], + key_type: KeyType, + key_ptr: u32, + out_ptr: u32, + out_len_ptr: u32, + ) -> Result { + let charged = + self.charge_gas(RuntimeCosts::GetTransientStorage(self.ext.max_value_size()))?; + let key = self.decode_key(memory, key_type, key_ptr)?; + let outcome = self.ext.get_transient_storage(&key); + + if let Some(value) = outcome { + self.adjust_gas(charged, RuntimeCosts::GetTransientStorage(value.len() as u32)); + self.write_sandbox_output( + memory, + out_ptr, + out_len_ptr, + &value, + false, + already_charged, + )?; + Ok(ReturnErrorCode::Success) + } else { + self.adjust_gas(charged, RuntimeCosts::GetTransientStorage(0)); + Ok(ReturnErrorCode::KeyNotFound) + } + } + + fn contains_transient_storage( + &mut self, + memory: &[u8], + key_type: KeyType, + key_ptr: u32, + ) -> Result { + let charged = + self.charge_gas(RuntimeCosts::ContainsTransientStorage(self.ext.max_value_size()))?; + let key = self.decode_key(memory, key_type, key_ptr)?; + let outcome = self.ext.get_transient_storage_size(&key); + + self.adjust_gas(charged, RuntimeCosts::ContainsTransientStorage(outcome.unwrap_or(0))); + Ok(outcome.unwrap_or(SENTINEL)) + } + + fn take_transient_storage( + &mut self, + memory: &mut [u8], + key_type: KeyType, + key_ptr: u32, + out_ptr: u32, + out_len_ptr: u32, + ) -> Result { + let charged = + self.charge_gas(RuntimeCosts::TakeTransientStorage(self.ext.max_value_size()))?; + let key = self.decode_key(memory, key_type, key_ptr)?; + if let crate::storage::WriteOutcome::Taken(value) = + self.ext.set_transient_storage(&key, None, true)? + { + self.adjust_gas(charged, RuntimeCosts::TakeTransientStorage(value.len() as u32)); + self.write_sandbox_output( + memory, + out_ptr, + out_len_ptr, + &value, + false, + already_charged, + )?; + Ok(ReturnErrorCode::Success) + } else { + self.adjust_gas(charged, RuntimeCosts::TakeTransientStorage(0)); + Ok(ReturnErrorCode::KeyNotFound) + } + } + fn call( &mut self, memory: &mut [u8], @@ -1098,6 +1262,67 @@ pub mod env { } } + /// Set the value at the given key in the contract transient storage. + #[unstable] + fn set_transient_storage( + ctx: _, + memory: _, + key_ptr: u32, + key_len: u32, + value_ptr: u32, + value_len: u32, + ) -> Result { + ctx.set_transient_storage(memory, KeyType::Var(key_len), key_ptr, value_ptr, value_len) + } + + /// Clear the value at the given key in the contract storage. + #[unstable] + fn clear_transient_storage( + ctx: _, + memory: _, + key_ptr: u32, + key_len: u32, + ) -> Result { + ctx.clear_transient_storage(memory, KeyType::Var(key_len), key_ptr) + } + + /// Retrieve the value under the given key from transient storage. + #[unstable] + fn get_transient_storage( + ctx: _, + memory: _, + key_ptr: u32, + key_len: u32, + out_ptr: u32, + out_len_ptr: u32, + ) -> Result { + ctx.get_transient_storage(memory, KeyType::Var(key_len), key_ptr, out_ptr, out_len_ptr) + } + + /// Checks whether there is a value stored under the given key in transient storage. + #[unstable] + fn contains_transient_storage( + ctx: _, + memory: _, + key_ptr: u32, + key_len: u32, + ) -> Result { + ctx.contains_transient_storage(memory, KeyType::Var(key_len), key_ptr) + } + + /// Retrieve and remove the value under the given key from transient storage. + #[unstable] + fn take_transient_storage( + ctx: _, + memory: _, + key_ptr: u32, + key_len: u32, + out_ptr: u32, + out_len_ptr: u32, + ) -> Result { + ctx.take_transient_storage(memory, KeyType::Var(key_len), key_ptr, out_ptr, out_len_ptr) + } + /// Transfer some value to another account. /// See [`pallet_contracts_uapi::HostFn::transfer`]. #[prefixed_alias] @@ -1900,7 +2125,7 @@ pub mod env { data_len: u32, ) -> Result<(), TrapReason> { let num_topic = topics_len - .checked_div(sp_std::mem::size_of::>() as u32) + .checked_div(core::mem::size_of::>() as u32) .ok_or("Zero sized topics are not allowed")?; ctx.charge_gas(RuntimeCosts::DepositEvent { num_topic, len: data_len })?; if data_len > ctx.ext.max_value_size() { diff --git a/substrate/frame/contracts/src/weights.rs b/substrate/frame/contracts/src/weights.rs index 0404a9d3d8e5011c68c5cd86724287ddd678199d..dc10a8aee773c84907198cee08aefc5aef785345 100644 --- a/substrate/frame/contracts/src/weights.rs +++ b/substrate/frame/contracts/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_contracts` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-06-07, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-07-09, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-1pho9goo-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-yaoqqom-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -98,6 +98,16 @@ pub trait WeightInfo { fn seal_get_storage(n: u32, ) -> Weight; fn seal_contains_storage(n: u32, ) -> Weight; fn seal_take_storage(n: u32, ) -> Weight; + fn set_transient_storage_empty() -> Weight; + fn set_transient_storage_full() -> Weight; + fn get_transient_storage_empty() -> Weight; + fn get_transient_storage_full() -> Weight; + fn rollback_transient_storage() -> Weight; + fn seal_set_transient_storage(n: u32, o: u32, ) -> Weight; + fn seal_clear_transient_storage(n: u32, ) -> Weight; + fn seal_get_transient_storage(n: u32, ) -> Weight; + fn seal_contains_transient_storage(n: u32, ) -> Weight; + fn seal_take_transient_storage(n: u32, ) -> Weight; fn seal_transfer() -> Weight; fn seal_call(t: u32, i: u32, ) -> Weight; fn seal_delegate_call() -> Weight; @@ -127,8 +137,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `142` // Estimated: `1627` - // Minimum execution time: 1_896_000 picoseconds. - Weight::from_parts(1_990_000, 1627) + // Minimum execution time: 1_921_000 picoseconds. + Weight::from_parts(2_003_000, 1627) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: `Skipped::Metadata` (r:0 w:0) @@ -138,10 +148,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `452 + k * (69 ±0)` // Estimated: `442 + k * (70 ±0)` - // Minimum execution time: 11_142_000 picoseconds. - Weight::from_parts(11_578_000, 442) - // Standard Error: 1_557 - .saturating_add(Weight::from_parts(1_165_198, 0).saturating_mul(k.into())) + // Minimum execution time: 11_364_000 picoseconds. + Weight::from_parts(11_463_000, 442) + // Standard Error: 2_141 + .saturating_add(Weight::from_parts(1_149_944, 0).saturating_mul(k.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(k.into()))) .saturating_add(T::DbWeight::get().writes(2_u64)) @@ -155,10 +165,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `211 + c * (1 ±0)` // Estimated: `6149 + c * (1 ±0)` - // Minimum execution time: 7_649_000 picoseconds. - Weight::from_parts(4_827_445, 6149) + // Minimum execution time: 7_565_000 picoseconds. + Weight::from_parts(5_041_009, 6149) // Standard Error: 5 - .saturating_add(Weight::from_parts(1_630, 0).saturating_mul(c.into())) + .saturating_add(Weight::from_parts(1_640, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(c.into())) @@ -171,8 +181,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `510` // Estimated: `6450` - // Minimum execution time: 16_096_000 picoseconds. - Weight::from_parts(16_937_000, 6450) + // Minimum execution time: 15_894_000 picoseconds. + Weight::from_parts(16_618_000, 6450) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -185,10 +195,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `171 + k * (1 ±0)` // Estimated: `3635 + k * (1 ±0)` - // Minimum execution time: 3_131_000 picoseconds. - Weight::from_parts(3_209_000, 3635) - // Standard Error: 481 - .saturating_add(Weight::from_parts(1_087_506, 0).saturating_mul(k.into())) + // Minimum execution time: 3_077_000 picoseconds. + Weight::from_parts(3_144_000, 3635) + // Standard Error: 650 + .saturating_add(Weight::from_parts(1_095_835, 0).saturating_mul(k.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(k.into()))) @@ -207,10 +217,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `325 + c * (1 ±0)` // Estimated: `6263 + c * (1 ±0)` - // Minimum execution time: 15_289_000 picoseconds. - Weight::from_parts(16_157_168, 6263) + // Minimum execution time: 14_960_000 picoseconds. + Weight::from_parts(15_778_951, 6263) // Standard Error: 1 - .saturating_add(Weight::from_parts(395, 0).saturating_mul(c.into())) + .saturating_add(Weight::from_parts(443, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(c.into())) @@ -221,8 +231,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `440` // Estimated: `6380` - // Minimum execution time: 12_312_000 picoseconds. - Weight::from_parts(12_650_000, 6380) + // Minimum execution time: 11_849_000 picoseconds. + Weight::from_parts(12_273_000, 6380) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -236,8 +246,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `352` // Estimated: `6292` - // Minimum execution time: 47_239_000 picoseconds. - Weight::from_parts(48_617_000, 6292) + // Minimum execution time: 47_862_000 picoseconds. + Weight::from_parts(48_879_000, 6292) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -249,8 +259,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `594` // Estimated: `6534` - // Minimum execution time: 52_084_000 picoseconds. - Weight::from_parts(53_838_000, 6534) + // Minimum execution time: 50_754_000 picoseconds. + Weight::from_parts(52_720_000, 6534) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -260,8 +270,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `409` // Estimated: `6349` - // Minimum execution time: 11_785_000 picoseconds. - Weight::from_parts(12_284_000, 6349) + // Minimum execution time: 11_459_000 picoseconds. + Weight::from_parts(11_921_000, 6349) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -271,8 +281,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `142` // Estimated: `1627` - // Minimum execution time: 2_136_000 picoseconds. - Weight::from_parts(2_233_000, 1627) + // Minimum execution time: 2_135_000 picoseconds. + Weight::from_parts(2_247_000, 1627) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -284,8 +294,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `166` // Estimated: `3631` - // Minimum execution time: 10_957_000 picoseconds. - Weight::from_parts(11_314_000, 3631) + // Minimum execution time: 10_645_000 picoseconds. + Weight::from_parts(11_107_000, 3631) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -295,8 +305,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `142` // Estimated: `3607` - // Minimum execution time: 4_354_000 picoseconds. - Weight::from_parts(4_613_000, 3607) + // Minimum execution time: 4_353_000 picoseconds. + Weight::from_parts(4_628_000, 3607) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:0) @@ -307,8 +317,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `167` // Estimated: `3632` - // Minimum execution time: 5_541_000 picoseconds. - Weight::from_parts(5_790_000, 3632) + // Minimum execution time: 5_432_000 picoseconds. + Weight::from_parts(5_624_000, 3632) .saturating_add(T::DbWeight::get().reads(2_u64)) } /// Storage: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:0) @@ -319,8 +329,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `142` // Estimated: `3607` - // Minimum execution time: 5_502_000 picoseconds. - Weight::from_parts(5_701_000, 3607) + // Minimum execution time: 5_371_000 picoseconds. + Weight::from_parts(5_794_000, 3607) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -339,12 +349,12 @@ impl WeightInfo for SubstrateWeight { /// The range of component `c` is `[0, 125952]`. fn call_with_code_per_byte(c: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `801 + c * (1 ±0)` - // Estimated: `4264 + c * (1 ±0)` - // Minimum execution time: 247_884_000 picoseconds. - Weight::from_parts(265_795_781, 4264) + // Measured: `800 + c * (1 ±0)` + // Estimated: `4266 + c * (1 ±0)` + // Minimum execution time: 247_157_000 picoseconds. + Weight::from_parts(269_252_698, 4266) // Standard Error: 4 - .saturating_add(Weight::from_parts(724, 0).saturating_mul(c.into())) + .saturating_add(Weight::from_parts(729, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(6_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(c.into())) @@ -372,14 +382,14 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `323` // Estimated: `6262` - // Minimum execution time: 4_500_184_000 picoseconds. - Weight::from_parts(160_729_258, 6262) - // Standard Error: 143 - .saturating_add(Weight::from_parts(52_809, 0).saturating_mul(c.into())) - // Standard Error: 17 - .saturating_add(Weight::from_parts(2_173, 0).saturating_mul(i.into())) - // Standard Error: 17 - .saturating_add(Weight::from_parts(2_165, 0).saturating_mul(s.into())) + // Minimum execution time: 4_575_784_000 picoseconds. + Weight::from_parts(207_379_459, 6262) + // Standard Error: 124 + .saturating_add(Weight::from_parts(52_392, 0).saturating_mul(c.into())) + // Standard Error: 15 + .saturating_add(Weight::from_parts(2_257, 0).saturating_mul(i.into())) + // Standard Error: 15 + .saturating_add(Weight::from_parts(2_263, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(7_u64)) } @@ -404,13 +414,13 @@ impl WeightInfo for SubstrateWeight { fn instantiate(i: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `560` - // Estimated: `4029` - // Minimum execution time: 2_219_163_000 picoseconds. - Weight::from_parts(2_236_918_000, 4029) - // Standard Error: 32 - .saturating_add(Weight::from_parts(937, 0).saturating_mul(i.into())) - // Standard Error: 32 - .saturating_add(Weight::from_parts(938, 0).saturating_mul(s.into())) + // Estimated: `4017` + // Minimum execution time: 2_306_770_000 picoseconds. + Weight::from_parts(2_462_908_000, 4017) + // Standard Error: 33 + .saturating_add(Weight::from_parts(898, 0).saturating_mul(i.into())) + // Standard Error: 33 + .saturating_add(Weight::from_parts(859, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(8_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -430,8 +440,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `826` // Estimated: `4291` - // Minimum execution time: 164_801_000 picoseconds. - Weight::from_parts(167_250_000, 4291) + // Minimum execution time: 165_499_000 picoseconds. + Weight::from_parts(169_903_000, 4291) .saturating_add(T::DbWeight::get().reads(6_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -448,10 +458,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `142` // Estimated: `3607` - // Minimum execution time: 225_207_000 picoseconds. - Weight::from_parts(263_665_658, 3607) - // Standard Error: 47 - .saturating_add(Weight::from_parts(50_732, 0).saturating_mul(c.into())) + // Minimum execution time: 227_590_000 picoseconds. + Weight::from_parts(260_045_588, 3607) + // Standard Error: 52 + .saturating_add(Weight::from_parts(51_305, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -468,10 +478,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `142` // Estimated: `3607` - // Minimum execution time: 230_718_000 picoseconds. - Weight::from_parts(258_359_271, 3607) - // Standard Error: 47 - .saturating_add(Weight::from_parts(51_014, 0).saturating_mul(c.into())) + // Minimum execution time: 239_634_000 picoseconds. + Weight::from_parts(262_040_831, 3607) + // Standard Error: 103 + .saturating_add(Weight::from_parts(51_590, 0).saturating_mul(c.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -487,8 +497,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `315` // Estimated: `3780` - // Minimum execution time: 39_668_000 picoseconds. - Weight::from_parts(41_031_000, 3780) + // Minimum execution time: 39_152_000 picoseconds. + Weight::from_parts(39_970_000, 3780) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -502,8 +512,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `552` // Estimated: `6492` - // Minimum execution time: 25_890_000 picoseconds. - Weight::from_parts(26_603_000, 6492) + // Minimum execution time: 25_143_000 picoseconds. + Weight::from_parts(26_103_000, 6492) .saturating_add(T::DbWeight::get().reads(4_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -512,17 +522,17 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 8_269_000 picoseconds. - Weight::from_parts(9_227_069, 0) - // Standard Error: 74 - .saturating_add(Weight::from_parts(51_396, 0).saturating_mul(r.into())) + // Minimum execution time: 8_406_000 picoseconds. + Weight::from_parts(9_056_753, 0) + // Standard Error: 98 + .saturating_add(Weight::from_parts(53_110, 0).saturating_mul(r.into())) } fn seal_caller() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 602_000 picoseconds. - Weight::from_parts(664_000, 0) + // Minimum execution time: 659_000 picoseconds. + Weight::from_parts(705_000, 0) } /// Storage: `Contracts::ContractInfoOf` (r:1 w:0) /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) @@ -530,8 +540,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `354` // Estimated: `3819` - // Minimum execution time: 6_131_000 picoseconds. - Weight::from_parts(6_468_000, 3819) + // Minimum execution time: 6_165_000 picoseconds. + Weight::from_parts(6_340_000, 3819) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: `Contracts::ContractInfoOf` (r:1 w:0) @@ -540,79 +550,79 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `447` // Estimated: `3912` - // Minimum execution time: 7_557_000 picoseconds. - Weight::from_parts(7_704_000, 3912) + // Minimum execution time: 7_398_000 picoseconds. + Weight::from_parts(7_661_000, 3912) .saturating_add(T::DbWeight::get().reads(1_u64)) } fn seal_own_code_hash() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 783_000 picoseconds. - Weight::from_parts(848_000, 0) + // Minimum execution time: 723_000 picoseconds. + Weight::from_parts(793_000, 0) } fn seal_caller_is_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 397_000 picoseconds. - Weight::from_parts(435_000, 0) + // Minimum execution time: 398_000 picoseconds. + Weight::from_parts(428_000, 0) } fn seal_caller_is_root() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 351_000 picoseconds. - Weight::from_parts(372_000, 0) + // Minimum execution time: 329_000 picoseconds. + Weight::from_parts(364_000, 0) } fn seal_address() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 608_000 picoseconds. - Weight::from_parts(645_000, 0) + // Minimum execution time: 592_000 picoseconds. + Weight::from_parts(624_000, 0) } fn seal_gas_left() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 661_000 picoseconds. - Weight::from_parts(729_000, 0) + // Minimum execution time: 665_000 picoseconds. + Weight::from_parts(714_000, 0) } fn seal_balance() -> Weight { // Proof Size summary in bytes: // Measured: `140` // Estimated: `0` - // Minimum execution time: 4_545_000 picoseconds. - Weight::from_parts(4_663_000, 0) + // Minimum execution time: 4_486_000 picoseconds. + Weight::from_parts(4_668_000, 0) } fn seal_value_transferred() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 614_000 picoseconds. - Weight::from_parts(641_000, 0) + // Minimum execution time: 548_000 picoseconds. + Weight::from_parts(590_000, 0) } fn seal_minimum_balance() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 583_000 picoseconds. - Weight::from_parts(618_000, 0) + // Minimum execution time: 536_000 picoseconds. + Weight::from_parts(578_000, 0) } fn seal_block_number() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 583_000 picoseconds. - Weight::from_parts(617_000, 0) + // Minimum execution time: 552_000 picoseconds. + Weight::from_parts(599_000, 0) } fn seal_now() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 607_000 picoseconds. - Weight::from_parts(638_000, 0) + // Minimum execution time: 556_000 picoseconds. + Weight::from_parts(600_000, 0) } /// Storage: `TransactionPayment::NextFeeMultiplier` (r:1 w:0) /// Proof: `TransactionPayment::NextFeeMultiplier` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `Measured`) @@ -620,8 +630,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `67` // Estimated: `1552` - // Minimum execution time: 4_172_000 picoseconds. - Weight::from_parts(4_408_000, 1552) + // Minimum execution time: 4_084_000 picoseconds. + Weight::from_parts(4_321_000, 1552) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// The range of component `n` is `[0, 1048572]`. @@ -629,20 +639,20 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 475_000 picoseconds. - Weight::from_parts(515_000, 0) + // Minimum execution time: 468_000 picoseconds. + Weight::from_parts(492_000, 0) // Standard Error: 3 - .saturating_add(Weight::from_parts(298, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(310, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 1048572]`. fn seal_return(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 289_000 picoseconds. - Weight::from_parts(357_000, 0) - // Standard Error: 10 - .saturating_add(Weight::from_parts(405, 0).saturating_mul(n.into())) + // Minimum execution time: 377_000 picoseconds. + Weight::from_parts(396_000, 0) + // Standard Error: 9 + .saturating_add(Weight::from_parts(431, 0).saturating_mul(n.into())) } /// Storage: `Contracts::DeletionQueueCounter` (r:1 w:1) /// Proof: `Contracts::DeletionQueueCounter` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) @@ -655,10 +665,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `319 + n * (78 ±0)` // Estimated: `3784 + n * (2553 ±0)` - // Minimum execution time: 13_316_000 picoseconds. - Weight::from_parts(15_855_821, 3784) - // Standard Error: 7_274 - .saturating_add(Weight::from_parts(3_447_246, 0).saturating_mul(n.into())) + // Minimum execution time: 13_028_000 picoseconds. + Weight::from_parts(15_330_917, 3784) + // Standard Error: 8_260 + .saturating_add(Weight::from_parts(3_594_893, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(n.into()))) .saturating_add(T::DbWeight::get().writes(3_u64)) @@ -671,8 +681,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `76` // Estimated: `1561` - // Minimum execution time: 3_468_000 picoseconds. - Weight::from_parts(3_608_000, 1561) + // Minimum execution time: 3_367_000 picoseconds. + Weight::from_parts(3_555_000, 1561) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// Storage: `System::EventTopics` (r:4 w:4) @@ -683,12 +693,12 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `990 + t * (2475 ±0)` - // Minimum execution time: 3_777_000 picoseconds. - Weight::from_parts(4_028_191, 990) - // Standard Error: 5_907 - .saturating_add(Weight::from_parts(2_183_733, 0).saturating_mul(t.into())) + // Minimum execution time: 3_779_000 picoseconds. + Weight::from_parts(4_003_836, 990) + // Standard Error: 5_409 + .saturating_add(Weight::from_parts(2_082_176, 0).saturating_mul(t.into())) // Standard Error: 1 - .saturating_add(Weight::from_parts(18, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(14, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(t.into()))) .saturating_add(T::DbWeight::get().writes((1_u64).saturating_mul(t.into()))) .saturating_add(Weight::from_parts(0, 2475).saturating_mul(t.into())) @@ -698,10 +708,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 400_000 picoseconds. - Weight::from_parts(423_000, 0) + // Minimum execution time: 409_000 picoseconds. + Weight::from_parts(447_000, 0) // Standard Error: 10 - .saturating_add(Weight::from_parts(1_209, 0).saturating_mul(i.into())) + .saturating_add(Weight::from_parts(1_219, 0).saturating_mul(i.into())) } /// Storage: `Skipped::Metadata` (r:0 w:0) /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -711,12 +721,12 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `250 + o * (1 ±0)` // Estimated: `249 + o * (1 ±0)` - // Minimum execution time: 9_033_000 picoseconds. - Weight::from_parts(8_797_934, 249) + // Minimum execution time: 9_176_000 picoseconds. + Weight::from_parts(9_121_191, 249) // Standard Error: 1 - .saturating_add(Weight::from_parts(257, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(292, 0).saturating_mul(n.into())) // Standard Error: 1 - .saturating_add(Weight::from_parts(51, 0).saturating_mul(o.into())) + .saturating_add(Weight::from_parts(31, 0).saturating_mul(o.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(o.into())) @@ -728,10 +738,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `248 + n * (1 ±0)` - // Minimum execution time: 7_167_000 picoseconds. - Weight::from_parts(8_012_194, 248) + // Minimum execution time: 7_294_000 picoseconds. + Weight::from_parts(7_963_151, 248) // Standard Error: 1 - .saturating_add(Weight::from_parts(90, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(92, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -743,10 +753,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `248 + n * (1 ±0)` - // Minimum execution time: 6_868_000 picoseconds. - Weight::from_parts(7_801_811, 248) + // Minimum execution time: 6_978_000 picoseconds. + Weight::from_parts(7_741_355, 248) // Standard Error: 1 - .saturating_add(Weight::from_parts(605, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(654, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) } @@ -757,10 +767,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `248 + n * (1 ±0)` - // Minimum execution time: 6_322_000 picoseconds. - Weight::from_parts(7_103_552, 248) + // Minimum execution time: 6_286_000 picoseconds. + Weight::from_parts(7_026_923, 248) // Standard Error: 1 - .saturating_add(Weight::from_parts(79, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(86, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) } @@ -771,20 +781,106 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `248 + n * (1 ±0)` - // Minimum execution time: 7_702_000 picoseconds. - Weight::from_parts(8_746_305, 248) - // Standard Error: 2 - .saturating_add(Weight::from_parts(604, 0).saturating_mul(n.into())) + // Minimum execution time: 7_597_000 picoseconds. + Weight::from_parts(8_706_785, 248) + // Standard Error: 1 + .saturating_add(Weight::from_parts(653, 0).saturating_mul(n.into())) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) } + fn set_transient_storage_empty() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_497_000 picoseconds. + Weight::from_parts(1_564_000, 0) + } + fn set_transient_storage_full() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_670_000 picoseconds. + Weight::from_parts(2_807_000, 0) + } + fn get_transient_storage_empty() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 3_836_000 picoseconds. + Weight::from_parts(3_878_000, 0) + } + fn get_transient_storage_full() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 4_537_000 picoseconds. + Weight::from_parts(4_665_000, 0) + } + fn rollback_transient_storage() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_592_000 picoseconds. + Weight::from_parts(1_742_000, 0) + } + /// The range of component `n` is `[0, 16384]`. + /// The range of component `o` is `[0, 16384]`. + fn seal_set_transient_storage(n: u32, o: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 6_101_000 picoseconds. + Weight::from_parts(2_481_218, 0) + // Standard Error: 0 + .saturating_add(Weight::from_parts(242, 0).saturating_mul(n.into())) + // Standard Error: 0 + .saturating_add(Weight::from_parts(300, 0).saturating_mul(o.into())) + } + /// The range of component `n` is `[0, 16384]`. + fn seal_clear_transient_storage(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_059_000 picoseconds. + Weight::from_parts(2_426_609, 0) + // Standard Error: 2 + .saturating_add(Weight::from_parts(307, 0).saturating_mul(n.into())) + } + /// The range of component `n` is `[0, 16384]`. + fn seal_get_transient_storage(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_918_000 picoseconds. + Weight::from_parts(2_114_837, 0) + // Standard Error: 0 + .saturating_add(Weight::from_parts(302, 0).saturating_mul(n.into())) + } + /// The range of component `n` is `[0, 16384]`. + fn seal_contains_transient_storage(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_759_000 picoseconds. + Weight::from_parts(1_959_995, 0) + // Standard Error: 0 + .saturating_add(Weight::from_parts(147, 0).saturating_mul(n.into())) + } + /// The range of component `n` is `[0, 16384]`. + fn seal_take_transient_storage(_n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 9_759_000 picoseconds. + Weight::from_parts(9_952_099, 0) + } fn seal_transfer() -> Weight { // Proof Size summary in bytes: // Measured: `140` // Estimated: `0` - // Minimum execution time: 8_851_000 picoseconds. - Weight::from_parts(9_083_000, 0) + // Minimum execution time: 8_700_000 picoseconds. + Weight::from_parts(8_903_000, 0) } /// Storage: `Contracts::ContractInfoOf` (r:1 w:1) /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) @@ -800,12 +896,12 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `620 + t * (280 ±0)` // Estimated: `4085 + t * (2182 ±0)` - // Minimum execution time: 121_148_000 picoseconds. - Weight::from_parts(119_605_377, 4085) - // Standard Error: 208_337 - .saturating_add(Weight::from_parts(43_153_338, 0).saturating_mul(t.into())) + // Minimum execution time: 123_399_000 picoseconds. + Weight::from_parts(120_909_821, 4085) + // Standard Error: 166_830 + .saturating_add(Weight::from_parts(43_853_642, 0).saturating_mul(t.into())) // Standard Error: 0 - .saturating_add(Weight::from_parts(5, 0).saturating_mul(i.into())) + .saturating_add(Weight::from_parts(6, 0).saturating_mul(i.into())) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(t.into()))) .saturating_add(T::DbWeight::get().writes(1_u64)) @@ -820,8 +916,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `430` // Estimated: `3895` - // Minimum execution time: 108_159_000 picoseconds. - Weight::from_parts(110_027_000, 3895) + // Minimum execution time: 112_350_000 picoseconds. + Weight::from_parts(116_003_000, 3895) .saturating_add(T::DbWeight::get().reads(2_u64)) } /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) @@ -839,13 +935,13 @@ impl WeightInfo for SubstrateWeight { fn seal_instantiate(i: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `676` - // Estimated: `4127` - // Minimum execution time: 1_861_874_000 picoseconds. - Weight::from_parts(1_872_926_000, 4127) - // Standard Error: 23 - .saturating_add(Weight::from_parts(557, 0).saturating_mul(i.into())) - // Standard Error: 23 - .saturating_add(Weight::from_parts(920, 0).saturating_mul(s.into())) + // Estimated: `4132` + // Minimum execution time: 1_972_276_000 picoseconds. + Weight::from_parts(1_977_872_000, 4132) + // Standard Error: 24 + .saturating_add(Weight::from_parts(623, 0).saturating_mul(i.into())) + // Standard Error: 24 + .saturating_add(Weight::from_parts(917, 0).saturating_mul(s.into())) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } @@ -854,64 +950,64 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 878_000 picoseconds. - Weight::from_parts(10_993_950, 0) + // Minimum execution time: 899_000 picoseconds. + Weight::from_parts(10_963_972, 0) // Standard Error: 0 - .saturating_add(Weight::from_parts(1_325, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(1_355, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 1048576]`. fn seal_hash_keccak_256(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_261_000 picoseconds. - Weight::from_parts(9_759_497, 0) + // Minimum execution time: 1_396_000 picoseconds. + Weight::from_parts(9_404_986, 0) // Standard Error: 0 - .saturating_add(Weight::from_parts(3_594, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(3_627, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 1048576]`. fn seal_hash_blake2_256(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 726_000 picoseconds. - Weight::from_parts(9_795_728, 0) + // Minimum execution time: 834_000 picoseconds. + Weight::from_parts(9_749_716, 0) // Standard Error: 0 - .saturating_add(Weight::from_parts(1_455, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(1_500, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 1048576]`. fn seal_hash_blake2_128(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 739_000 picoseconds. - Weight::from_parts(9_701_202, 0) + // Minimum execution time: 756_000 picoseconds. + Weight::from_parts(8_995_036, 0) // Standard Error: 0 - .saturating_add(Weight::from_parts(1_459, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(1_495, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 125697]`. fn seal_sr25519_verify(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 43_309_000 picoseconds. - Weight::from_parts(41_405_949, 0) + // Minimum execution time: 45_800_000 picoseconds. + Weight::from_parts(44_676_829, 0) // Standard Error: 8 - .saturating_add(Weight::from_parts(5_336, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(5_315, 0).saturating_mul(n.into())) } fn seal_ecdsa_recover() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 47_880_000 picoseconds. - Weight::from_parts(49_025_000, 0) + // Minimum execution time: 47_415_000 picoseconds. + Weight::from_parts(48_743_000, 0) } fn seal_ecdsa_to_eth_address() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 13_462_000 picoseconds. - Weight::from_parts(13_631_000, 0) + // Minimum execution time: 13_437_000 picoseconds. + Weight::from_parts(13_588_000, 0) } /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) @@ -921,8 +1017,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `430` // Estimated: `3895` - // Minimum execution time: 17_978_000 picoseconds. - Weight::from_parts(18_578_000, 3895) + // Minimum execution time: 17_775_000 picoseconds. + Weight::from_parts(18_332_000, 3895) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -932,8 +1028,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `355` // Estimated: `3820` - // Minimum execution time: 8_384_000 picoseconds. - Weight::from_parts(8_687_000, 3820) + // Minimum execution time: 8_326_000 picoseconds. + Weight::from_parts(8_656_000, 3820) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -943,8 +1039,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `355` // Estimated: `3558` - // Minimum execution time: 7_547_000 picoseconds. - Weight::from_parts(7_935_000, 3558) + // Minimum execution time: 7_276_000 picoseconds. + Weight::from_parts(7_630_000, 3558) .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -952,15 +1048,15 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 331_000 picoseconds. - Weight::from_parts(363_000, 0) + // Minimum execution time: 330_000 picoseconds. + Weight::from_parts(373_000, 0) } fn seal_account_reentrance_count() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 349_000 picoseconds. - Weight::from_parts(365_000, 0) + // Minimum execution time: 381_000 picoseconds. + Weight::from_parts(418_000, 0) } /// Storage: `Contracts::Nonce` (r:1 w:0) /// Proof: `Contracts::Nonce` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) @@ -968,8 +1064,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `219` // Estimated: `1704` - // Minimum execution time: 2_814_000 picoseconds. - Weight::from_parts(3_038_000, 1704) + // Minimum execution time: 2_711_000 picoseconds. + Weight::from_parts(2_941_000, 1704) .saturating_add(T::DbWeight::get().reads(1_u64)) } /// The range of component `r` is `[0, 5000]`. @@ -977,10 +1073,10 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 693_000 picoseconds. - Weight::from_parts(665_431, 0) - // Standard Error: 12 - .saturating_add(Weight::from_parts(7_030, 0).saturating_mul(r.into())) + // Minimum execution time: 720_000 picoseconds. + Weight::from_parts(389_111, 0) + // Standard Error: 16 + .saturating_add(Weight::from_parts(7_278, 0).saturating_mul(r.into())) } } @@ -992,8 +1088,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `142` // Estimated: `1627` - // Minimum execution time: 1_896_000 picoseconds. - Weight::from_parts(1_990_000, 1627) + // Minimum execution time: 1_921_000 picoseconds. + Weight::from_parts(2_003_000, 1627) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: `Skipped::Metadata` (r:0 w:0) @@ -1003,10 +1099,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `452 + k * (69 ±0)` // Estimated: `442 + k * (70 ±0)` - // Minimum execution time: 11_142_000 picoseconds. - Weight::from_parts(11_578_000, 442) - // Standard Error: 1_557 - .saturating_add(Weight::from_parts(1_165_198, 0).saturating_mul(k.into())) + // Minimum execution time: 11_364_000 picoseconds. + Weight::from_parts(11_463_000, 442) + // Standard Error: 2_141 + .saturating_add(Weight::from_parts(1_149_944, 0).saturating_mul(k.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(k.into()))) .saturating_add(RocksDbWeight::get().writes(2_u64)) @@ -1020,10 +1116,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `211 + c * (1 ±0)` // Estimated: `6149 + c * (1 ±0)` - // Minimum execution time: 7_649_000 picoseconds. - Weight::from_parts(4_827_445, 6149) + // Minimum execution time: 7_565_000 picoseconds. + Weight::from_parts(5_041_009, 6149) // Standard Error: 5 - .saturating_add(Weight::from_parts(1_630, 0).saturating_mul(c.into())) + .saturating_add(Weight::from_parts(1_640, 0).saturating_mul(c.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(c.into())) @@ -1036,8 +1132,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `510` // Estimated: `6450` - // Minimum execution time: 16_096_000 picoseconds. - Weight::from_parts(16_937_000, 6450) + // Minimum execution time: 15_894_000 picoseconds. + Weight::from_parts(16_618_000, 6450) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1050,10 +1146,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `171 + k * (1 ±0)` // Estimated: `3635 + k * (1 ±0)` - // Minimum execution time: 3_131_000 picoseconds. - Weight::from_parts(3_209_000, 3635) - // Standard Error: 481 - .saturating_add(Weight::from_parts(1_087_506, 0).saturating_mul(k.into())) + // Minimum execution time: 3_077_000 picoseconds. + Weight::from_parts(3_144_000, 3635) + // Standard Error: 650 + .saturating_add(Weight::from_parts(1_095_835, 0).saturating_mul(k.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(k.into()))) @@ -1072,10 +1168,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `325 + c * (1 ±0)` // Estimated: `6263 + c * (1 ±0)` - // Minimum execution time: 15_289_000 picoseconds. - Weight::from_parts(16_157_168, 6263) + // Minimum execution time: 14_960_000 picoseconds. + Weight::from_parts(15_778_951, 6263) // Standard Error: 1 - .saturating_add(Weight::from_parts(395, 0).saturating_mul(c.into())) + .saturating_add(Weight::from_parts(443, 0).saturating_mul(c.into())) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(c.into())) @@ -1086,8 +1182,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `440` // Estimated: `6380` - // Minimum execution time: 12_312_000 picoseconds. - Weight::from_parts(12_650_000, 6380) + // Minimum execution time: 11_849_000 picoseconds. + Weight::from_parts(12_273_000, 6380) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1101,8 +1197,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `352` // Estimated: `6292` - // Minimum execution time: 47_239_000 picoseconds. - Weight::from_parts(48_617_000, 6292) + // Minimum execution time: 47_862_000 picoseconds. + Weight::from_parts(48_879_000, 6292) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1114,8 +1210,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `594` // Estimated: `6534` - // Minimum execution time: 52_084_000 picoseconds. - Weight::from_parts(53_838_000, 6534) + // Minimum execution time: 50_754_000 picoseconds. + Weight::from_parts(52_720_000, 6534) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -1125,8 +1221,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `409` // Estimated: `6349` - // Minimum execution time: 11_785_000 picoseconds. - Weight::from_parts(12_284_000, 6349) + // Minimum execution time: 11_459_000 picoseconds. + Weight::from_parts(11_921_000, 6349) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1136,8 +1232,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `142` // Estimated: `1627` - // Minimum execution time: 2_136_000 picoseconds. - Weight::from_parts(2_233_000, 1627) + // Minimum execution time: 2_135_000 picoseconds. + Weight::from_parts(2_247_000, 1627) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1149,8 +1245,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `166` // Estimated: `3631` - // Minimum execution time: 10_957_000 picoseconds. - Weight::from_parts(11_314_000, 3631) + // Minimum execution time: 10_645_000 picoseconds. + Weight::from_parts(11_107_000, 3631) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -1160,8 +1256,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `142` // Estimated: `3607` - // Minimum execution time: 4_354_000 picoseconds. - Weight::from_parts(4_613_000, 3607) + // Minimum execution time: 4_353_000 picoseconds. + Weight::from_parts(4_628_000, 3607) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:0) @@ -1172,8 +1268,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `167` // Estimated: `3632` - // Minimum execution time: 5_541_000 picoseconds. - Weight::from_parts(5_790_000, 3632) + // Minimum execution time: 5_432_000 picoseconds. + Weight::from_parts(5_624_000, 3632) .saturating_add(RocksDbWeight::get().reads(2_u64)) } /// Storage: UNKNOWN KEY `0x4342193e496fab7ec59d615ed0dc55304e7b9012096b41c4eb3aaf947f6ea429` (r:1 w:0) @@ -1184,8 +1280,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `142` // Estimated: `3607` - // Minimum execution time: 5_502_000 picoseconds. - Weight::from_parts(5_701_000, 3607) + // Minimum execution time: 5_371_000 picoseconds. + Weight::from_parts(5_794_000, 3607) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1204,12 +1300,12 @@ impl WeightInfo for () { /// The range of component `c` is `[0, 125952]`. fn call_with_code_per_byte(c: u32, ) -> Weight { // Proof Size summary in bytes: - // Measured: `801 + c * (1 ±0)` - // Estimated: `4264 + c * (1 ±0)` - // Minimum execution time: 247_884_000 picoseconds. - Weight::from_parts(265_795_781, 4264) + // Measured: `800 + c * (1 ±0)` + // Estimated: `4266 + c * (1 ±0)` + // Minimum execution time: 247_157_000 picoseconds. + Weight::from_parts(269_252_698, 4266) // Standard Error: 4 - .saturating_add(Weight::from_parts(724, 0).saturating_mul(c.into())) + .saturating_add(Weight::from_parts(729, 0).saturating_mul(c.into())) .saturating_add(RocksDbWeight::get().reads(6_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(c.into())) @@ -1237,14 +1333,14 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `323` // Estimated: `6262` - // Minimum execution time: 4_500_184_000 picoseconds. - Weight::from_parts(160_729_258, 6262) - // Standard Error: 143 - .saturating_add(Weight::from_parts(52_809, 0).saturating_mul(c.into())) - // Standard Error: 17 - .saturating_add(Weight::from_parts(2_173, 0).saturating_mul(i.into())) - // Standard Error: 17 - .saturating_add(Weight::from_parts(2_165, 0).saturating_mul(s.into())) + // Minimum execution time: 4_575_784_000 picoseconds. + Weight::from_parts(207_379_459, 6262) + // Standard Error: 124 + .saturating_add(Weight::from_parts(52_392, 0).saturating_mul(c.into())) + // Standard Error: 15 + .saturating_add(Weight::from_parts(2_257, 0).saturating_mul(i.into())) + // Standard Error: 15 + .saturating_add(Weight::from_parts(2_263, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(7_u64)) } @@ -1269,13 +1365,13 @@ impl WeightInfo for () { fn instantiate(i: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `560` - // Estimated: `4029` - // Minimum execution time: 2_219_163_000 picoseconds. - Weight::from_parts(2_236_918_000, 4029) - // Standard Error: 32 - .saturating_add(Weight::from_parts(937, 0).saturating_mul(i.into())) - // Standard Error: 32 - .saturating_add(Weight::from_parts(938, 0).saturating_mul(s.into())) + // Estimated: `4017` + // Minimum execution time: 2_306_770_000 picoseconds. + Weight::from_parts(2_462_908_000, 4017) + // Standard Error: 33 + .saturating_add(Weight::from_parts(898, 0).saturating_mul(i.into())) + // Standard Error: 33 + .saturating_add(Weight::from_parts(859, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(8_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } @@ -1295,8 +1391,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `826` // Estimated: `4291` - // Minimum execution time: 164_801_000 picoseconds. - Weight::from_parts(167_250_000, 4291) + // Minimum execution time: 165_499_000 picoseconds. + Weight::from_parts(169_903_000, 4291) .saturating_add(RocksDbWeight::get().reads(6_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -1313,10 +1409,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `142` // Estimated: `3607` - // Minimum execution time: 225_207_000 picoseconds. - Weight::from_parts(263_665_658, 3607) - // Standard Error: 47 - .saturating_add(Weight::from_parts(50_732, 0).saturating_mul(c.into())) + // Minimum execution time: 227_590_000 picoseconds. + Weight::from_parts(260_045_588, 3607) + // Standard Error: 52 + .saturating_add(Weight::from_parts(51_305, 0).saturating_mul(c.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -1333,10 +1429,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `142` // Estimated: `3607` - // Minimum execution time: 230_718_000 picoseconds. - Weight::from_parts(258_359_271, 3607) - // Standard Error: 47 - .saturating_add(Weight::from_parts(51_014, 0).saturating_mul(c.into())) + // Minimum execution time: 239_634_000 picoseconds. + Weight::from_parts(262_040_831, 3607) + // Standard Error: 103 + .saturating_add(Weight::from_parts(51_590, 0).saturating_mul(c.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -1352,8 +1448,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `315` // Estimated: `3780` - // Minimum execution time: 39_668_000 picoseconds. - Weight::from_parts(41_031_000, 3780) + // Minimum execution time: 39_152_000 picoseconds. + Weight::from_parts(39_970_000, 3780) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -1367,8 +1463,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `552` // Estimated: `6492` - // Minimum execution time: 25_890_000 picoseconds. - Weight::from_parts(26_603_000, 6492) + // Minimum execution time: 25_143_000 picoseconds. + Weight::from_parts(26_103_000, 6492) .saturating_add(RocksDbWeight::get().reads(4_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -1377,17 +1473,17 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 8_269_000 picoseconds. - Weight::from_parts(9_227_069, 0) - // Standard Error: 74 - .saturating_add(Weight::from_parts(51_396, 0).saturating_mul(r.into())) + // Minimum execution time: 8_406_000 picoseconds. + Weight::from_parts(9_056_753, 0) + // Standard Error: 98 + .saturating_add(Weight::from_parts(53_110, 0).saturating_mul(r.into())) } fn seal_caller() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 602_000 picoseconds. - Weight::from_parts(664_000, 0) + // Minimum execution time: 659_000 picoseconds. + Weight::from_parts(705_000, 0) } /// Storage: `Contracts::ContractInfoOf` (r:1 w:0) /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) @@ -1395,8 +1491,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `354` // Estimated: `3819` - // Minimum execution time: 6_131_000 picoseconds. - Weight::from_parts(6_468_000, 3819) + // Minimum execution time: 6_165_000 picoseconds. + Weight::from_parts(6_340_000, 3819) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: `Contracts::ContractInfoOf` (r:1 w:0) @@ -1405,79 +1501,79 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `447` // Estimated: `3912` - // Minimum execution time: 7_557_000 picoseconds. - Weight::from_parts(7_704_000, 3912) + // Minimum execution time: 7_398_000 picoseconds. + Weight::from_parts(7_661_000, 3912) .saturating_add(RocksDbWeight::get().reads(1_u64)) } fn seal_own_code_hash() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 783_000 picoseconds. - Weight::from_parts(848_000, 0) + // Minimum execution time: 723_000 picoseconds. + Weight::from_parts(793_000, 0) } fn seal_caller_is_origin() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 397_000 picoseconds. - Weight::from_parts(435_000, 0) + // Minimum execution time: 398_000 picoseconds. + Weight::from_parts(428_000, 0) } fn seal_caller_is_root() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 351_000 picoseconds. - Weight::from_parts(372_000, 0) + // Minimum execution time: 329_000 picoseconds. + Weight::from_parts(364_000, 0) } fn seal_address() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 608_000 picoseconds. - Weight::from_parts(645_000, 0) + // Minimum execution time: 592_000 picoseconds. + Weight::from_parts(624_000, 0) } fn seal_gas_left() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 661_000 picoseconds. - Weight::from_parts(729_000, 0) + // Minimum execution time: 665_000 picoseconds. + Weight::from_parts(714_000, 0) } fn seal_balance() -> Weight { // Proof Size summary in bytes: // Measured: `140` // Estimated: `0` - // Minimum execution time: 4_545_000 picoseconds. - Weight::from_parts(4_663_000, 0) + // Minimum execution time: 4_486_000 picoseconds. + Weight::from_parts(4_668_000, 0) } fn seal_value_transferred() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 614_000 picoseconds. - Weight::from_parts(641_000, 0) + // Minimum execution time: 548_000 picoseconds. + Weight::from_parts(590_000, 0) } fn seal_minimum_balance() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 583_000 picoseconds. - Weight::from_parts(618_000, 0) + // Minimum execution time: 536_000 picoseconds. + Weight::from_parts(578_000, 0) } fn seal_block_number() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 583_000 picoseconds. - Weight::from_parts(617_000, 0) + // Minimum execution time: 552_000 picoseconds. + Weight::from_parts(599_000, 0) } fn seal_now() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 607_000 picoseconds. - Weight::from_parts(638_000, 0) + // Minimum execution time: 556_000 picoseconds. + Weight::from_parts(600_000, 0) } /// Storage: `TransactionPayment::NextFeeMultiplier` (r:1 w:0) /// Proof: `TransactionPayment::NextFeeMultiplier` (`max_values`: Some(1), `max_size`: Some(16), added: 511, mode: `Measured`) @@ -1485,8 +1581,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `67` // Estimated: `1552` - // Minimum execution time: 4_172_000 picoseconds. - Weight::from_parts(4_408_000, 1552) + // Minimum execution time: 4_084_000 picoseconds. + Weight::from_parts(4_321_000, 1552) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// The range of component `n` is `[0, 1048572]`. @@ -1494,20 +1590,20 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 475_000 picoseconds. - Weight::from_parts(515_000, 0) + // Minimum execution time: 468_000 picoseconds. + Weight::from_parts(492_000, 0) // Standard Error: 3 - .saturating_add(Weight::from_parts(298, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(310, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 1048572]`. fn seal_return(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 289_000 picoseconds. - Weight::from_parts(357_000, 0) - // Standard Error: 10 - .saturating_add(Weight::from_parts(405, 0).saturating_mul(n.into())) + // Minimum execution time: 377_000 picoseconds. + Weight::from_parts(396_000, 0) + // Standard Error: 9 + .saturating_add(Weight::from_parts(431, 0).saturating_mul(n.into())) } /// Storage: `Contracts::DeletionQueueCounter` (r:1 w:1) /// Proof: `Contracts::DeletionQueueCounter` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) @@ -1520,10 +1616,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `319 + n * (78 ±0)` // Estimated: `3784 + n * (2553 ±0)` - // Minimum execution time: 13_316_000 picoseconds. - Weight::from_parts(15_855_821, 3784) - // Standard Error: 7_274 - .saturating_add(Weight::from_parts(3_447_246, 0).saturating_mul(n.into())) + // Minimum execution time: 13_028_000 picoseconds. + Weight::from_parts(15_330_917, 3784) + // Standard Error: 8_260 + .saturating_add(Weight::from_parts(3_594_893, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(n.into()))) .saturating_add(RocksDbWeight::get().writes(3_u64)) @@ -1536,8 +1632,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `76` // Estimated: `1561` - // Minimum execution time: 3_468_000 picoseconds. - Weight::from_parts(3_608_000, 1561) + // Minimum execution time: 3_367_000 picoseconds. + Weight::from_parts(3_555_000, 1561) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// Storage: `System::EventTopics` (r:4 w:4) @@ -1548,12 +1644,12 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `990 + t * (2475 ±0)` - // Minimum execution time: 3_777_000 picoseconds. - Weight::from_parts(4_028_191, 990) - // Standard Error: 5_907 - .saturating_add(Weight::from_parts(2_183_733, 0).saturating_mul(t.into())) + // Minimum execution time: 3_779_000 picoseconds. + Weight::from_parts(4_003_836, 990) + // Standard Error: 5_409 + .saturating_add(Weight::from_parts(2_082_176, 0).saturating_mul(t.into())) // Standard Error: 1 - .saturating_add(Weight::from_parts(18, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(14, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(t.into()))) .saturating_add(RocksDbWeight::get().writes((1_u64).saturating_mul(t.into()))) .saturating_add(Weight::from_parts(0, 2475).saturating_mul(t.into())) @@ -1563,10 +1659,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 400_000 picoseconds. - Weight::from_parts(423_000, 0) + // Minimum execution time: 409_000 picoseconds. + Weight::from_parts(447_000, 0) // Standard Error: 10 - .saturating_add(Weight::from_parts(1_209, 0).saturating_mul(i.into())) + .saturating_add(Weight::from_parts(1_219, 0).saturating_mul(i.into())) } /// Storage: `Skipped::Metadata` (r:0 w:0) /// Proof: `Skipped::Metadata` (`max_values`: None, `max_size`: None, mode: `Measured`) @@ -1576,12 +1672,12 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `250 + o * (1 ±0)` // Estimated: `249 + o * (1 ±0)` - // Minimum execution time: 9_033_000 picoseconds. - Weight::from_parts(8_797_934, 249) + // Minimum execution time: 9_176_000 picoseconds. + Weight::from_parts(9_121_191, 249) // Standard Error: 1 - .saturating_add(Weight::from_parts(257, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(292, 0).saturating_mul(n.into())) // Standard Error: 1 - .saturating_add(Weight::from_parts(51, 0).saturating_mul(o.into())) + .saturating_add(Weight::from_parts(31, 0).saturating_mul(o.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(o.into())) @@ -1593,10 +1689,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `248 + n * (1 ±0)` - // Minimum execution time: 7_167_000 picoseconds. - Weight::from_parts(8_012_194, 248) + // Minimum execution time: 7_294_000 picoseconds. + Weight::from_parts(7_963_151, 248) // Standard Error: 1 - .saturating_add(Weight::from_parts(90, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(92, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) @@ -1608,10 +1704,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `248 + n * (1 ±0)` - // Minimum execution time: 6_868_000 picoseconds. - Weight::from_parts(7_801_811, 248) + // Minimum execution time: 6_978_000 picoseconds. + Weight::from_parts(7_741_355, 248) // Standard Error: 1 - .saturating_add(Weight::from_parts(605, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(654, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) } @@ -1622,10 +1718,10 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `248 + n * (1 ±0)` - // Minimum execution time: 6_322_000 picoseconds. - Weight::from_parts(7_103_552, 248) + // Minimum execution time: 6_286_000 picoseconds. + Weight::from_parts(7_026_923, 248) // Standard Error: 1 - .saturating_add(Weight::from_parts(79, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(86, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) } @@ -1636,20 +1732,106 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `248 + n * (1 ±0)` // Estimated: `248 + n * (1 ±0)` - // Minimum execution time: 7_702_000 picoseconds. - Weight::from_parts(8_746_305, 248) - // Standard Error: 2 - .saturating_add(Weight::from_parts(604, 0).saturating_mul(n.into())) + // Minimum execution time: 7_597_000 picoseconds. + Weight::from_parts(8_706_785, 248) + // Standard Error: 1 + .saturating_add(Weight::from_parts(653, 0).saturating_mul(n.into())) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) .saturating_add(Weight::from_parts(0, 1).saturating_mul(n.into())) } + fn set_transient_storage_empty() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_497_000 picoseconds. + Weight::from_parts(1_564_000, 0) + } + fn set_transient_storage_full() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_670_000 picoseconds. + Weight::from_parts(2_807_000, 0) + } + fn get_transient_storage_empty() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 3_836_000 picoseconds. + Weight::from_parts(3_878_000, 0) + } + fn get_transient_storage_full() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 4_537_000 picoseconds. + Weight::from_parts(4_665_000, 0) + } + fn rollback_transient_storage() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_592_000 picoseconds. + Weight::from_parts(1_742_000, 0) + } + /// The range of component `n` is `[0, 16384]`. + /// The range of component `o` is `[0, 16384]`. + fn seal_set_transient_storage(n: u32, o: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 6_101_000 picoseconds. + Weight::from_parts(2_481_218, 0) + // Standard Error: 0 + .saturating_add(Weight::from_parts(242, 0).saturating_mul(n.into())) + // Standard Error: 0 + .saturating_add(Weight::from_parts(300, 0).saturating_mul(o.into())) + } + /// The range of component `n` is `[0, 16384]`. + fn seal_clear_transient_storage(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 2_059_000 picoseconds. + Weight::from_parts(2_426_609, 0) + // Standard Error: 2 + .saturating_add(Weight::from_parts(307, 0).saturating_mul(n.into())) + } + /// The range of component `n` is `[0, 16384]`. + fn seal_get_transient_storage(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_918_000 picoseconds. + Weight::from_parts(2_114_837, 0) + // Standard Error: 0 + .saturating_add(Weight::from_parts(302, 0).saturating_mul(n.into())) + } + /// The range of component `n` is `[0, 16384]`. + fn seal_contains_transient_storage(n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 1_759_000 picoseconds. + Weight::from_parts(1_959_995, 0) + // Standard Error: 0 + .saturating_add(Weight::from_parts(147, 0).saturating_mul(n.into())) + } + /// The range of component `n` is `[0, 16384]`. + fn seal_take_transient_storage(_n: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 9_759_000 picoseconds. + Weight::from_parts(9_952_099, 0) + } fn seal_transfer() -> Weight { // Proof Size summary in bytes: // Measured: `140` // Estimated: `0` - // Minimum execution time: 8_851_000 picoseconds. - Weight::from_parts(9_083_000, 0) + // Minimum execution time: 8_700_000 picoseconds. + Weight::from_parts(8_903_000, 0) } /// Storage: `Contracts::ContractInfoOf` (r:1 w:1) /// Proof: `Contracts::ContractInfoOf` (`max_values`: None, `max_size`: Some(1795), added: 4270, mode: `Measured`) @@ -1665,12 +1847,12 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `620 + t * (280 ±0)` // Estimated: `4085 + t * (2182 ±0)` - // Minimum execution time: 121_148_000 picoseconds. - Weight::from_parts(119_605_377, 4085) - // Standard Error: 208_337 - .saturating_add(Weight::from_parts(43_153_338, 0).saturating_mul(t.into())) + // Minimum execution time: 123_399_000 picoseconds. + Weight::from_parts(120_909_821, 4085) + // Standard Error: 166_830 + .saturating_add(Weight::from_parts(43_853_642, 0).saturating_mul(t.into())) // Standard Error: 0 - .saturating_add(Weight::from_parts(5, 0).saturating_mul(i.into())) + .saturating_add(Weight::from_parts(6, 0).saturating_mul(i.into())) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(t.into()))) .saturating_add(RocksDbWeight::get().writes(1_u64)) @@ -1685,8 +1867,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `430` // Estimated: `3895` - // Minimum execution time: 108_159_000 picoseconds. - Weight::from_parts(110_027_000, 3895) + // Minimum execution time: 112_350_000 picoseconds. + Weight::from_parts(116_003_000, 3895) .saturating_add(RocksDbWeight::get().reads(2_u64)) } /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) @@ -1704,13 +1886,13 @@ impl WeightInfo for () { fn seal_instantiate(i: u32, s: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `676` - // Estimated: `4127` - // Minimum execution time: 1_861_874_000 picoseconds. - Weight::from_parts(1_872_926_000, 4127) - // Standard Error: 23 - .saturating_add(Weight::from_parts(557, 0).saturating_mul(i.into())) - // Standard Error: 23 - .saturating_add(Weight::from_parts(920, 0).saturating_mul(s.into())) + // Estimated: `4132` + // Minimum execution time: 1_972_276_000 picoseconds. + Weight::from_parts(1_977_872_000, 4132) + // Standard Error: 24 + .saturating_add(Weight::from_parts(623, 0).saturating_mul(i.into())) + // Standard Error: 24 + .saturating_add(Weight::from_parts(917, 0).saturating_mul(s.into())) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } @@ -1719,64 +1901,64 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 878_000 picoseconds. - Weight::from_parts(10_993_950, 0) + // Minimum execution time: 899_000 picoseconds. + Weight::from_parts(10_963_972, 0) // Standard Error: 0 - .saturating_add(Weight::from_parts(1_325, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(1_355, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 1048576]`. fn seal_hash_keccak_256(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 1_261_000 picoseconds. - Weight::from_parts(9_759_497, 0) + // Minimum execution time: 1_396_000 picoseconds. + Weight::from_parts(9_404_986, 0) // Standard Error: 0 - .saturating_add(Weight::from_parts(3_594, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(3_627, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 1048576]`. fn seal_hash_blake2_256(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 726_000 picoseconds. - Weight::from_parts(9_795_728, 0) + // Minimum execution time: 834_000 picoseconds. + Weight::from_parts(9_749_716, 0) // Standard Error: 0 - .saturating_add(Weight::from_parts(1_455, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(1_500, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 1048576]`. fn seal_hash_blake2_128(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 739_000 picoseconds. - Weight::from_parts(9_701_202, 0) + // Minimum execution time: 756_000 picoseconds. + Weight::from_parts(8_995_036, 0) // Standard Error: 0 - .saturating_add(Weight::from_parts(1_459, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(1_495, 0).saturating_mul(n.into())) } /// The range of component `n` is `[0, 125697]`. fn seal_sr25519_verify(n: u32, ) -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 43_309_000 picoseconds. - Weight::from_parts(41_405_949, 0) + // Minimum execution time: 45_800_000 picoseconds. + Weight::from_parts(44_676_829, 0) // Standard Error: 8 - .saturating_add(Weight::from_parts(5_336, 0).saturating_mul(n.into())) + .saturating_add(Weight::from_parts(5_315, 0).saturating_mul(n.into())) } fn seal_ecdsa_recover() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 47_880_000 picoseconds. - Weight::from_parts(49_025_000, 0) + // Minimum execution time: 47_415_000 picoseconds. + Weight::from_parts(48_743_000, 0) } fn seal_ecdsa_to_eth_address() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 13_462_000 picoseconds. - Weight::from_parts(13_631_000, 0) + // Minimum execution time: 13_437_000 picoseconds. + Weight::from_parts(13_588_000, 0) } /// Storage: `Contracts::CodeInfoOf` (r:1 w:1) /// Proof: `Contracts::CodeInfoOf` (`max_values`: None, `max_size`: Some(93), added: 2568, mode: `Measured`) @@ -1786,8 +1968,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `430` // Estimated: `3895` - // Minimum execution time: 17_978_000 picoseconds. - Weight::from_parts(18_578_000, 3895) + // Minimum execution time: 17_775_000 picoseconds. + Weight::from_parts(18_332_000, 3895) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1797,8 +1979,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `355` // Estimated: `3820` - // Minimum execution time: 8_384_000 picoseconds. - Weight::from_parts(8_687_000, 3820) + // Minimum execution time: 8_326_000 picoseconds. + Weight::from_parts(8_656_000, 3820) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1808,8 +1990,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `355` // Estimated: `3558` - // Minimum execution time: 7_547_000 picoseconds. - Weight::from_parts(7_935_000, 3558) + // Minimum execution time: 7_276_000 picoseconds. + Weight::from_parts(7_630_000, 3558) .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -1817,15 +1999,15 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 331_000 picoseconds. - Weight::from_parts(363_000, 0) + // Minimum execution time: 330_000 picoseconds. + Weight::from_parts(373_000, 0) } fn seal_account_reentrance_count() -> Weight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 349_000 picoseconds. - Weight::from_parts(365_000, 0) + // Minimum execution time: 381_000 picoseconds. + Weight::from_parts(418_000, 0) } /// Storage: `Contracts::Nonce` (r:1 w:0) /// Proof: `Contracts::Nonce` (`max_values`: Some(1), `max_size`: Some(8), added: 503, mode: `Measured`) @@ -1833,8 +2015,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `219` // Estimated: `1704` - // Minimum execution time: 2_814_000 picoseconds. - Weight::from_parts(3_038_000, 1704) + // Minimum execution time: 2_711_000 picoseconds. + Weight::from_parts(2_941_000, 1704) .saturating_add(RocksDbWeight::get().reads(1_u64)) } /// The range of component `r` is `[0, 5000]`. @@ -1842,9 +2024,9 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 693_000 picoseconds. - Weight::from_parts(665_431, 0) - // Standard Error: 12 - .saturating_add(Weight::from_parts(7_030, 0).saturating_mul(r.into())) + // Minimum execution time: 720_000 picoseconds. + Weight::from_parts(389_111, 0) + // Standard Error: 16 + .saturating_add(Weight::from_parts(7_278, 0).saturating_mul(r.into())) } } diff --git a/substrate/frame/contracts/uapi/src/host.rs b/substrate/frame/contracts/uapi/src/host.rs index 92065eda5d635352a0d7f7facb743960ba9189b7..51f0cd7eb2dc002ff041f1f27589f243e22cb896 100644 --- a/substrate/frame/contracts/uapi/src/host.rs +++ b/substrate/frame/contracts/uapi/src/host.rs @@ -67,7 +67,7 @@ fn ptr_or_sentinel(data: &Option<&[u8]>) -> *const u8 { pub enum HostFnImpl {} /// Defines all the host apis implemented by both wasm and RISC-V vms. -pub trait HostFn { +pub trait HostFn: private::Sealed { /// Returns the number of times specified contract exists on the call stack. Delegated calls are /// not counted as separate calls. /// @@ -292,6 +292,20 @@ pub trait HostFn { /// Returns the size of the pre-existing value at the specified key if any. fn clear_storage_v1(key: &[u8]) -> Option; + /// Clear the value at the given key in the contract transient storage. + /// + /// # Parameters + /// + /// - `key`: The storage key. + /// + /// # Return + /// + /// Returns the size of the pre-existing value at the specified key if any. + #[deprecated( + note = "Unstable function. Behaviour can change without further notice. Use only for testing." + )] + fn clear_transient_storage(key: &[u8]) -> Option; + /// Retrieve the code hash for a specified contract address. /// /// # Parameters @@ -324,6 +338,21 @@ pub trait HostFn { /// Returns the size of the pre-existing value at the specified key if any. fn contains_storage_v1(key: &[u8]) -> Option; + /// Checks whether there is a value stored under the given key in transient storage. + /// + /// The key length must not exceed the maximum defined by the contracts module parameter. + /// + /// # Parameters + /// - `key`: The storage key. + /// + /// # Return + /// + /// Returns the size of the pre-existing value at the specified key if any. + #[deprecated( + note = "Unstable function. Behaviour can change without further notice. Use only for testing." + )] + fn contains_transient_storage(key: &[u8]) -> Option; + /// Emit a custom debug message. /// /// No newlines are added to the supplied message. @@ -453,6 +482,22 @@ pub trait HostFn { /// [KeyNotFound][`crate::ReturnErrorCode::KeyNotFound] fn get_storage_v1(key: &[u8], output: &mut &mut [u8]) -> Result; + /// Retrieve the value under the given key from transient storage. + /// + /// The key length must not exceed the maximum defined by the contracts module parameter. + /// + /// # Parameters + /// - `key`: The storage key. + /// - `output`: A reference to the output data buffer to write the storage entry. + /// + /// # Errors + /// + /// [KeyNotFound][`crate::ReturnErrorCode::KeyNotFound] + #[deprecated( + note = "Unstable function. Behaviour can change without further notice. Use only for testing." + )] + fn get_transient_storage(key: &[u8], output: &mut &mut [u8]) -> Result; + hash_fn!(sha2_256, 32); hash_fn!(keccak_256, 32); hash_fn!(blake2_256, 32); @@ -673,6 +718,24 @@ pub trait HostFn { /// Returns the size of the pre-existing value at the specified key if any. fn set_storage_v2(key: &[u8], value: &[u8]) -> Option; + /// Set the value at the given key in the contract transient storage. + /// + /// The key and value lengths must not exceed the maximums defined by the contracts module + /// parameters. + /// + /// # Parameters + /// + /// - `key`: The storage key. + /// - `encoded_value`: The storage value. + /// + /// # Return + /// + /// Returns the size of the pre-existing value at the specified key if any. + #[deprecated( + note = "Unstable function. Behaviour can change without further notice. Use only for testing." + )] + fn set_transient_storage(key: &[u8], value: &[u8]) -> Option; + /// Verify a sr25519 signature /// /// # Parameters @@ -696,6 +759,20 @@ pub trait HostFn { /// [KeyNotFound][`crate::ReturnErrorCode::KeyNotFound] fn take_storage(key: &[u8], output: &mut &mut [u8]) -> Result; + /// Retrieve and remove the value under the given key from transient storage. + /// + /// # Parameters + /// - `key`: The storage key. + /// - `output`: A reference to the output data buffer to write the storage entry. + /// + /// # Errors + /// + /// [KeyNotFound][`crate::ReturnErrorCode::KeyNotFound] + #[deprecated( + note = "Unstable function. Behaviour can change without further notice. Use only for testing." + )] + fn take_transient_storage(key: &[u8], output: &mut &mut [u8]) -> Result; + /// Transfer some amount of funds into the specified account. /// /// # Parameters @@ -804,3 +881,8 @@ pub trait HostFn { )] fn xcm_send(dest: &[u8], msg: &[u8], output: &mut [u8; 32]) -> Result; } + +mod private { + pub trait Sealed {} + impl Sealed for super::HostFnImpl {} +} diff --git a/substrate/frame/contracts/uapi/src/host/riscv32.rs b/substrate/frame/contracts/uapi/src/host/riscv32.rs index 561ab28747df9e55d105d6db09f4776d5e453e28..355520233212113df9b864add68d52f4b368ee60 100644 --- a/substrate/frame/contracts/uapi/src/host/riscv32.rs +++ b/substrate/frame/contracts/uapi/src/host/riscv32.rs @@ -172,6 +172,10 @@ impl HostFn for HostFnImpl { todo!() } + fn set_transient_storage(key: &[u8], encoded_value: &[u8]) -> Option { + todo!() + } + fn clear_storage(key: &[u8]) { todo!() } @@ -180,13 +184,25 @@ impl HostFn for HostFnImpl { todo!() } + fn clear_transient_storage(key: &[u8]) -> Option { + todo!() + } + impl_get_storage!(get_storage, sys::get_storage); impl_get_storage!(get_storage_v1, sys::v1::get_storage); + fn get_transient_storage(key: &[u8], output: &mut &mut [u8]) -> Result { + todo!() + } + fn take_storage(key: &[u8], output: &mut &mut [u8]) -> Result { todo!() } + fn take_transient_storage(key: &[u8], output: &mut &mut [u8]) -> Result { + todo!() + } + fn contains_storage(key: &[u8]) -> Option { todo!() } @@ -195,6 +211,10 @@ impl HostFn for HostFnImpl { todo!() } + fn contains_transient_storage(key: &[u8]) -> Option { + todo!() + } + fn terminate(beneficiary: &[u8]) -> ! { todo!() } diff --git a/substrate/frame/contracts/uapi/src/host/wasm32.rs b/substrate/frame/contracts/uapi/src/host/wasm32.rs index cb5435bfc014ddd268b4b36c6dd86ce534be9042..55600bc3201f034b1bc15094593097b504ea2aa1 100644 --- a/substrate/frame/contracts/uapi/src/host/wasm32.rs +++ b/substrate/frame/contracts/uapi/src/host/wasm32.rs @@ -61,6 +61,8 @@ mod sys { pub fn clear_storage(key_ptr: *const u8); + pub fn clear_transient_storage(key_ptr: *const u8, key_len: u32) -> ReturnCode; + pub fn code_hash( account_id_ptr: *const u8, output_ptr: *mut u8, @@ -69,6 +71,8 @@ mod sys { pub fn contains_storage(key_ptr: *const u8) -> ReturnCode; + pub fn contains_transient_storage(key_ptr: *const u8, key_len: u32) -> ReturnCode; + pub fn debug_message(str_ptr: *const u8, str_len: u32) -> ReturnCode; pub fn delegate_call( @@ -103,6 +107,13 @@ mod sys { out_len_ptr: *mut u32, ) -> ReturnCode; + pub fn get_transient_storage( + key_ptr: *const u8, + key_len: u32, + out_ptr: *mut u8, + out_len_ptr: *mut u32, + ) -> ReturnCode; + pub fn hash_blake2_128(input_ptr: *const u8, input_len: u32, output_ptr: *mut u8); pub fn hash_blake2_256(input_ptr: *const u8, input_len: u32, output_ptr: *mut u8); @@ -133,6 +144,13 @@ mod sys { pub fn set_storage(key_ptr: *const u8, value_ptr: *const u8, value_len: u32); + pub fn set_transient_storage( + key_ptr: *const u8, + key_len: u32, + value_ptr: *const u8, + value_len: u32, + ) -> ReturnCode; + pub fn sr25519_verify( signature_ptr: *const u8, public_key_ptr: *const u8, @@ -147,6 +165,13 @@ mod sys { out_len_ptr: *mut u32, ) -> ReturnCode; + pub fn take_transient_storage( + key_ptr: *const u8, + key_len: u32, + out_ptr: *mut u8, + out_len_ptr: *mut u32, + ) -> ReturnCode; + pub fn terminate(beneficiary_ptr: *const u8) -> !; pub fn transfer( @@ -598,6 +623,18 @@ impl HostFn for HostFnImpl { ret_code.into() } + fn set_transient_storage(key: &[u8], encoded_value: &[u8]) -> Option { + let ret_code = unsafe { + sys::set_transient_storage( + key.as_ptr(), + key.len() as u32, + encoded_value.as_ptr(), + encoded_value.len() as u32, + ) + }; + ret_code.into() + } + fn clear_storage(key: &[u8]) { unsafe { sys::clear_storage(key.as_ptr()) }; } @@ -607,6 +644,11 @@ impl HostFn for HostFnImpl { ret_code.into() } + fn clear_transient_storage(key: &[u8]) -> Option { + let ret_code = unsafe { sys::clear_transient_storage(key.as_ptr(), key.len() as u32) }; + ret_code.into() + } + #[inline(always)] fn get_storage(key: &[u8], output: &mut &mut [u8]) -> Result { let mut output_len = output.len() as u32; @@ -633,6 +675,23 @@ impl HostFn for HostFnImpl { ret_code.into() } + #[inline(always)] + fn get_transient_storage(key: &[u8], output: &mut &mut [u8]) -> Result { + let mut output_len = output.len() as u32; + let ret_code = { + unsafe { + sys::get_transient_storage( + key.as_ptr(), + key.len() as u32, + output.as_mut_ptr(), + &mut output_len, + ) + } + }; + extract_from_slice(output, output_len as usize); + ret_code.into() + } + #[inline(always)] fn take_storage(key: &[u8], output: &mut &mut [u8]) -> Result { let mut output_len = output.len() as u32; @@ -650,6 +709,23 @@ impl HostFn for HostFnImpl { ret_code.into() } + #[inline(always)] + fn take_transient_storage(key: &[u8], output: &mut &mut [u8]) -> Result { + let mut output_len = output.len() as u32; + let ret_code = { + unsafe { + sys::take_transient_storage( + key.as_ptr(), + key.len() as u32, + output.as_mut_ptr(), + &mut output_len, + ) + } + }; + extract_from_slice(output, output_len as usize); + ret_code.into() + } + fn debug_message(str: &[u8]) -> Result { let ret_code = unsafe { sys::debug_message(str.as_ptr(), str.len() as u32) }; ret_code.into() @@ -665,6 +741,11 @@ impl HostFn for HostFnImpl { ret_code.into() } + fn contains_transient_storage(key: &[u8]) -> Option { + let ret_code = unsafe { sys::contains_transient_storage(key.as_ptr(), key.len() as u32) }; + ret_code.into() + } + fn terminate(beneficiary: &[u8]) -> ! { unsafe { sys::terminate(beneficiary.as_ptr()) } } diff --git a/substrate/frame/conviction-voting/Cargo.toml b/substrate/frame/conviction-voting/Cargo.toml index b96809b8aeb4d2a1011c003471f3c918157e60a9..6184b0ffd6e67d4c47299b1372ebdc57273f16d2 100644 --- a/substrate/frame/conviction-voting/Cargo.toml +++ b/substrate/frame/conviction-voting/Cargo.toml @@ -28,7 +28,6 @@ frame-support = { workspace = true } frame-system = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] pallet-balances = { workspace = true, default-features = true } @@ -49,7 +48,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/conviction-voting/src/benchmarking.rs b/substrate/frame/conviction-voting/src/benchmarking.rs index 8701ed7ebb074273b161a980ef0f6650d1ced11b..546ad5385355e23316c24ca19ee83dc07cf497b8 100644 --- a/substrate/frame/conviction-voting/src/benchmarking.rs +++ b/substrate/frame/conviction-voting/src/benchmarking.rs @@ -19,6 +19,7 @@ use super::*; +use alloc::{collections::btree_map::BTreeMap, vec::Vec}; use assert_matches::assert_matches; use frame_benchmarking::v1::{account, benchmarks_instance_pallet, whitelist_account}; use frame_support::{ @@ -30,7 +31,6 @@ use frame_support::{ }, }; use sp_runtime::traits::Bounded; -use sp_std::collections::btree_map::BTreeMap; use crate::Pallet as ConvictionVoting; diff --git a/substrate/frame/conviction-voting/src/lib.rs b/substrate/frame/conviction-voting/src/lib.rs index 466fc70a619b649e4b1aade0002e506dde430a1e..be7f7f448070fe57d77df6e02d05745acdfa422b 100644 --- a/substrate/frame/conviction-voting/src/lib.rs +++ b/substrate/frame/conviction-voting/src/lib.rs @@ -27,6 +27,8 @@ #![recursion_limit = "256"] #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + use frame_support::{ dispatch::DispatchResult, ensure, @@ -40,7 +42,6 @@ use sp_runtime::{ traits::{AtLeast32BitUnsigned, Saturating, StaticLookup, Zero}, ArithmeticError, DispatchError, Perbill, }; -use sp_std::prelude::*; mod conviction; mod types; @@ -559,7 +560,7 @@ impl, I: 'static> Pallet { ensure!(balance <= T::Currency::total_balance(&who), Error::::InsufficientFunds); let votes = VotingFor::::try_mutate(&who, &class, |voting| -> Result { - let old = sp_std::mem::replace( + let old = core::mem::replace( voting, Voting::Delegating(Delegating { balance, @@ -596,7 +597,7 @@ impl, I: 'static> Pallet { fn try_undelegate(who: T::AccountId, class: ClassOf) -> Result { let votes = VotingFor::::try_mutate(&who, &class, |voting| -> Result { - match sp_std::mem::replace(voting, Voting::default()) { + match core::mem::replace(voting, Voting::default()) { Voting::Delegating(Delegating { balance, target, diff --git a/substrate/frame/conviction-voting/src/types.rs b/substrate/frame/conviction-voting/src/types.rs index 2c45b54485bd95c5d0e6e97b114ea199b376444f..d6bbb678a14b3129e0ae75db0271d7f9c25f6875 100644 --- a/substrate/frame/conviction-voting/src/types.rs +++ b/substrate/frame/conviction-voting/src/types.rs @@ -18,6 +18,7 @@ //! Miscellaneous additional datatypes. use codec::{Codec, Decode, Encode, MaxEncodedLen}; +use core::{fmt::Debug, marker::PhantomData}; use frame_support::{ traits::VoteTally, CloneNoBound, EqNoBound, PartialEqNoBound, RuntimeDebugNoBound, }; @@ -26,7 +27,6 @@ use sp_runtime::{ traits::{Saturating, Zero}, RuntimeDebug, }; -use sp_std::{fmt::Debug, marker::PhantomData}; use super::*; use crate::{AccountVote, Conviction, Vote}; diff --git a/substrate/frame/conviction-voting/src/vote.rs b/substrate/frame/conviction-voting/src/vote.rs index 5ae08f0de65f269ad71cf1e7679e5421be4fa3db..1c5b742ba12b16714b7c886d94b374c8d2dde5a3 100644 --- a/substrate/frame/conviction-voting/src/vote.rs +++ b/substrate/frame/conviction-voting/src/vote.rs @@ -25,7 +25,6 @@ use sp_runtime::{ traits::{Saturating, Zero}, RuntimeDebug, }; -use sp_std::prelude::*; /// A number of lock periods, plus a vote, one way or the other. #[derive(Copy, Clone, Eq, PartialEq, Default, RuntimeDebug, MaxEncodedLen)] diff --git a/substrate/frame/core-fellowship/Cargo.toml b/substrate/frame/core-fellowship/Cargo.toml index 44290402594a956e58250cf4086d4f0e9cc4400f..7ef6f9e11eb1129e8491d884ddcdac571a950a14 100644 --- a/substrate/frame/core-fellowship/Cargo.toml +++ b/substrate/frame/core-fellowship/Cargo.toml @@ -26,7 +26,6 @@ sp-arithmetic = { workspace = true } sp-core = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } pallet-ranked-collective = { optional = true, workspace = true } [features] @@ -44,7 +43,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/core-fellowship/src/benchmarking.rs b/substrate/frame/core-fellowship/src/benchmarking.rs index 34461e062b35cc73c727e81fcdb9ab9081c2580c..adb8a4a091b8dcf473277763d992a632e3fb539a 100644 --- a/substrate/frame/core-fellowship/src/benchmarking.rs +++ b/substrate/frame/core-fellowship/src/benchmarking.rs @@ -22,6 +22,7 @@ use super::*; use crate::Pallet as CoreFellowship; +use alloc::{boxed::Box, vec}; use frame_benchmarking::v2::*; use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; use sp_arithmetic::traits::Bounded; diff --git a/substrate/frame/core-fellowship/src/lib.rs b/substrate/frame/core-fellowship/src/lib.rs index 5ed2562d6d019b9a85e3974005831861a3e37887..c61447e36280a93e0ce553116c8b868d606061a3 100644 --- a/substrate/frame/core-fellowship/src/lib.rs +++ b/substrate/frame/core-fellowship/src/lib.rs @@ -57,11 +57,14 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + +use alloc::boxed::Box; use codec::{Decode, Encode, MaxEncodedLen}; +use core::{fmt::Debug, marker::PhantomData}; use scale_info::TypeInfo; use sp_arithmetic::traits::{Saturating, Zero}; use sp_runtime::RuntimeDebug; -use sp_std::{fmt::Debug, marker::PhantomData, prelude::*}; use frame_support::{ defensive, diff --git a/substrate/frame/core-fellowship/src/migration.rs b/substrate/frame/core-fellowship/src/migration.rs index b8b5540a4b475be0a5a40ec2324b94f71d0da9c8..b1e27d1e79363c8beff890a578edda832ccb8349 100644 --- a/substrate/frame/core-fellowship/src/migration.rs +++ b/substrate/frame/core-fellowship/src/migration.rs @@ -24,6 +24,8 @@ use frame_support::{ BoundedVec, }; +#[cfg(feature = "try-runtime")] +use alloc::vec::Vec; #[cfg(feature = "try-runtime")] use sp_runtime::TryRuntimeError; diff --git a/substrate/frame/delegated-staking/Cargo.toml b/substrate/frame/delegated-staking/Cargo.toml index 0c1bcf0df0c5e3422367d64ec3c3d21e85f50e75..a7751e1d6c1ca1b7bf32da1d260e72c2729ad8e5 100644 --- a/substrate/frame/delegated-staking/Cargo.toml +++ b/substrate/frame/delegated-staking/Cargo.toml @@ -16,7 +16,6 @@ codec = { features = ["derive"], workspace = true } frame-support = { workspace = true } frame-system = { workspace = true } scale-info = { features = ["derive"], workspace = true } -sp-std = { workspace = true } sp-runtime = { workspace = true } sp-staking = { workspace = true } @@ -48,7 +47,6 @@ std = [ "sp-io/std", "sp-runtime/std", "sp-staking/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-election-provider-support/runtime-benchmarks", diff --git a/substrate/frame/delegated-staking/src/impls.rs b/substrate/frame/delegated-staking/src/impls.rs index 9f5649672d70e9e55ad84350d0be53bd4abb2b0f..f8df9dfe7b46c9c1730321d657bbd9b3e11617c8 100644 --- a/substrate/frame/delegated-staking/src/impls.rs +++ b/substrate/frame/delegated-staking/src/impls.rs @@ -139,7 +139,7 @@ impl OnStakingUpdate> for Pallet { fn on_slash( who: &T::AccountId, _slashed_active: BalanceOf, - _slashed_unlocking: &sp_std::collections::btree_map::BTreeMap>, + _slashed_unlocking: &alloc::collections::btree_map::BTreeMap>, slashed_total: BalanceOf, ) { >::mutate(who, |maybe_register| match maybe_register { diff --git a/substrate/frame/delegated-staking/src/lib.rs b/substrate/frame/delegated-staking/src/lib.rs index f16bb0d1dc08da50f7c936726b107c7ad35b3fc1..8203f75133057dff3b2856a635b762876168da56 100644 --- a/substrate/frame/delegated-staking/src/lib.rs +++ b/substrate/frame/delegated-staking/src/lib.rs @@ -132,10 +132,13 @@ mod mock; mod tests; mod types; +extern crate alloc; + pub use pallet::*; use types::*; +use core::convert::TryInto; use frame_support::{ pallet_prelude::*, traits::{ @@ -154,7 +157,6 @@ use sp_runtime::{ ArithmeticError, DispatchResult, Perbill, RuntimeDebug, Saturating, }; use sp_staking::{Agent, Delegator, EraIndex, StakingInterface, StakingUnchecked}; -use sp_std::{convert::TryInto, prelude::*}; pub type BalanceOf = <::Currency as FunInspect<::AccountId>>::Balance; @@ -409,6 +411,11 @@ pub mod pallet { Delegation::::can_delegate(&delegator, &agent), Error::::InvalidDelegation ); + + // Implementation note: Staking uses deprecated locks (similar to freeze) which are not + // mutually exclusive of holds. This means, if we allow delegating for existing stakers, + // already staked funds might be reused for delegation. We avoid that by just blocking + // this. ensure!(!Self::is_direct_staker(&delegator), Error::::AlreadyStaking); // ensure agent is sane. @@ -503,7 +510,7 @@ impl Pallet { Preservation::Expendable, )?; - T::CoreStaking::update_payee(who, reward_account)?; + T::CoreStaking::set_payee(who, reward_account)?; // delegate all transferred funds back to agent. Self::do_delegate(proxy_delegator, Agent::from(who.clone()), amount_to_transfer)?; @@ -779,7 +786,7 @@ impl Pallet { } #[cfg(any(test, feature = "try-runtime"))] -use sp_std::collections::btree_map::BTreeMap; +use alloc::collections::btree_map::BTreeMap; #[cfg(any(test, feature = "try-runtime"))] impl Pallet { diff --git a/substrate/frame/delegated-staking/src/tests.rs b/substrate/frame/delegated-staking/src/tests.rs index 385bb17ddadbdf8f5a6bc2748a767d6ec72bfc5b..ade0872dd3900d0f44962de2e89e4b47247ce06d 100644 --- a/substrate/frame/delegated-staking/src/tests.rs +++ b/substrate/frame/delegated-staking/src/tests.rs @@ -573,14 +573,14 @@ mod staking_integration { 100 )); - // update_payee to self fails. + // set_payee to self fails. assert_noop!( - ::update_payee(&200, &200), + ::set_payee(&200, &200), StakingError::::RewardDestinationRestricted ); // passing correct reward destination works - assert_ok!(::update_payee(&200, &201)); + assert_ok!(::set_payee(&200, &201)); // amount is staked correctly assert!(eq_stake(200, 100, 100)); diff --git a/substrate/frame/democracy/Cargo.toml b/substrate/frame/democracy/Cargo.toml index 6a44951e09c4bbf1a64ccff0b60459aba5865193..ce5ffa57d579882943411db7e043ebc73e9cb8c9 100644 --- a/substrate/frame/democracy/Cargo.toml +++ b/substrate/frame/democracy/Cargo.toml @@ -26,7 +26,6 @@ frame-support = { workspace = true } frame-system = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } sp-core = { workspace = true } log = { workspace = true } @@ -51,7 +50,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/democracy/src/benchmarking.rs b/substrate/frame/democracy/src/benchmarking.rs index 799d614c37f4a87a147c1d1e0c21febc1ad68cd3..ee36e9212f52b44b592247b6a3348a2ad54b45d8 100644 --- a/substrate/frame/democracy/src/benchmarking.rs +++ b/substrate/frame/democracy/src/benchmarking.rs @@ -85,8 +85,8 @@ fn assert_has_event(generic_event: ::RuntimeEvent) { // note a new preimage. fn note_preimage() -> T::Hash { + use alloc::borrow::Cow; use core::sync::atomic::{AtomicU8, Ordering}; - use sp_std::borrow::Cow; // note a new preimage on every function invoke. static COUNTER: AtomicU8 = AtomicU8::new(0); let data = Cow::from(vec![COUNTER.fetch_add(1, Ordering::Relaxed)]); diff --git a/substrate/frame/democracy/src/lib.rs b/substrate/frame/democracy/src/lib.rs index 19cdc754659d34b08b3c149e5766ea7bb6c01219..27bc36a756e4b36f3d6f3afdc2eb351063f6df56 100644 --- a/substrate/frame/democracy/src/lib.rs +++ b/substrate/frame/democracy/src/lib.rs @@ -152,10 +152,12 @@ #![recursion_limit = "256"] #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + +use alloc::{vec, vec::Vec}; use codec::{Decode, Encode}; use frame_support::{ ensure, - error::BadOrigin, traits::{ defensive_prelude::*, schedule::{v3::Named as ScheduleNamed, DispatchTime}, @@ -166,10 +168,9 @@ use frame_support::{ }; use frame_system::pallet_prelude::{BlockNumberFor, OriginFor}; use sp_runtime::{ - traits::{Bounded as ArithBounded, One, Saturating, StaticLookup, Zero}, + traits::{BadOrigin, Bounded as ArithBounded, One, Saturating, StaticLookup, Zero}, ArithmeticError, DispatchError, DispatchResult, }; -use sp_std::prelude::*; mod conviction; mod types; @@ -439,7 +440,7 @@ pub mod pallet { #[derive(frame_support::DefaultNoBound)] pub struct GenesisConfig { #[serde(skip)] - _config: sp_std::marker::PhantomData, + _config: core::marker::PhantomData, } #[pallet::genesis_build] @@ -1434,7 +1435,7 @@ impl Pallet { delegations: Default::default(), prior: Default::default(), }; - sp_std::mem::swap(&mut old, voting); + core::mem::swap(&mut old, voting); match old { Voting::Delegating { balance, target, conviction, delegations, mut prior, .. @@ -1475,7 +1476,7 @@ impl Pallet { fn try_undelegate(who: T::AccountId) -> Result { let votes = VotingOf::::try_mutate(&who, |voting| -> Result { let mut old = Voting::default(); - sp_std::mem::swap(&mut old, voting); + core::mem::swap(&mut old, voting); match old { Voting::Delegating { balance, target, conviction, delegations, mut prior } => { // remove any delegation votes to our current target. diff --git a/substrate/frame/democracy/src/migrations/unlock_and_unreserve_all_funds.rs b/substrate/frame/democracy/src/migrations/unlock_and_unreserve_all_funds.rs index 1cb50a157b12bb5ea68fc870e870cda6536fd524..ca0e0f7a091aaacbf1dc3bce18915a67e8c1ad78 100644 --- a/substrate/frame/democracy/src/migrations/unlock_and_unreserve_all_funds.rs +++ b/substrate/frame/democracy/src/migrations/unlock_and_unreserve_all_funds.rs @@ -19,6 +19,7 @@ //! pallet. use crate::{PropIndex, Voting, DEMOCRACY_ID}; +use alloc::{collections::btree_map::BTreeMap, vec::Vec}; use core::iter::Sum; use frame_support::{ pallet_prelude::ValueQuery, @@ -29,7 +30,6 @@ use frame_support::{ }; use sp_core::Get; use sp_runtime::{traits::Zero, BoundedVec, Saturating}; -use sp_std::{collections::btree_map::BTreeMap, vec::Vec}; const LOG_TARGET: &str = "runtime::democracy::migrations::unlock_and_unreserve_all_funds"; @@ -87,7 +87,7 @@ type VotingOf = StorageMap< /// The pallet should be made inoperable before this migration is run. /// /// (See also [`RemovePallet`][frame_support::migrations::RemovePallet]) -pub struct UnlockAndUnreserveAllFunds(sp_std::marker::PhantomData); +pub struct UnlockAndUnreserveAllFunds(core::marker::PhantomData); impl UnlockAndUnreserveAllFunds { /// Calculates and returns the total amounts reserved by each account by this pallet, and all @@ -170,8 +170,8 @@ where /// the actual total reserved amount for any accounts. #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { + use alloc::collections::btree_set::BTreeSet; use codec::Encode; - use sp_std::collections::btree_set::BTreeSet; // Get staked and deposited balances as reported by this pallet. let (account_deposits, account_locks, _) = Self::get_account_deposits_and_locks(); diff --git a/substrate/frame/democracy/src/vote.rs b/substrate/frame/democracy/src/vote.rs index b3fe9aa28e1ac4948761de52c0bec456f28e4618..779f7ecd570f060f29d53ebd05471eb37b531ff1 100644 --- a/substrate/frame/democracy/src/vote.rs +++ b/substrate/frame/democracy/src/vote.rs @@ -25,7 +25,6 @@ use sp_runtime::{ traits::{Saturating, Zero}, BoundedVec, RuntimeDebug, }; -use sp_std::prelude::*; /// A number of lock periods, plus a vote, one way or the other. #[derive(Copy, Clone, Eq, PartialEq, Default, RuntimeDebug)] diff --git a/substrate/frame/election-provider-multi-phase/Cargo.toml b/substrate/frame/election-provider-multi-phase/Cargo.toml index 941d720f2c6ca869cb8fdae55a27f009ad56e95a..4d1f521d726e28a4092dcd324f07ccc38849e85a 100644 --- a/substrate/frame/election-provider-multi-phase/Cargo.toml +++ b/substrate/frame/election-provider-multi-phase/Cargo.toml @@ -27,7 +27,6 @@ frame-support = { workspace = true } frame-system = { workspace = true } sp-io = { workspace = true } -sp-std = { workspace = true } sp-core = { workspace = true } sp-runtime = { workspace = true } sp-npos-elections = { workspace = true } @@ -68,7 +67,6 @@ std = [ "sp-io/std", "sp-npos-elections/std", "sp-runtime/std", - "sp-std/std", "sp-tracing/std", "strum/std", ] diff --git a/substrate/frame/election-provider-multi-phase/src/helpers.rs b/substrate/frame/election-provider-multi-phase/src/helpers.rs index a3f27fc18f07730ebbe9907ddd897a17ccb876e2..8269b2cb73be210c24925090d7c3a950519b9698 100644 --- a/substrate/frame/election-provider-multi-phase/src/helpers.rs +++ b/substrate/frame/election-provider-multi-phase/src/helpers.rs @@ -21,7 +21,7 @@ use crate::{ unsigned::{MinerConfig, MinerVoterOf}, SolutionTargetIndexOf, SolutionVoterIndexOf, VoteWeight, }; -use sp_std::{collections::btree_map::BTreeMap, prelude::*}; +use alloc::{collections::btree_map::BTreeMap, vec::Vec}; #[macro_export] macro_rules! log { diff --git a/substrate/frame/election-provider-multi-phase/src/lib.rs b/substrate/frame/election-provider-multi-phase/src/lib.rs index 63b4c49cdfe47a882560d4cd076a4cb113b26b1d..9ce8b3890a62402b53c2b489b2cac8b39d90ec10 100644 --- a/substrate/frame/election-provider-multi-phase/src/lib.rs +++ b/substrate/frame/election-provider-multi-phase/src/lib.rs @@ -229,6 +229,9 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + +use alloc::{boxed::Box, vec::Vec}; use codec::{Decode, Encode}; use frame_election_provider_support::{ bounds::{CountBound, ElectionBounds, ElectionBoundsBuilder, SizeBound}, @@ -256,7 +259,6 @@ use sp_runtime::{ }, DispatchError, ModuleError, PerThing, Perbill, RuntimeDebug, SaturatedConversion, }; -use sp_std::prelude::*; #[cfg(feature = "try-runtime")] use sp_runtime::TryRuntimeError; @@ -837,7 +839,7 @@ pub mod pallet { } fn integrity_test() { - use sp_std::mem::size_of; + use core::mem::size_of; // The index type of both voters and targets need to be smaller than that of usize (very // unlikely to be the case, but anyhow).. assert!(size_of::>() <= size_of::()); @@ -1354,7 +1356,7 @@ pub mod pallet { /// This wrapper is created for handling the synchronization of [`Snapshot`], [`SnapshotMetadata`] /// and [`DesiredTargets`] storage items. -pub struct SnapshotWrapper(sp_std::marker::PhantomData); +pub struct SnapshotWrapper(core::marker::PhantomData); impl SnapshotWrapper { /// Kill all snapshot related storage items at the same time. diff --git a/substrate/frame/election-provider-multi-phase/src/migrations.rs b/substrate/frame/election-provider-multi-phase/src/migrations.rs index 156f1c02e27cd23e3e37014650fdff66115cd18f..73a2d878f150f82611d5b469b32a12d4c0210772 100644 --- a/substrate/frame/election-provider-multi-phase/src/migrations.rs +++ b/substrate/frame/election-provider-multi-phase/src/migrations.rs @@ -16,15 +16,15 @@ // limitations under the License. pub mod v1 { + use alloc::collections::btree_map::BTreeMap; use frame_support::{ storage::unhashed, traits::{Defensive, GetStorageVersion, OnRuntimeUpgrade}, BoundedVec, }; - use sp_std::collections::btree_map::BTreeMap; use crate::*; - pub struct MigrateToV1(sp_std::marker::PhantomData); + pub struct MigrateToV1(core::marker::PhantomData); impl OnRuntimeUpgrade for MigrateToV1 { fn on_runtime_upgrade() -> Weight { let current = Pallet::::in_code_storage_version(); diff --git a/substrate/frame/election-provider-multi-phase/src/signed.rs b/substrate/frame/election-provider-multi-phase/src/signed.rs index ae830ed0382d8adfaf664e68548dfce6beddf9d0..fe07e477e1d5db3b071abd5c054e97d2dcb5cb9e 100644 --- a/substrate/frame/election-provider-multi-phase/src/signed.rs +++ b/substrate/frame/election-provider-multi-phase/src/signed.rs @@ -24,7 +24,12 @@ use crate::{ ReadySolution, SignedSubmissionIndices, SignedSubmissionNextIndex, SignedSubmissionsMap, SolutionOf, SolutionOrSnapshotSize, Weight, WeightInfo, }; +use alloc::{ + collections::{btree_map::BTreeMap, btree_set::BTreeSet}, + vec::Vec, +}; use codec::{Decode, Encode, HasCompact}; +use core::cmp::Ordering; use frame_election_provider_support::NposSolution; use frame_support::traits::{ defensive_prelude::*, Currency, Get, OnUnbalanced, ReservableCurrency, @@ -37,11 +42,6 @@ use sp_runtime::{ traits::{Convert, Saturating, Zero}, FixedPointNumber, FixedPointOperand, FixedU128, Percent, RuntimeDebug, }; -use sp_std::{ - cmp::Ordering, - collections::{btree_map::BTreeMap, btree_set::BTreeSet}, - vec::Vec, -}; /// A raw, unchecked signed submission. /// diff --git a/substrate/frame/election-provider-multi-phase/src/unsigned.rs b/substrate/frame/election-provider-multi-phase/src/unsigned.rs index 8b25815eca13ec72491bdb1cb9135a69c540001f..728ab93023895b2f8f74a3447cf008e66a17c9e4 100644 --- a/substrate/frame/election-provider-multi-phase/src/unsigned.rs +++ b/substrate/frame/election-provider-multi-phase/src/unsigned.rs @@ -21,6 +21,7 @@ use crate::{ helpers, Call, Config, ElectionCompute, Error, FeasibilityError, Pallet, RawSolution, ReadySolution, RoundSnapshot, SolutionAccuracyOf, SolutionOf, SolutionOrSnapshotSize, Weight, }; +use alloc::{boxed::Box, vec::Vec}; use codec::Encode; use frame_election_provider_support::{NposSolution, NposSolver, PerThing128, VoteWeight}; use frame_support::{ @@ -39,7 +40,6 @@ use sp_runtime::{ offchain::storage::{MutateStorageError, StorageValueRef}, DispatchError, SaturatedConversion, }; -use sp_std::prelude::*; /// Storage key used to store the last block number at which offchain worker ran. pub(crate) const OFFCHAIN_LAST_BLOCK: &[u8] = b"parity/multi-phase-unsigned-election"; @@ -396,14 +396,14 @@ impl Pallet { /// Configurations for a miner that comes with this pallet. pub trait MinerConfig { /// The account id type. - type AccountId: Ord + Clone + codec::Codec + sp_std::fmt::Debug; + type AccountId: Ord + Clone + codec::Codec + core::fmt::Debug; /// The solution that the miner is mining. type Solution: codec::Codec + Default + PartialEq + Eq + Clone - + sp_std::fmt::Debug + + core::fmt::Debug + Ord + NposSolution + TypeInfo; @@ -428,7 +428,7 @@ pub trait MinerConfig { } /// A base miner, suitable to be used for both signed and unsigned submissions. -pub struct Miner(sp_std::marker::PhantomData); +pub struct Miner(core::marker::PhantomData); impl Miner { /// Same as [`Pallet::mine_solution`], but the input snapshot data must be given. pub fn mine_solution_with_snapshot( @@ -505,7 +505,7 @@ impl Miner { stake }) .unwrap_or_default(); - sp_std::cmp::Reverse(stake) + core::cmp::Reverse(stake) }, ); @@ -1016,6 +1016,7 @@ mod tests { Event, InvalidTransaction, Phase, QueuedSolution, TransactionSource, TransactionValidityError, }; + use alloc::vec; use codec::Decode; use frame_election_provider_support::IndexAssignment; use frame_support::{assert_noop, assert_ok, traits::OffchainWorker}; diff --git a/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs b/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs index bb1bdb31420565a104fb58b553b211411d7a3520..5c64f2a0bc20ff2226e0503fffe995a6ae8d97c0 100644 --- a/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs +++ b/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/mock.rs @@ -38,7 +38,6 @@ use sp_staking::{ offence::{OffenceDetails, OnOffenceHandler}, EraIndex, SessionIndex, }; -use sp_std::prelude::*; use std::collections::BTreeMap; use codec::Decode; diff --git a/substrate/frame/election-provider-support/Cargo.toml b/substrate/frame/election-provider-support/Cargo.toml index 012392ffc59d9644181902ac3f5afbb6d444868f..80fea6c5ca972090cc59bd556578f660f1072db1 100644 --- a/substrate/frame/election-provider-support/Cargo.toml +++ b/substrate/frame/election-provider-support/Cargo.toml @@ -23,7 +23,6 @@ frame-system = { workspace = true } sp-arithmetic = { workspace = true } sp-npos-elections = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } sp-core = { workspace = true } [dev-dependencies] @@ -44,7 +43,6 @@ std = [ "sp-io/std", "sp-npos-elections/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-support/runtime-benchmarks", diff --git a/substrate/frame/election-provider-support/benchmarking/Cargo.toml b/substrate/frame/election-provider-support/benchmarking/Cargo.toml index ecf41ff9663bb94fb9feffa1991d6a90438d3952..dcfcb9c35cda070ef1d3876e4236ced121691881 100644 --- a/substrate/frame/election-provider-support/benchmarking/Cargo.toml +++ b/substrate/frame/election-provider-support/benchmarking/Cargo.toml @@ -23,7 +23,6 @@ frame-election-provider-support = { workspace = true } frame-system = { workspace = true } sp-npos-elections = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [features] default = ["std"] @@ -34,7 +33,6 @@ std = [ "frame-system/std", "sp-npos-elections/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/election-provider-support/benchmarking/src/inner.rs b/substrate/frame/election-provider-support/benchmarking/src/inner.rs index 4722680cfcc1cb9131f55d6002b666b28fb3d2ae..8cca0d459eac303028045c17f52694aa9140f782 100644 --- a/substrate/frame/election-provider-support/benchmarking/src/inner.rs +++ b/substrate/frame/election-provider-support/benchmarking/src/inner.rs @@ -18,10 +18,10 @@ //! Election provider support pallet benchmarking. //! This is separated into its own crate to avoid bloating the size of the runtime. +use alloc::vec::Vec; use codec::Decode; use frame_benchmarking::v1::benchmarks; use frame_election_provider_support::{NposSolver, PhragMMS, SequentialPhragmen}; -use sp_std::vec::Vec; pub struct Pallet(frame_system::Pallet); pub trait Config: frame_system::Config {} diff --git a/substrate/frame/election-provider-support/benchmarking/src/lib.rs b/substrate/frame/election-provider-support/benchmarking/src/lib.rs index 78b226e52af6c2cec67706acb67dee280b818af3..d092483f9383927a845883c7614dc12894eb5bf6 100644 --- a/substrate/frame/election-provider-support/benchmarking/src/lib.rs +++ b/substrate/frame/election-provider-support/benchmarking/src/lib.rs @@ -19,6 +19,8 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + #[cfg(feature = "runtime-benchmarks")] pub mod inner; diff --git a/substrate/frame/election-provider-support/solution-type/src/codec.rs b/substrate/frame/election-provider-support/solution-type/src/codec.rs index 17a256c228e287a2ad810cf37fd948d0d9f0abc0..16d5f17469b7eb0936e94161d53a331fbaf71ac5 100644 --- a/substrate/frame/election-provider-support/solution-type/src/codec.rs +++ b/substrate/frame/election-provider-support/solution-type/src/codec.rs @@ -51,14 +51,14 @@ fn decode_impl( quote! { let #name = < - _fepsp::sp_std::prelude::Vec<(_fepsp::codec::Compact<#voter_type>, _fepsp::codec::Compact<#target_type>)> + _fepsp::Vec<(_fepsp::codec::Compact<#voter_type>, _fepsp::codec::Compact<#target_type>)> as _fepsp::codec::Decode >::decode(value)?; let #name = #name .into_iter() .map(|(v, t)| (v.0, t.0)) - .collect::<_fepsp::sp_std::prelude::Vec<_>>(); + .collect::<_fepsp::Vec<_>>(); } }; @@ -73,7 +73,7 @@ fn decode_impl( quote! { let #name = < - _fepsp::sp_std::prelude::Vec<( + _fepsp::Vec<( _fepsp::codec::Compact<#voter_type>, [(_fepsp::codec::Compact<#target_type>, _fepsp::codec::Compact<#weight_type>); #c-1], _fepsp::codec::Compact<#target_type>, @@ -87,7 +87,7 @@ fn decode_impl( [ #inner_impl ], t_last.0, )) - .collect::<_fepsp::sp_std::prelude::Vec<_>>(); + .collect::<_fepsp::Vec<_>>(); } }) .collect::(); @@ -126,7 +126,7 @@ fn encode_impl(ident: &syn::Ident, count: usize) -> TokenStream2 { _fepsp::codec::Compact(v.clone()), _fepsp::codec::Compact(t.clone()), )) - .collect::<_fepsp::sp_std::prelude::Vec<_>>(); + .collect::<_fepsp::Vec<_>>(); #name.encode_to(&mut r); } }; @@ -153,7 +153,7 @@ fn encode_impl(ident: &syn::Ident, count: usize) -> TokenStream2 { [ #inners_solution_array ], _fepsp::codec::Compact(t_last.clone()), )) - .collect::<_fepsp::sp_std::prelude::Vec<_>>(); + .collect::<_fepsp::Vec<_>>(); #name.encode_to(&mut r); } }) @@ -161,7 +161,7 @@ fn encode_impl(ident: &syn::Ident, count: usize) -> TokenStream2 { quote!( impl _fepsp::codec::Encode for #ident { - fn encode(&self) -> _fepsp::sp_std::prelude::Vec { + fn encode(&self) -> _fepsp::Vec { let mut r = vec![]; #encode_impl_single #encode_impl_rest @@ -182,7 +182,7 @@ fn scale_info_impl( let name = format!("{}", vote_field(1)); quote! { .field(|f| - f.ty::<_fepsp::sp_std::prelude::Vec< + f.ty::<_fepsp::Vec< (_fepsp::codec::Compact<#voter_type>, _fepsp::codec::Compact<#target_type>) >>() .name(#name) @@ -194,7 +194,7 @@ fn scale_info_impl( let name = format!("{}", vote_field(2)); quote! { .field(|f| - f.ty::<_fepsp::sp_std::prelude::Vec<( + f.ty::<_fepsp::Vec<( _fepsp::codec::Compact<#voter_type>, (_fepsp::codec::Compact<#target_type>, _fepsp::codec::Compact<#weight_type>), _fepsp::codec::Compact<#target_type> @@ -209,7 +209,7 @@ fn scale_info_impl( let name = format!("{}", vote_field(c)); quote! { .field(|f| - f.ty::<_fepsp::sp_std::prelude::Vec<( + f.ty::<_fepsp::Vec<( _fepsp::codec::Compact<#voter_type>, [ (_fepsp::codec::Compact<#target_type>, _fepsp::codec::Compact<#weight_type>); diff --git a/substrate/frame/election-provider-support/solution-type/src/single_page.rs b/substrate/frame/election-provider-support/solution-type/src/single_page.rs index 161631ee83fa6562c47b6f09ad5962ee111fde28..de59df162c8ada6a7930d90b661fb8e226a6dbac 100644 --- a/substrate/frame/election-provider-support/solution-type/src/single_page.rs +++ b/substrate/frame/election-provider-support/solution-type/src/single_page.rs @@ -40,7 +40,7 @@ pub(crate) fn generate(def: crate::SolutionDef) -> Result { let name = vote_field(1); // NOTE: we use the visibility of the struct for the fields as well.. could be made better. quote!( - #vis #name: _fepsp::sp_std::prelude::Vec<(#voter_type, #target_type)>, + #vis #name: _fepsp::Vec<(#voter_type, #target_type)>, ) }; @@ -49,7 +49,7 @@ pub(crate) fn generate(def: crate::SolutionDef) -> Result { let field_name = vote_field(c); let array_len = c - 1; quote!( - #vis #field_name: _fepsp::sp_std::prelude::Vec<( + #vis #field_name: _fepsp::Vec<( #voter_type, [(#target_type, #weight_type); #array_len], #target_type @@ -147,8 +147,8 @@ pub(crate) fn generate(def: crate::SolutionDef) -> Result { self, voter_at: impl Fn(Self::VoterIndex) -> Option, target_at: impl Fn(Self::TargetIndex) -> Option, - ) -> Result<_fepsp::sp_std::prelude::Vec<_feps::Assignment>, _feps::Error> { - let mut #assignment_name: _fepsp::sp_std::prelude::Vec<_feps::Assignment> = Default::default(); + ) -> Result<_fepsp::Vec<_feps::Assignment>, _feps::Error> { + let mut #assignment_name: _fepsp::Vec<_feps::Assignment> = Default::default(); #into_impl Ok(#assignment_name) } @@ -165,10 +165,10 @@ pub(crate) fn generate(def: crate::SolutionDef) -> Result { all_edges } - fn unique_targets(&self) -> _fepsp::sp_std::prelude::Vec { + fn unique_targets(&self) -> _fepsp::Vec { // NOTE: this implementation returns the targets sorted, but we don't use it yet per // se, nor is the API enforcing it. - use _fepsp::sp_std::collections::btree_set::BTreeSet; + use _fepsp::BTreeSet; let mut all_targets: BTreeSet = BTreeSet::new(); let mut maybe_insert_target = |t: Self::TargetIndex| { all_targets.insert(t); @@ -206,7 +206,7 @@ pub(crate) fn generate(def: crate::SolutionDef) -> Result { .saturating_add((s as usize).saturating_mul(max_element_size)) } } - impl<'a> _fepsp::sp_std::convert::TryFrom<&'a [__IndexAssignment]> for #ident { + impl<'a> core::convert::TryFrom<&'a [__IndexAssignment]> for #ident { type Error = _feps::Error; fn try_from(index_assignments: &'a [__IndexAssignment]) -> Result { let mut #struct_name = #ident::default(); @@ -361,7 +361,7 @@ pub(crate) fn into_impl( let target = target_at(*t_idx).or_invalid_index()?; Ok((target, *p)) }) - .collect::, _feps::Error>>()?; + .collect::, _feps::Error>>()?; if sum >= #per_thing::one() { return Err(_feps::Error::SolutionWeightOverflow); diff --git a/substrate/frame/election-provider-support/src/lib.rs b/substrate/frame/election-provider-support/src/lib.rs index 2e9ee3b8a48b581b5a5880bd24e9abd3ebd636ea..394f58a38442519dd27286bd74f3459e63b6a857 100644 --- a/substrate/frame/election-provider-support/src/lib.rs +++ b/substrate/frame/election-provider-support/src/lib.rs @@ -177,11 +177,14 @@ pub mod bounds; pub mod onchain; pub mod traits; +extern crate alloc; + +use alloc::{boxed::Box, vec::Vec}; +use core::fmt::Debug; use sp_runtime::{ traits::{Bounded, Saturating, Zero}, RuntimeDebug, }; -use sp_std::{fmt::Debug, prelude::*}; pub use bounds::DataProviderBounds; pub use codec::{Decode, Encode}; @@ -202,10 +205,10 @@ use sp_runtime::TryRuntimeError; // re-export for the solution macro, with the dependencies of the macro. #[doc(hidden)] pub mod private { + pub use alloc::{collections::btree_set::BTreeSet, vec::Vec}; pub use codec; pub use scale_info; pub use sp_arithmetic; - pub use sp_std; // Simple Extension trait to easily convert `None` from index closures to `Err`. // @@ -276,7 +279,7 @@ pub type IndexAssignmentOf = IndexAssignment< /// Types that are used by the data provider trait. pub mod data_provider { /// Alias for the result type of the election data provider. - pub type Result = sp_std::result::Result; + pub type Result = core::result::Result; } /// Something that can provide the data to an [`ElectionProvider`]. @@ -431,7 +434,7 @@ pub trait InstantElectionProvider: ElectionProviderBase { } /// An election provider that does nothing whatsoever. -pub struct NoElection(sp_std::marker::PhantomData); +pub struct NoElection(core::marker::PhantomData); impl ElectionProviderBase for NoElection<(AccountId, BlockNumber, DataProvider, MaxWinners)> @@ -486,7 +489,7 @@ where /// used on the implementing side of [`ElectionDataProvider`]. pub trait SortedListProvider { /// The list's error type. - type Error: sp_std::fmt::Debug; + type Error: core::fmt::Debug; /// The type used by the list to compare nodes for ordering. type Score: Bounded + Saturating + Zero; @@ -597,7 +600,7 @@ pub trait NposSolver { /// The accuracy of this solver. This will affect the accuracy of the output. type Accuracy: PerThing128; /// The error type of this implementation. - type Error: sp_std::fmt::Debug + sp_std::cmp::PartialEq; + type Error: core::fmt::Debug + core::cmp::PartialEq; /// Solve an NPoS solution with the given `voters`, `targets`, and select `to_elect` count /// of `targets`. @@ -617,7 +620,7 @@ pub trait NposSolver { /// A wrapper for [`sp_npos_elections::seq_phragmen`] that implements [`NposSolver`]. See the /// documentation of [`sp_npos_elections::seq_phragmen`] for more info. pub struct SequentialPhragmen( - sp_std::marker::PhantomData<(AccountId, Accuracy, Balancing)>, + core::marker::PhantomData<(AccountId, Accuracy, Balancing)>, ); impl>> @@ -642,7 +645,7 @@ impl( - sp_std::marker::PhantomData<(AccountId, Accuracy, Balancing)>, + core::marker::PhantomData<(AccountId, Accuracy, Balancing)>, ); impl>> diff --git a/substrate/frame/election-provider-support/src/onchain.rs b/substrate/frame/election-provider-support/src/onchain.rs index ee4f6992a085e677aeb8dc2cafbc5637c135ebfd..1063d5d35aee72b12dfdcec670f32ebae493dacb 100644 --- a/substrate/frame/election-provider-support/src/onchain.rs +++ b/substrate/frame/election-provider-support/src/onchain.rs @@ -24,11 +24,12 @@ use crate::{ BoundedSupportsOf, Debug, ElectionDataProvider, ElectionProvider, ElectionProviderBase, InstantElectionProvider, NposSolver, WeightInfo, }; +use alloc::collections::btree_map::BTreeMap; +use core::marker::PhantomData; use frame_support::{dispatch::DispatchClass, traits::Get}; use sp_npos_elections::{ assignment_ratio_to_staked_normalized, to_supports, BoundedSupports, ElectionResult, VoteWeight, }; -use sp_std::{collections::btree_map::BTreeMap, marker::PhantomData, prelude::*}; /// Errors of the on-chain election. #[derive(Eq, PartialEq, Debug)] diff --git a/substrate/frame/election-provider-support/src/traits.rs b/substrate/frame/election-provider-support/src/traits.rs index 43d183b338e297f675453c5ba361a3e0d409ab3d..84fd57992d343ca5a83f686e5021067b53171dbc 100644 --- a/substrate/frame/election-provider-support/src/traits.rs +++ b/substrate/frame/election-provider-support/src/traits.rs @@ -18,11 +18,12 @@ //! Traits for the election operations. use crate::{Assignment, IdentifierT, IndexAssignmentOf, PerThing128, VoteWeight}; +use alloc::vec::Vec; use codec::Encode; +use core::fmt::Debug; use scale_info::TypeInfo; use sp_arithmetic::traits::{Bounded, UniqueSaturatedInto}; use sp_npos_elections::{ElectionScore, Error, EvaluateSupport}; -use sp_std::{fmt::Debug, prelude::*}; /// An opaque index-based, NPoS solution type. pub trait NposSolution diff --git a/substrate/frame/elections-phragmen/Cargo.toml b/substrate/frame/elections-phragmen/Cargo.toml index b53118b6b6fd2d070427615968fbfa43ad0bf920..6d1ecbd07350e7cdc9c92f74e71c771087d30803 100644 --- a/substrate/frame/elections-phragmen/Cargo.toml +++ b/substrate/frame/elections-phragmen/Cargo.toml @@ -28,7 +28,6 @@ sp-core = { workspace = true } sp-io = { workspace = true } sp-npos-elections = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } sp-staking = { workspace = true } [dev-dependencies] @@ -52,7 +51,6 @@ std = [ "sp-npos-elections/std", "sp-runtime/std", "sp-staking/std", - "sp-std/std", "sp-tracing/std", ] runtime-benchmarks = [ diff --git a/substrate/frame/elections-phragmen/src/lib.rs b/substrate/frame/elections-phragmen/src/lib.rs index c6eca40c47182321d5846d38f07408767fddd6f0..565ead4059d5fedda41240451e01d2bd17f48ad2 100644 --- a/substrate/frame/elections-phragmen/src/lib.rs +++ b/substrate/frame/elections-phragmen/src/lib.rs @@ -98,7 +98,11 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + +use alloc::{vec, vec::Vec}; use codec::{Decode, Encode}; +use core::cmp::Ordering; use frame_support::{ traits::{ defensive_prelude::*, ChangeMembers, Contains, ContainsLengthBound, Currency, Get, @@ -115,7 +119,6 @@ use sp_runtime::{ DispatchError, Perbill, RuntimeDebug, }; use sp_staking::currency_to_vote::CurrencyToVote; -use sp_std::{cmp::Ordering, prelude::*}; #[cfg(any(feature = "try-runtime", test))] use sp_runtime::TryRuntimeError; diff --git a/substrate/frame/elections-phragmen/src/migrations/unlock_and_unreserve_all_funds.rs b/substrate/frame/elections-phragmen/src/migrations/unlock_and_unreserve_all_funds.rs index 482766ee97f543081d520148ed6cdc37c7641945..ed4569aa25ee6813e0dd8ed98038436e2aad80cd 100644 --- a/substrate/frame/elections-phragmen/src/migrations/unlock_and_unreserve_all_funds.rs +++ b/substrate/frame/elections-phragmen/src/migrations/unlock_and_unreserve_all_funds.rs @@ -18,6 +18,7 @@ //! A migration that unreserves all deposit and unlocks all stake held in the context of this //! pallet. +use alloc::{collections::btree_map::BTreeMap, vec::Vec}; use core::iter::Sum; use frame_support::{ pallet_prelude::ValueQuery, @@ -28,7 +29,6 @@ use frame_support::{ }; use sp_core::Get; use sp_runtime::traits::Zero; -use sp_std::{collections::btree_map::BTreeMap, vec::Vec}; const LOG_TARGET: &str = "elections_phragmen::migrations::unlock_and_unreserve_all_funds"; @@ -93,7 +93,7 @@ type Voting = StorageMap< /// The pallet should be made inoperable before this migration is run. /// /// (See also [`RemovePallet`][frame_support::migrations::RemovePallet]) -pub struct UnlockAndUnreserveAllFunds(sp_std::marker::PhantomData); +pub struct UnlockAndUnreserveAllFunds(core::marker::PhantomData); impl UnlockAndUnreserveAllFunds { /// Calculates and returns the total amounts deposited and staked by each account in the context @@ -187,8 +187,8 @@ where /// reported as staked by the pallet and the amount actually locked in `Balances`. #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { + use alloc::collections::btree_set::BTreeSet; use codec::Encode; - use sp_std::collections::btree_set::BTreeSet; // Get staked and deposited balances as reported by this pallet. let (account_deposited_sums, account_staked_sums, _) = diff --git a/substrate/frame/elections-phragmen/src/migrations/v3.rs b/substrate/frame/elections-phragmen/src/migrations/v3.rs index b0092d6c07bb647f077fa336201e48f575ae9b9b..82f82f23e712f3304ae762c23fbb0eca96df3170 100644 --- a/substrate/frame/elections-phragmen/src/migrations/v3.rs +++ b/substrate/frame/elections-phragmen/src/migrations/v3.rs @@ -19,12 +19,12 @@ use super::super::LOG_TARGET; use crate::{Config, Pallet}; +use alloc::vec::Vec; use codec::{Decode, Encode, FullCodec}; use frame_support::{ pallet_prelude::ValueQuery, traits::StorageVersion, weights::Weight, Twox64Concat, }; use sp_runtime::RuntimeDebug; -use sp_std::prelude::*; #[derive(Encode, Decode, Clone, Default, RuntimeDebug, PartialEq)] struct SeatHolder { diff --git a/substrate/frame/elections-phragmen/src/migrations/v5.rs b/substrate/frame/elections-phragmen/src/migrations/v5.rs index 6e360aa8b8c15a21ccbb357d701da074c221fde9..150a4c4fa6c2c0830471281ada5c23fc611a8bd4 100644 --- a/substrate/frame/elections-phragmen/src/migrations/v5.rs +++ b/substrate/frame/elections-phragmen/src/migrations/v5.rs @@ -16,6 +16,7 @@ // limitations under the License. use super::super::*; +use alloc::{boxed::Box, vec::Vec}; /// Migrate the locks and vote stake on accounts (as specified with param `to_migrate`) that have /// more than their free balance locked. diff --git a/substrate/frame/examples/basic/Cargo.toml b/substrate/frame/examples/basic/Cargo.toml index b34d9efc15b7fef9285eb7ecf741f677d47e472a..af547c7eeb21eba379e126ea9cbfc6b74a336061 100644 --- a/substrate/frame/examples/basic/Cargo.toml +++ b/substrate/frame/examples/basic/Cargo.toml @@ -26,7 +26,6 @@ frame-system = { workspace = true } pallet-balances = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] sp-core = { workspace = true } @@ -44,7 +43,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/examples/basic/src/lib.rs b/substrate/frame/examples/basic/src/lib.rs index 12cadc969fd74288fc2ca99ac014fa98a603d56d..fea04cb447a0790ef99768dd034b59af9cb73105 100644 --- a/substrate/frame/examples/basic/src/lib.rs +++ b/substrate/frame/examples/basic/src/lib.rs @@ -53,6 +53,9 @@ // Ensure we're `no_std` when compiling for Wasm. #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + +use alloc::vec::Vec; use codec::{Decode, Encode}; use core::marker::PhantomData; use frame_support::{ @@ -69,7 +72,6 @@ use sp_runtime::{ InvalidTransaction, TransactionValidity, TransactionValidityError, ValidTransaction, }, }; -use sp_std::vec::Vec; // Re-export pallet items so that they can be accessed from the crate namespace. pub use pallet::*; diff --git a/substrate/frame/examples/basic/src/tests.rs b/substrate/frame/examples/basic/src/tests.rs index 505cd6f906de23bb5045834125201cc51c613217..d7095eb3c944ffb4532c7ec0efeaca3e6d95a4b3 100644 --- a/substrate/frame/examples/basic/src/tests.rs +++ b/substrate/frame/examples/basic/src/tests.rs @@ -92,7 +92,7 @@ pub fn new_test_ext() -> sp_io::TestExternalities { example: pallet_example_basic::GenesisConfig { dummy: 42, // we configure the map with (key, value) pairs. - bar: vec![(1, 2), (2, 3)], + bar: alloc::vec![(1, 2), (2, 3)], foo: 24, }, } diff --git a/substrate/frame/examples/default-config/Cargo.toml b/substrate/frame/examples/default-config/Cargo.toml index 8a0d14edbdbf386c64a675ad33885de632d753a3..81509c782a3fa092ca0cbf25c76a17b5d640ff7f 100644 --- a/substrate/frame/examples/default-config/Cargo.toml +++ b/substrate/frame/examples/default-config/Cargo.toml @@ -25,7 +25,6 @@ frame-system = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [features] default = ["std"] @@ -37,7 +36,6 @@ std = [ "scale-info/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] try-runtime = [ "frame-support/try-runtime", diff --git a/substrate/frame/examples/default-config/src/lib.rs b/substrate/frame/examples/default-config/src/lib.rs index 5b66c78e06283a2d9155dd76a653a7ca4649bbbf..ccdcd4968598d243ca4d236736402170db5e90bd 100644 --- a/substrate/frame/examples/default-config/src/lib.rs +++ b/substrate/frame/examples/default-config/src/lib.rs @@ -32,6 +32,8 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + #[frame_support::pallet] pub mod pallet { use frame_support::pallet_prelude::*; @@ -189,7 +191,7 @@ pub mod tests { } parameter_types! { - pub const SomeCall: RuntimeCall = RuntimeCall::System(frame_system::Call::::remark { remark: vec![] }); + pub const SomeCall: RuntimeCall = RuntimeCall::System(frame_system::Call::::remark { remark: alloc::vec![] }); } #[derive_impl(TestDefaultConfig as pallet::DefaultConfig)] diff --git a/substrate/frame/examples/dev-mode/Cargo.toml b/substrate/frame/examples/dev-mode/Cargo.toml index 1dd033d7e071e29027109f624cbc613f542e9575..c3dd7f26f21d484298792c8cc5984ea966ae0273 100644 --- a/substrate/frame/examples/dev-mode/Cargo.toml +++ b/substrate/frame/examples/dev-mode/Cargo.toml @@ -24,7 +24,6 @@ frame-system = { workspace = true } pallet-balances = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] sp-core = { workspace = true } @@ -41,7 +40,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] try-runtime = [ "frame-support/try-runtime", diff --git a/substrate/frame/examples/dev-mode/src/lib.rs b/substrate/frame/examples/dev-mode/src/lib.rs index 15f1a4b5d6199c29158e1600ad825e15d04479bf..eb94c024280c7fa96e790e1719b84df263331e16 100644 --- a/substrate/frame/examples/dev-mode/src/lib.rs +++ b/substrate/frame/examples/dev-mode/src/lib.rs @@ -28,9 +28,11 @@ // Ensure we're `no_std` when compiling for Wasm. #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + +use alloc::{vec, vec::Vec}; use frame_support::dispatch::DispatchResult; use frame_system::ensure_signed; -use sp_std::{vec, vec::Vec}; // Re-export pallet items so that they can be accessed from the crate namespace. pub use pallet::*; diff --git a/substrate/frame/examples/kitchensink/Cargo.toml b/substrate/frame/examples/kitchensink/Cargo.toml index b3869dff94142de172340ce7f02b701389d1b5a5..f1f9fdb492d9cb6bd56a7be72a28af6160c575af 100644 --- a/substrate/frame/examples/kitchensink/Cargo.toml +++ b/substrate/frame/examples/kitchensink/Cargo.toml @@ -25,7 +25,6 @@ frame-system = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } frame-benchmarking = { optional = true, workspace = true } @@ -47,7 +46,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/examples/kitchensink/src/lib.rs b/substrate/frame/examples/kitchensink/src/lib.rs index b7425b0c0846afc3e9488a490144a89e7b647301..442318565426ef4dde7cf8145c42bcecc0f11ee6 100644 --- a/substrate/frame/examples/kitchensink/src/lib.rs +++ b/substrate/frame/examples/kitchensink/src/lib.rs @@ -42,6 +42,8 @@ use sp_runtime::TryRuntimeError; pub mod weights; pub use weights::*; +extern crate alloc; + #[frame_support::pallet] pub mod pallet { use super::*; diff --git a/substrate/frame/examples/offchain-worker/Cargo.toml b/substrate/frame/examples/offchain-worker/Cargo.toml index f8ccd1f04e47534857894a6a5a1c497d48eb446b..179a658de312d1540ff3ed1e477967768c94474d 100644 --- a/substrate/frame/examples/offchain-worker/Cargo.toml +++ b/substrate/frame/examples/offchain-worker/Cargo.toml @@ -27,7 +27,6 @@ sp-core = { workspace = true } sp-io = { workspace = true } sp-keystore = { optional = true, workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [features] default = ["std"] @@ -42,7 +41,6 @@ std = [ "sp-io/std", "sp-keystore/std", "sp-runtime/std", - "sp-std/std", ] try-runtime = [ "frame-support/try-runtime", diff --git a/substrate/frame/examples/offchain-worker/src/lib.rs b/substrate/frame/examples/offchain-worker/src/lib.rs index 0a90e896188ebe111baafd46b265d7e8d8790d9e..add014f6b34a96971eca3ed4f0570bea9a797565 100644 --- a/substrate/frame/examples/offchain-worker/src/lib.rs +++ b/substrate/frame/examples/offchain-worker/src/lib.rs @@ -45,6 +45,9 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + +use alloc::vec::Vec; use codec::{Decode, Encode}; use frame_support::traits::Get; use frame_system::{ @@ -67,7 +70,6 @@ use sp_runtime::{ transaction_validity::{InvalidTransaction, TransactionValidity, ValidTransaction}, RuntimeDebug, }; -use sp_std::vec::Vec; #[cfg(test)] mod tests; @@ -606,7 +608,7 @@ impl Pallet { let body = response.body().collect::>(); // Create a str slice from the body. - let body_str = sp_std::str::from_utf8(&body).map_err(|_| { + let body_str = alloc::str::from_utf8(&body).map_err(|_| { log::warn!("No UTF8 body"); http::Error::Unknown })?; diff --git a/substrate/frame/examples/offchain-worker/src/tests.rs b/substrate/frame/examples/offchain-worker/src/tests.rs index e2c57a8c1e1abcb855a97db9590edc19c7bf881b..b665cbbb62aed3c38326881904ec685070e4b67f 100644 --- a/substrate/frame/examples/offchain-worker/src/tests.rs +++ b/substrate/frame/examples/offchain-worker/src/tests.rs @@ -375,7 +375,7 @@ fn price_oracle_response(state: &mut testing::OffchainState) { #[test] fn parse_price_works() { - let test_data = vec![ + let test_data = alloc::vec![ ("{\"USD\":6536.92}", Some(653692)), ("{\"USD\":65.92}", Some(6592)), ("{\"USD\":6536.924565}", Some(653692)), diff --git a/substrate/frame/examples/single-block-migrations/Cargo.toml b/substrate/frame/examples/single-block-migrations/Cargo.toml index a6cf020ce535d96cb81b9f93955bbbf795a62e34..2d524f2caa269fe00db41bd2db02ebee03c4fa3e 100644 --- a/substrate/frame/examples/single-block-migrations/Cargo.toml +++ b/substrate/frame/examples/single-block-migrations/Cargo.toml @@ -22,7 +22,6 @@ frame-executive = { workspace = true } frame-system = { workspace = true } frame-try-runtime = { optional = true, workspace = true } pallet-balances = { workspace = true } -sp-std = { workspace = true } sp-runtime = { workspace = true } sp-core = { workspace = true } sp-io = { workspace = true } @@ -42,7 +41,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", "sp-version/std", ] runtime-benchmarks = [ diff --git a/substrate/frame/examples/single-block-migrations/src/lib.rs b/substrate/frame/examples/single-block-migrations/src/lib.rs index 411537aa8c65f0c1462336cd6705a2a900bc230a..07c7199b932238b19ede0055503db8ec26965731 100644 --- a/substrate/frame/examples/single-block-migrations/src/lib.rs +++ b/substrate/frame/examples/single-block-migrations/src/lib.rs @@ -156,6 +156,9 @@ pub use pallet::*; pub mod migrations; #[doc(hidden)] mod mock; + +extern crate alloc; + use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::traits::StorageVersion; use sp_runtime::RuntimeDebug; diff --git a/substrate/frame/examples/single-block-migrations/src/migrations/v1.rs b/substrate/frame/examples/single-block-migrations/src/migrations/v1.rs index 7b543d72c98404d84ba8f68b3d864176c4182fb9..55cf7cef9a7a85a2a2174e5f9b2cb48c38db2549 100644 --- a/substrate/frame/examples/single-block-migrations/src/migrations/v1.rs +++ b/substrate/frame/examples/single-block-migrations/src/migrations/v1.rs @@ -21,7 +21,7 @@ use frame_support::{ }; #[cfg(feature = "try-runtime")] -use sp_std::vec::Vec; +use alloc::vec::Vec; /// Collection of storage item formats from the previous storage version. /// @@ -41,7 +41,7 @@ mod v0 { /// /// In this migration, update the on-chain storage for the pallet to reflect the new storage /// layout. -pub struct InnerMigrateV0ToV1(sp_std::marker::PhantomData); +pub struct InnerMigrateV0ToV1(core::marker::PhantomData); impl UncheckedOnRuntimeUpgrade for InnerMigrateV0ToV1 { /// Return the existing [`crate::Value`] so we can check that it was correctly set in diff --git a/substrate/frame/examples/split/Cargo.toml b/substrate/frame/examples/split/Cargo.toml index d8a8c6869ab5f78b16a793e544face8866d24b8d..9542902bae64b09347de2b1b13a248d573bccaac 100644 --- a/substrate/frame/examples/split/Cargo.toml +++ b/substrate/frame/examples/split/Cargo.toml @@ -25,7 +25,6 @@ frame-support = { workspace = true } frame-system = { workspace = true } sp-io = { workspace = true } -sp-std = { workspace = true } frame-benchmarking = { optional = true, workspace = true } @@ -43,7 +42,6 @@ std = [ "scale-info/std", "sp-core/std", "sp-io/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/examples/tasks/Cargo.toml b/substrate/frame/examples/tasks/Cargo.toml index 1ca62fd89943ec729af9a2c059b1b434fe274ce8..00695ceddf1977aaccfeec31db93c248c8391677 100644 --- a/substrate/frame/examples/tasks/Cargo.toml +++ b/substrate/frame/examples/tasks/Cargo.toml @@ -24,7 +24,6 @@ frame-system = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } sp-core = { workspace = true } frame-benchmarking = { optional = true, workspace = true } @@ -41,7 +40,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/executive/Cargo.toml b/substrate/frame/executive/Cargo.toml index 0f9741eec180d172c24434d587d723735551148c..78d9ea6fa4992d43f1ea72fbe1d39b85ec1dc48d 100644 --- a/substrate/frame/executive/Cargo.toml +++ b/substrate/frame/executive/Cargo.toml @@ -28,7 +28,6 @@ frame-try-runtime = { optional = true, workspace = true } sp-core = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } sp-tracing = { workspace = true } [dev-dependencies] @@ -57,7 +56,6 @@ std = [ "sp-inherents/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", "sp-tracing/std", "sp-version/std", ] diff --git a/substrate/frame/executive/src/lib.rs b/substrate/frame/executive/src/lib.rs index 3028eaf318e0881c1b6f4d4ea6ac17adfe99a75f..1e7bac64e18fd68ddec72fe38eff5b67e2ca7c2e 100644 --- a/substrate/frame/executive/src/lib.rs +++ b/substrate/frame/executive/src/lib.rs @@ -151,7 +151,10 @@ pub mod block_flowchart {} #[cfg(test)] mod tests; +extern crate alloc; + use codec::{Codec, Encode}; +use core::marker::PhantomData; use frame_support::{ defensive_assert, dispatch::{DispatchClass, DispatchInfo, GetDispatchInfo, PostDispatchInfo}, @@ -174,7 +177,6 @@ use sp_runtime::{ transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, ExtrinsicInclusionMode, }; -use sp_std::{marker::PhantomData, prelude::*}; #[cfg(feature = "try-runtime")] use ::{ @@ -467,7 +469,7 @@ where /// Logs the result of trying to decode the entire state. fn log_decode_result( - res: Result>, + res: Result>, ) -> Result<(), TryRuntimeError> { match res { Ok(bytes) => { diff --git a/substrate/frame/fast-unstake/Cargo.toml b/substrate/frame/fast-unstake/Cargo.toml index 59676ad39951951c6046bb6de303ee7ec9c0b21f..2b188bad1dfa7b40dbc575930dc4c7b7d5a8ca3b 100644 --- a/substrate/frame/fast-unstake/Cargo.toml +++ b/substrate/frame/fast-unstake/Cargo.toml @@ -24,7 +24,6 @@ frame-system = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } sp-staking = { workspace = true } frame-election-provider-support = { workspace = true } @@ -58,7 +57,6 @@ std = [ "sp-io/std", "sp-runtime/std", "sp-staking/std", - "sp-std/std", "sp-tracing/std", ] runtime-benchmarks = [ diff --git a/substrate/frame/fast-unstake/src/benchmarking.rs b/substrate/frame/fast-unstake/src/benchmarking.rs index 4828dcb9b42cb924c8b20363e2447b3c428ecf36..d01ff715ca4fccc8e8c32a35355f7ceeaadc79f6 100644 --- a/substrate/frame/fast-unstake/src/benchmarking.rs +++ b/substrate/frame/fast-unstake/src/benchmarking.rs @@ -20,6 +20,7 @@ #![cfg(feature = "runtime-benchmarks")] use crate::{types::*, Pallet as FastUnstake, *}; +use alloc::{vec, vec::Vec}; use frame_benchmarking::v1::{benchmarks, whitelist_account, BenchmarkError}; use frame_support::{ assert_ok, @@ -28,7 +29,6 @@ use frame_support::{ use frame_system::RawOrigin; use sp_runtime::traits::Zero; use sp_staking::{EraIndex, StakingInterface}; -use sp_std::prelude::*; const USER_SEED: u32 = 0; diff --git a/substrate/frame/fast-unstake/src/lib.rs b/substrate/frame/fast-unstake/src/lib.rs index f31c9c640260b2bccad684ce5aa23ef384847d43..41920907bd57b165dcfcd2668302b42310dfc52c 100644 --- a/substrate/frame/fast-unstake/src/lib.rs +++ b/substrate/frame/fast-unstake/src/lib.rs @@ -112,6 +112,8 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + pub use pallet::*; #[cfg(test)] @@ -150,6 +152,7 @@ macro_rules! log { pub mod pallet { use super::*; use crate::types::*; + use alloc::vec::Vec; use frame_support::{ pallet_prelude::*, traits::{Defensive, ReservableCurrency, StorageVersion}, @@ -157,7 +160,6 @@ pub mod pallet { use frame_system::pallet_prelude::*; use sp_runtime::{traits::Zero, DispatchResult}; use sp_staking::{EraIndex, StakingInterface}; - use sp_std::{prelude::*, vec::Vec}; pub use weights::WeightInfo; #[cfg(feature = "try-runtime")] diff --git a/substrate/frame/fast-unstake/src/migrations.rs b/substrate/frame/fast-unstake/src/migrations.rs index 97ad86bfff42bf6ee1e258f5663d9bb53144373c..1a873534ac819022496305541bb5cfff90100a0a 100644 --- a/substrate/frame/fast-unstake/src/migrations.rs +++ b/substrate/frame/fast-unstake/src/migrations.rs @@ -17,20 +17,20 @@ pub mod v1 { use crate::{types::BalanceOf, *}; + use alloc::vec::Vec; use frame_support::{ storage::unhashed, traits::{Defensive, Get, GetStorageVersion, OnRuntimeUpgrade}, weights::Weight, }; use sp_staking::EraIndex; - use sp_std::prelude::*; #[cfg(feature = "try-runtime")] use frame_support::ensure; #[cfg(feature = "try-runtime")] use sp_runtime::TryRuntimeError; - pub struct MigrateToV1(sp_std::marker::PhantomData); + pub struct MigrateToV1(core::marker::PhantomData); impl OnRuntimeUpgrade for MigrateToV1 { fn on_runtime_upgrade() -> Weight { let current = Pallet::::in_code_storage_version(); diff --git a/substrate/frame/fast-unstake/src/mock.rs b/substrate/frame/fast-unstake/src/mock.rs index 7ce7fee1410782a2166f7e696f2f0cad71746b40..757052e230a187ed9ce712a2b30bc5a5f2e9febb 100644 --- a/substrate/frame/fast-unstake/src/mock.rs +++ b/substrate/frame/fast-unstake/src/mock.rs @@ -26,7 +26,6 @@ use frame_support::{ use sp_runtime::{traits::IdentityLookup, BuildStorage}; use pallet_staking::{Exposure, IndividualExposure, StakerStatus}; -use sp_std::prelude::*; pub type AccountId = u128; pub type BlockNumber = u64; diff --git a/substrate/frame/fast-unstake/src/types.rs b/substrate/frame/fast-unstake/src/types.rs index 3fb5720861fa875c87c7b338028d66208e42e220..2a2319ef61296a5781b9ff752d45da1aa7c4cbf6 100644 --- a/substrate/frame/fast-unstake/src/types.rs +++ b/substrate/frame/fast-unstake/src/types.rs @@ -24,7 +24,6 @@ use frame_support::{ }; use scale_info::TypeInfo; use sp_staking::{EraIndex, StakingInterface}; -use sp_std::prelude::*; /// Maximum number of eras that we might check for a single staker. /// @@ -32,7 +31,7 @@ use sp_std::prelude::*; #[derive(scale_info::TypeInfo, codec::Encode, codec::Decode, codec::MaxEncodedLen)] #[codec(mel_bound(T: Config))] #[scale_info(skip_type_params(T))] -pub struct MaxChecking(sp_std::marker::PhantomData); +pub struct MaxChecking(core::marker::PhantomData); impl frame_support::traits::Get for MaxChecking { fn get() -> u32 { T::Staking::bonding_duration() + 1 diff --git a/substrate/frame/glutton/Cargo.toml b/substrate/frame/glutton/Cargo.toml index 58faecde62939f50d6b901ec9a5f3fa32ee8eda6..5a73e8caef8ea5cad7760cb55edb9a597bd81574 100644 --- a/substrate/frame/glutton/Cargo.toml +++ b/substrate/frame/glutton/Cargo.toml @@ -26,7 +26,6 @@ frame-system = { workspace = true } sp-core = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } sp-inherents = { workspace = true } [dev-dependencies] @@ -47,7 +46,6 @@ std = [ "sp-inherents/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] try-runtime = [ "frame-support/try-runtime", diff --git a/substrate/frame/glutton/src/lib.rs b/substrate/frame/glutton/src/lib.rs index 5427173b486bab7dfbc830d6af130bf8bccf7e6a..c8d2981ebfef136eca81d62aad479c7c07ae8819 100644 --- a/substrate/frame/glutton/src/lib.rs +++ b/substrate/frame/glutton/src/lib.rs @@ -35,12 +35,14 @@ mod mock; mod tests; pub mod weights; +extern crate alloc; + +use alloc::{vec, vec::Vec}; use blake2::{Blake2b512, Digest}; use frame_support::{pallet_prelude::*, weights::WeightMeter, DefaultNoBound}; use frame_system::pallet_prelude::*; use sp_io::hashing::twox_256; use sp_runtime::{traits::Zero, FixedPointNumber, FixedU64}; -use sp_std::{vec, vec::Vec}; pub use pallet::*; pub use weights::WeightInfo; @@ -162,7 +164,7 @@ pub mod pallet { pub block_length: FixedU64, #[serde(skip)] /// The required configuration field. - pub _config: sp_std::marker::PhantomData, + pub _config: core::marker::PhantomData, } #[pallet::genesis_build] diff --git a/substrate/frame/grandpa/Cargo.toml b/substrate/frame/grandpa/Cargo.toml index e08af3a5e91b31a00b6fd8d6f5a9f7764e7c8993..e24f9a51db8428e5e978febde2bcbb5bcc6e74ff 100644 --- a/substrate/frame/grandpa/Cargo.toml +++ b/substrate/frame/grandpa/Cargo.toml @@ -31,7 +31,6 @@ sp-io = { workspace = true } sp-runtime = { features = ["serde"], workspace = true } sp-session = { workspace = true } sp-staking = { features = ["serde"], workspace = true } -sp-std = { workspace = true } [dev-dependencies] finality-grandpa = { features = ["derive-codec"], workspace = true, default-features = true } @@ -67,7 +66,6 @@ std = [ "sp-runtime/std", "sp-session/std", "sp-staking/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/grandpa/src/equivocation.rs b/substrate/frame/grandpa/src/equivocation.rs index 16727f79a58d589182f5dbfbd01e9cf8674efabb..b213c1ceb7219f8ae4c860ba85c23ef1033dde93 100644 --- a/substrate/frame/grandpa/src/equivocation.rs +++ b/substrate/frame/grandpa/src/equivocation.rs @@ -35,6 +35,7 @@ //! that the `ValidateUnsigned` for the GRANDPA pallet is used in the runtime //! definition. +use alloc::{boxed::Box, vec, vec::Vec}; use codec::{self as codec, Decode, Encode}; use frame_support::traits::{Get, KeyOwnerProofSystem}; use frame_system::pallet_prelude::BlockNumberFor; @@ -52,7 +53,6 @@ use sp_staking::{ offence::{Kind, Offence, OffenceReportSystem, ReportOffence}, SessionIndex, }; -use sp_std::prelude::*; use super::{Call, Config, Error, Pallet, LOG_TARGET}; @@ -114,7 +114,7 @@ impl Offence for EquivocationOffence { /// - On-chain validity checks and processing are mostly delegated to the user provided generic /// types implementing `KeyOwnerProofSystem` and `ReportOffence` traits. /// - Offence reporter for unsigned transactions is fetched via the the authorship pallet. -pub struct EquivocationReportSystem(sp_std::marker::PhantomData<(T, R, P, L)>); +pub struct EquivocationReportSystem(core::marker::PhantomData<(T, R, P, L)>); impl OffenceReportSystem< diff --git a/substrate/frame/grandpa/src/lib.rs b/substrate/frame/grandpa/src/lib.rs index 90bcd8721dfa1f6d091edc34da883c2172d9f6ca..4f69aeaef523671969e961b24b4b87b59115bae3 100644 --- a/substrate/frame/grandpa/src/lib.rs +++ b/substrate/frame/grandpa/src/lib.rs @@ -28,11 +28,14 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + // Re-export since this is necessary for `impl_apis` in runtime. pub use sp_consensus_grandpa::{ self as fg_primitives, AuthorityId, AuthorityList, AuthorityWeight, }; +use alloc::{boxed::Box, vec::Vec}; use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{ dispatch::{DispatchResultWithPostInfo, Pays}, @@ -50,7 +53,6 @@ use sp_consensus_grandpa::{ use sp_runtime::{generic::DigestItem, traits::Zero, DispatchResult}; use sp_session::{GetSessionNumber, GetValidatorCount}; use sp_staking::{offence::OffenceReportSystem, SessionIndex}; -use sp_std::prelude::*; mod default_weights; mod equivocation; @@ -351,7 +353,7 @@ pub mod pallet { pub struct GenesisConfig { pub authorities: AuthorityList, #[serde(skip)] - pub _config: sp_std::marker::PhantomData, + pub _config: core::marker::PhantomData, } #[pallet::genesis_build] diff --git a/substrate/frame/grandpa/src/migrations/v5.rs b/substrate/frame/grandpa/src/migrations/v5.rs index a0865a3f2bf9a8b6be340065b8b4658c97d5050a..f1af0af42dd0a2ce9629a36416246eb70b453767 100644 --- a/substrate/frame/grandpa/src/migrations/v5.rs +++ b/substrate/frame/grandpa/src/migrations/v5.rs @@ -16,7 +16,9 @@ // limitations under the License. use crate::{BoundedAuthorityList, Pallet}; +use alloc::vec::Vec; use codec::Decode; +use core::marker::PhantomData; use frame_support::{ migrations::VersionedMigration, storage, @@ -24,7 +26,6 @@ use frame_support::{ weights::Weight, }; use sp_consensus_grandpa::AuthorityList; -use sp_std::{marker::PhantomData, vec::Vec}; const GRANDPA_AUTHORITIES_KEY: &[u8] = b":grandpa_authorities"; diff --git a/substrate/frame/identity/Cargo.toml b/substrate/frame/identity/Cargo.toml index d0b796cd75d351ba2e5df0d791d932babad11c08..6794fbfbbf42bfe070cd548c46514a6f7f1a3490 100644 --- a/substrate/frame/identity/Cargo.toml +++ b/substrate/frame/identity/Cargo.toml @@ -25,7 +25,6 @@ frame-support = { workspace = true } frame-system = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] pallet-balances = { workspace = true, default-features = true } @@ -48,7 +47,6 @@ std = [ "sp-io/std", "sp-keystore/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/identity/src/benchmarking.rs b/substrate/frame/identity/src/benchmarking.rs index 957549b19f859d39377ca6281e51fb35cf039d8e..ab04000c2281bdab28e646aab3f5df04c7251e57 100644 --- a/substrate/frame/identity/src/benchmarking.rs +++ b/substrate/frame/identity/src/benchmarking.rs @@ -22,6 +22,7 @@ use super::*; use crate::Pallet as Identity; +use alloc::{vec, vec::Vec}; use frame_benchmarking::{account, v2::*, whitelisted_caller, BenchmarkError}; use frame_support::{ assert_ok, ensure, diff --git a/substrate/frame/identity/src/legacy.rs b/substrate/frame/identity/src/legacy.rs index 60e812c2238b26ac79b737f90bca5e4770aee500..c2107e92903856b7d0d5493dbd08c59c31adfff6 100644 --- a/substrate/frame/identity/src/legacy.rs +++ b/substrate/frame/identity/src/legacy.rs @@ -15,6 +15,8 @@ // See the License for the specific language governing permissions and // limitations under the License. +#[cfg(feature = "runtime-benchmarks")] +use alloc::vec; use codec::{Decode, Encode, MaxEncodedLen}; #[cfg(feature = "runtime-benchmarks")] use enumflags2::BitFlag; @@ -22,7 +24,6 @@ use enumflags2::{bitflags, BitFlags}; use frame_support::{traits::Get, CloneNoBound, EqNoBound, PartialEqNoBound, RuntimeDebugNoBound}; use scale_info::{build::Variants, Path, Type, TypeInfo}; use sp_runtime::{BoundedVec, RuntimeDebug}; -use sp_std::prelude::*; use crate::types::{Data, IdentityInformationProvider}; diff --git a/substrate/frame/identity/src/lib.rs b/substrate/frame/identity/src/lib.rs index 50d6de32ac61e7c8ee9d8aeeeace0b3a42dac65b..776a08f5e9e8a3b2cc15423d4677ab4792d98ed2 100644 --- a/substrate/frame/identity/src/lib.rs +++ b/substrate/frame/identity/src/lib.rs @@ -101,7 +101,10 @@ mod tests; mod types; pub mod weights; +extern crate alloc; + use crate::types::{AuthorityPropertiesOf, Suffix, Username}; +use alloc::{boxed::Box, vec::Vec}; use codec::Encode; use frame_support::{ ensure, @@ -113,7 +116,6 @@ pub use pallet::*; use sp_runtime::traits::{ AppendZerosInput, Hash, IdentifyAccount, Saturating, StaticLookup, Verify, Zero, }; -use sp_std::prelude::*; pub use types::{ Data, IdentityInformationProvider, Judgement, RegistrarIndex, RegistrarInfo, Registration, }; diff --git a/substrate/frame/identity/src/types.rs b/substrate/frame/identity/src/types.rs index 10f0db8c25d8f0ba1c0a50789870ada6caa4d2c6..45401d53e9e9006839ab55a1999e9ebc5637fad4 100644 --- a/substrate/frame/identity/src/types.rs +++ b/substrate/frame/identity/src/types.rs @@ -16,7 +16,9 @@ // limitations under the License. use super::*; +use alloc::{vec, vec::Vec}; use codec::{Decode, Encode, MaxEncodedLen}; +use core::{fmt::Debug, iter::once, ops::Add}; use frame_support::{ traits::{ConstU32, Get}, BoundedVec, CloneNoBound, PartialEqNoBound, RuntimeDebugNoBound, @@ -29,7 +31,6 @@ use sp_runtime::{ traits::{Member, Zero}, RuntimeDebug, }; -use sp_std::{fmt::Debug, iter::once, ops::Add, prelude::*}; /// An identifier for a single name registrar/identity verification service. pub type RegistrarIndex = u32; @@ -65,7 +66,7 @@ impl Data { } impl Decode for Data { - fn decode(input: &mut I) -> sp_std::result::Result { + fn decode(input: &mut I) -> core::result::Result { let b = input.read_byte()?; Ok(match b { 0 => Data::None, @@ -295,7 +296,7 @@ impl< IdentityInfo: IdentityInformationProvider, > Decode for Registration { - fn decode(input: &mut I) -> sp_std::result::Result { + fn decode(input: &mut I) -> core::result::Result { let (judgements, deposit, info) = Decode::decode(&mut AppendZerosInput::new(input))?; Ok(Self { judgements, deposit, info }) } diff --git a/substrate/frame/im-online/Cargo.toml b/substrate/frame/im-online/Cargo.toml index 85cbcb3941b17b8675049196d8d60ad201e40916..2cb03b57d6ca82d93140302a634343f58a35082a 100644 --- a/substrate/frame/im-online/Cargo.toml +++ b/substrate/frame/im-online/Cargo.toml @@ -28,7 +28,6 @@ sp-core = { features = ["serde"], workspace = true } sp-io = { workspace = true } sp-runtime = { features = ["serde"], workspace = true } sp-staking = { features = ["serde"], workspace = true } -sp-std = { workspace = true } [dev-dependencies] pallet-session = { workspace = true, default-features = true } @@ -49,7 +48,6 @@ std = [ "sp-io/std", "sp-runtime/std", "sp-staking/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/im-online/src/lib.rs b/substrate/frame/im-online/src/lib.rs index f91a473e53d5389275974ed0e62c1d75d0daff54..ee2a8451d6fb7935f4ae06e34a9c9fde039722ca 100644 --- a/substrate/frame/im-online/src/lib.rs +++ b/substrate/frame/im-online/src/lib.rs @@ -82,6 +82,9 @@ mod mock; mod tests; pub mod weights; +extern crate alloc; + +use alloc::{vec, vec::Vec}; use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{ pallet_prelude::*, @@ -107,7 +110,6 @@ use sp_staking::{ offence::{Kind, Offence, ReportOffence}, SessionIndex, }; -use sp_std::prelude::*; pub use weights::WeightInfo; pub mod sr25519 { @@ -196,8 +198,8 @@ enum OffchainErr { SubmitTransaction, } -impl sp_std::fmt::Debug for OffchainErr { - fn fmt(&self, fmt: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { +impl core::fmt::Debug for OffchainErr { + fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result { match *self { OffchainErr::TooEarly => write!(fmt, "Too early to send heartbeat."), OffchainErr::WaitingForInclusion(ref block) => { diff --git a/substrate/frame/im-online/src/migration.rs b/substrate/frame/im-online/src/migration.rs index 754a2e672e6cfaec32ed0e44c9af54469fddbb04..6d3a5cda697359f190cc8ccaa5884518d760dbae 100644 --- a/substrate/frame/im-online/src/migration.rs +++ b/substrate/frame/im-online/src/migration.rs @@ -18,6 +18,7 @@ //! Storage migrations for the im-online pallet. use super::*; +use alloc::vec::Vec; use frame_support::{storage_alias, traits::OnRuntimeUpgrade}; #[cfg(feature = "try-runtime")] diff --git a/substrate/frame/indices/Cargo.toml b/substrate/frame/indices/Cargo.toml index 20c3863ff99b0743100c9d3354a9e5efb43ffc71..ea170481531264ab08fa744f2e294fc400383312 100644 --- a/substrate/frame/indices/Cargo.toml +++ b/substrate/frame/indices/Cargo.toml @@ -25,7 +25,6 @@ sp-core = { workspace = true } sp-io = { workspace = true } sp-keyring = { optional = true, workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] pallet-balances = { workspace = true, default-features = true } @@ -44,7 +43,6 @@ std = [ "sp-keyring", "sp-keyring?/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/indices/src/lib.rs b/substrate/frame/indices/src/lib.rs index ff12d092cfb8d67f7d44ca5648a120bbd8507cb3..740d69365df3e4a4539dd6fed3d18aadc0b7bddc 100644 --- a/substrate/frame/indices/src/lib.rs +++ b/substrate/frame/indices/src/lib.rs @@ -25,13 +25,15 @@ mod mock; mod tests; pub mod weights; +extern crate alloc; + +use alloc::vec::Vec; use codec::Codec; use frame_support::traits::{BalanceStatus::Reserved, Currency, ReservableCurrency}; use sp_runtime::{ traits::{AtLeast32Bit, LookupError, Saturating, StaticLookup, Zero}, MultiAddress, }; -use sp_std::prelude::*; pub use weights::WeightInfo; type BalanceOf = diff --git a/substrate/frame/insecure-randomness-collective-flip/Cargo.toml b/substrate/frame/insecure-randomness-collective-flip/Cargo.toml index 0da0d5373953b7703c095e86a9dbf2ec09fba2a6..977b9fdb6f60681b8a97207e2dbac0cbb9914cc2 100644 --- a/substrate/frame/insecure-randomness-collective-flip/Cargo.toml +++ b/substrate/frame/insecure-randomness-collective-flip/Cargo.toml @@ -22,7 +22,6 @@ scale-info = { features = ["derive"], workspace = true } frame-support = { workspace = true } frame-system = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] sp-core = { workspace = true, default-features = true } @@ -39,7 +38,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] try-runtime = [ "frame-support/try-runtime", diff --git a/substrate/frame/lottery/Cargo.toml b/substrate/frame/lottery/Cargo.toml index 34d1728e42ed0df444530cd4cdd6f039f2e12da4..0a33e54a825de6afb67d8320cbb4176abaf9569e 100644 --- a/substrate/frame/lottery/Cargo.toml +++ b/substrate/frame/lottery/Cargo.toml @@ -23,7 +23,6 @@ frame-benchmarking = { optional = true, workspace = true } frame-support = { workspace = true } frame-system = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] frame-support-test = { workspace = true } @@ -44,7 +43,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/lottery/src/benchmarking.rs b/substrate/frame/lottery/src/benchmarking.rs index 123b425b976f3b5b2842e748498513611dca5bc2..046bc0acbb6442d48bf84cbff7cc0cde10b65567 100644 --- a/substrate/frame/lottery/src/benchmarking.rs +++ b/substrate/frame/lottery/src/benchmarking.rs @@ -22,6 +22,7 @@ use super::*; use crate::Pallet as Lottery; +use alloc::{boxed::Box, vec}; use frame_benchmarking::{ v1::{account, whitelisted_caller, BenchmarkError}, v2::*, diff --git a/substrate/frame/lottery/src/lib.rs b/substrate/frame/lottery/src/lib.rs index 54a8edd38606d76bfa4780d05918d05a1d690ae9..0071b258fc45c0fc7539e0394d4c95104d2a94ce 100644 --- a/substrate/frame/lottery/src/lib.rs +++ b/substrate/frame/lottery/src/lib.rs @@ -54,6 +54,9 @@ mod mock; mod tests; pub mod weights; +extern crate alloc; + +use alloc::{boxed::Box, vec::Vec}; use codec::{Decode, Encode}; use frame_support::{ dispatch::{DispatchResult, GetDispatchInfo}, @@ -68,7 +71,6 @@ use sp_runtime::{ traits::{AccountIdConversion, Dispatchable, Saturating, Zero}, ArithmeticError, DispatchError, RuntimeDebug, }; -use sp_std::prelude::*; pub use weights::WeightInfo; type BalanceOf = diff --git a/substrate/frame/membership/Cargo.toml b/substrate/frame/membership/Cargo.toml index 35b0eeaa7141985c31ab857931e300da050aafcd..0fc5ce02809e1809b2a1b8b3df623c66e99989bd 100644 --- a/substrate/frame/membership/Cargo.toml +++ b/substrate/frame/membership/Cargo.toml @@ -25,7 +25,6 @@ frame-system = { workspace = true } sp-core = { features = ["serde"], workspace = true } sp-io = { workspace = true } sp-runtime = { features = ["serde"], workspace = true } -sp-std = { workspace = true } [features] default = ["std"] @@ -39,7 +38,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/membership/src/lib.rs b/substrate/frame/membership/src/lib.rs index d5dad68e811b008a94fc4b1b1f67ff0e454ba8d2..e38a6ba5d931b332fbd6ac62b0557dd45fba4b20 100644 --- a/substrate/frame/membership/src/lib.rs +++ b/substrate/frame/membership/src/lib.rs @@ -23,12 +23,14 @@ // Ensure we're `no_std` when compiling for Wasm. #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + +use alloc::vec::Vec; use frame_support::{ traits::{ChangeMembers, Contains, ContainsLengthBound, Get, InitializeMembers, SortedMembers}, BoundedVec, }; use sp_runtime::traits::{StaticLookup, UniqueSaturatedInto}; -use sp_std::prelude::*; pub mod migrations; pub mod weights; @@ -113,7 +115,7 @@ pub mod pallet { #[pallet::genesis_build] impl, I: 'static> BuildGenesisConfig for GenesisConfig { fn build(&self) { - use sp_std::collections::btree_set::BTreeSet; + use alloc::collections::btree_set::BTreeSet; let members_set: BTreeSet<_> = self.members.iter().collect(); assert_eq!( members_set.len(), diff --git a/substrate/frame/merkle-mountain-range/Cargo.toml b/substrate/frame/merkle-mountain-range/Cargo.toml index 27ba77e5a62a9c6d2c31639aac5824ab0e8383cc..b8a9b6065c6cdd6ae48ffb24ee6108ddbc4c8ebb 100644 --- a/substrate/frame/merkle-mountain-range/Cargo.toml +++ b/substrate/frame/merkle-mountain-range/Cargo.toml @@ -25,7 +25,6 @@ sp-core = { workspace = true } sp-io = { workspace = true } sp-mmr-primitives = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] array-bytes = { workspace = true, default-features = true } @@ -45,7 +44,6 @@ std = [ "sp-io/std", "sp-mmr-primitives/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/merkle-mountain-range/src/benchmarking.rs b/substrate/frame/merkle-mountain-range/src/benchmarking.rs index 9eb676a4ee44b21cef7ced59c40366067017f7ce..07afd9529eb2608941881cf01c7d9a8e341bae7c 100644 --- a/substrate/frame/merkle-mountain-range/src/benchmarking.rs +++ b/substrate/frame/merkle-mountain-range/src/benchmarking.rs @@ -28,10 +28,13 @@ benchmarks_instance_pallet! { let x in 1 .. 1_000; let leaves = x as NodeIndex; - }: { - for b in 0..leaves { - Pallet::::on_initialize((b as u32).into()); + + <>::BenchmarkHelper as BenchmarkHelper>::setup(); + for leaf in 0..(leaves - 1) { + Pallet::::on_initialize((leaf as u32).into()); } + }: { + Pallet::::on_initialize((leaves as u32 - 1).into()); } verify { assert_eq!(crate::NumberOfLeaves::::get(), leaves); } diff --git a/substrate/frame/merkle-mountain-range/src/default_weights.rs b/substrate/frame/merkle-mountain-range/src/default_weights.rs index 52e3f130383fdf8d9267b9b34300014741677b9f..b0ef0539018cdf8814223862a5508b81ad2863b1 100644 --- a/substrate/frame/merkle-mountain-range/src/default_weights.rs +++ b/substrate/frame/merkle-mountain-range/src/default_weights.rs @@ -24,7 +24,8 @@ use frame_support::weights::{ }; impl crate::WeightInfo for () { - fn on_initialize(peaks: u64) -> Weight { + fn on_initialize(peaks: u32) -> Weight { + let peaks = u64::from(peaks); // Reading the parent hash. let leaf_weight = DbWeight::get().reads(1); // Blake2 hash cost. diff --git a/substrate/frame/merkle-mountain-range/src/lib.rs b/substrate/frame/merkle-mountain-range/src/lib.rs index 47a325db605d833443afd6568647528a0d54fe21..0ab44711bcf5d854c3c158434740fdbaf1931b1b 100644 --- a/substrate/frame/merkle-mountain-range/src/lib.rs +++ b/substrate/frame/merkle-mountain-range/src/lib.rs @@ -56,6 +56,9 @@ //! NOTE This pallet is experimental and not proven to work in production. #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + +use alloc::vec::Vec; use frame_support::weights::Weight; use frame_system::pallet_prelude::{BlockNumberFor, HeaderFor}; use log; @@ -64,7 +67,6 @@ use sp_runtime::{ traits::{self, One, Saturating}, SaturatedConversion, }; -use sp_std::prelude::*; pub use pallet::*; pub use sp_mmr_primitives::{ @@ -89,7 +91,7 @@ mod tests; /// is not available (since the block is not finished yet), /// we use the `parent_hash` here along with parent block number. pub struct ParentNumberAndHash { - _phantom: sp_std::marker::PhantomData, + _phantom: core::marker::PhantomData, } impl LeafDataProvider for ParentNumberAndHash { @@ -110,7 +112,7 @@ pub trait BlockHashProvider { /// Default implementation of BlockHashProvider using frame_system. pub struct DefaultBlockHashProvider { - _phantom: sp_std::marker::PhantomData, + _phantom: core::marker::PhantomData, } impl BlockHashProvider, T::Hash> @@ -122,7 +124,18 @@ impl BlockHashProvider, T::Hash> } pub trait WeightInfo { - fn on_initialize(peaks: NodeIndex) -> Weight; + fn on_initialize(peaks: u32) -> Weight; +} + +/// This trait decoples dependencies on pallets needed for benchmarking. +#[cfg(feature = "runtime-benchmarks")] +pub trait BenchmarkHelper { + fn setup(); +} + +#[cfg(feature = "runtime-benchmarks")] +impl BenchmarkHelper for () { + fn setup() {} } /// An MMR specific to the pallet. @@ -203,6 +216,10 @@ pub mod pallet { /// Weights for this pallet. type WeightInfo: WeightInfo; + + /// Benchmarking setup helper trait. + #[cfg(feature = "runtime-benchmarks")] + type BenchmarkHelper: BenchmarkHelper; } /// Latest MMR Root hash. @@ -236,14 +253,14 @@ pub mod pallet { // MMR push never fails, but better safe than sorry. if mmr.push(data).is_none() { log::error!(target: "runtime::mmr", "MMR push failed"); - return T::WeightInfo::on_initialize(peaks_before) + return T::WeightInfo::on_initialize(peaks_before as u32) } // Update the size, `mmr.finalize()` should also never fail. let (leaves, root) = match mmr.finalize() { Ok((leaves, root)) => (leaves, root), Err(e) => { log::error!(target: "runtime::mmr", "MMR finalize failed: {:?}", e); - return T::WeightInfo::on_initialize(peaks_before) + return T::WeightInfo::on_initialize(peaks_before as u32) }, }; >::on_new_root(&root); @@ -253,7 +270,7 @@ pub mod pallet { let peaks_after = sp_mmr_primitives::utils::NodesUtils::new(leaves).number_of_peaks(); - T::WeightInfo::on_initialize(peaks_before.max(peaks_after)) + T::WeightInfo::on_initialize(peaks_before.max(peaks_after) as u32) } } } @@ -302,7 +319,7 @@ impl, I: 'static> Pallet { fn node_temp_offchain_key( pos: NodeIndex, parent_hash: ::Hash, - ) -> sp_std::prelude::Vec { + ) -> Vec { NodesUtils::node_temp_offchain_key::>(&T::INDEXING_PREFIX, pos, parent_hash) } @@ -311,7 +328,7 @@ impl, I: 'static> Pallet { /// Used for nodes added by now finalized blocks. /// Never read keys using `node_canon_offchain_key` unless you sure that /// there's no `node_offchain_key` key in the storage. - fn node_canon_offchain_key(pos: NodeIndex) -> sp_std::prelude::Vec { + fn node_canon_offchain_key(pos: NodeIndex) -> Vec { NodesUtils::node_canon_offchain_key(&T::INDEXING_PREFIX, pos) } diff --git a/substrate/frame/merkle-mountain-range/src/mmr/mmr.rs b/substrate/frame/merkle-mountain-range/src/mmr/mmr.rs index 8a99f4d87deb02df9c86f449317a2d8a7baa484e..2b46357c50723dfa8299a42fab1c9030ad0077fa 100644 --- a/substrate/frame/merkle-mountain-range/src/mmr/mmr.rs +++ b/substrate/frame/merkle-mountain-range/src/mmr/mmr.rs @@ -23,8 +23,8 @@ use crate::{ primitives::{self, Error, NodeIndex}, Config, HashOf, HashingOf, }; +use alloc::vec::Vec; use sp_mmr_primitives::{mmr_lib, mmr_lib::MMRStoreReadOps, utils::NodesUtils, LeafIndex}; -use sp_std::prelude::*; /// Stateless verification of the proof for a batch of leaves. /// Note, the leaves should be sorted such that corresponding leaves and leaf indices have the diff --git a/substrate/frame/merkle-mountain-range/src/mmr/storage.rs b/substrate/frame/merkle-mountain-range/src/mmr/storage.rs index e27440be35c45cdf4823f3cdb542f07197e302da..a390898014846077f4547a355909e074a2adcf5a 100644 --- a/substrate/frame/merkle-mountain-range/src/mmr/storage.rs +++ b/substrate/frame/merkle-mountain-range/src/mmr/storage.rs @@ -17,14 +17,13 @@ //! An MMR storage implementation. +use alloc::{vec, vec::Vec}; use codec::Encode; +use core::iter::Peekable; use log::{debug, trace}; use sp_core::offchain::StorageKind; use sp_io::offchain_index; use sp_mmr_primitives::{mmr_lib, mmr_lib::helper, utils::NodesUtils}; -use sp_std::iter::Peekable; -#[cfg(not(feature = "std"))] -use sp_std::prelude::*; use crate::{ mmr::{Node, NodeOf}, @@ -52,7 +51,7 @@ pub struct OffchainStorage; /// /// There are two different implementations depending on the use case. /// See docs for [RuntimeStorage] and [OffchainStorage]. -pub struct Storage(sp_std::marker::PhantomData<(StorageType, T, I, L)>); +pub struct Storage(core::marker::PhantomData<(StorageType, T, I, L)>); impl Default for Storage { fn default() -> Self { diff --git a/substrate/frame/merkle-mountain-range/src/mock.rs b/substrate/frame/merkle-mountain-range/src/mock.rs index 8318b20e83074cd3bcb540b854fd7abae998438e..606719c6deba121f693250694894d104bae030f7 100644 --- a/substrate/frame/merkle-mountain-range/src/mock.rs +++ b/substrate/frame/merkle-mountain-range/src/mock.rs @@ -46,6 +46,8 @@ impl Config for Test { type OnNewRoot = (); type BlockHashProvider = DefaultBlockHashProvider; type WeightInfo = (); + #[cfg(feature = "runtime-benchmarks")] + type BenchmarkHelper = (); } #[derive(Encode, Decode, Clone, Default, Eq, PartialEq, Debug)] diff --git a/substrate/frame/message-queue/Cargo.toml b/substrate/frame/message-queue/Cargo.toml index 5ced1a4e08ff9a4d6fe328f7db76eef23f7c69f1..0c3bbb2c883c53212163a4ce4910b769e7262bd9 100644 --- a/substrate/frame/message-queue/Cargo.toml +++ b/substrate/frame/message-queue/Cargo.toml @@ -21,7 +21,6 @@ environmental = { workspace = true } sp-core = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } sp-arithmetic = { workspace = true } sp-weights = { workspace = true } @@ -49,7 +48,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", "sp-tracing/std", "sp-weights/std", ] diff --git a/substrate/frame/message-queue/src/benchmarking.rs b/substrate/frame/message-queue/src/benchmarking.rs index 7e99bc058584504dfea69ebcd3463657e4379d83..8f0712acc5f51cae3dc1ad165eec54c3875b582e 100644 --- a/substrate/frame/message-queue/src/benchmarking.rs +++ b/substrate/frame/message-queue/src/benchmarking.rs @@ -26,7 +26,6 @@ use frame_benchmarking::v2::*; use frame_support::traits::Get; use frame_system::RawOrigin; use sp_io::hashing::blake2_256; -use sp_std::prelude::*; #[benchmarks( where diff --git a/substrate/frame/message-queue/src/lib.rs b/substrate/frame/message-queue/src/lib.rs index ef3420d21be520f8056b1c1299e8369754186560..2dbffef7e5a242b1636313a76bba9fadcf3f9d28 100644 --- a/substrate/frame/message-queue/src/lib.rs +++ b/substrate/frame/message-queue/src/lib.rs @@ -203,7 +203,11 @@ pub mod mock_helpers; mod tests; pub mod weights; +extern crate alloc; + +use alloc::{vec, vec::Vec}; use codec::{Codec, Decode, Encode, MaxEncodedLen}; +use core::{fmt::Debug, ops::Deref}; use frame_support::{ defensive, pallet_prelude::*, @@ -223,7 +227,6 @@ use sp_runtime::{ traits::{One, Zero}, SaturatedConversion, Saturating, }; -use sp_std::{fmt::Debug, ops::Deref, prelude::*, vec}; use sp_weights::WeightMeter; pub use weights::WeightInfo; @@ -307,7 +310,7 @@ impl< return Err(()) } - let mut heap = sp_std::mem::take(&mut self.heap).into_inner(); + let mut heap = core::mem::take(&mut self.heap).into_inner(); header.using_encoded(|h| heap.extend_from_slice(h)); heap.extend_from_slice(message.deref()); self.heap = BoundedVec::defensive_truncate_from(heap); @@ -1509,7 +1512,7 @@ pub(crate) fn with_service_mutex R, R>(f: F) -> Result { } /// Provides a [`sp_core::Get`] to access the `MEL` of a [`codec::MaxEncodedLen`] type. -pub struct MaxEncodedLenOf(sp_std::marker::PhantomData); +pub struct MaxEncodedLenOf(core::marker::PhantomData); impl Get for MaxEncodedLenOf { fn get() -> u32 { T::max_encoded_len() as u32 @@ -1518,7 +1521,7 @@ impl Get for MaxEncodedLenOf { /// Calculates the maximum message length and exposed it through the [`codec::MaxEncodedLen`] trait. pub struct MaxMessageLen( - sp_std::marker::PhantomData<(Origin, Size, HeapSize)>, + core::marker::PhantomData<(Origin, Size, HeapSize)>, ); impl, HeapSize: Get> Get for MaxMessageLen @@ -1544,7 +1547,7 @@ pub type BookStateOf = BookState>; /// Converts a [`sp_core::Get`] with returns a type that can be cast into an `u32` into a `Get` /// which returns an `u32`. -pub struct IntoU32(sp_std::marker::PhantomData<(T, O)>); +pub struct IntoU32(core::marker::PhantomData<(T, O)>); impl, O: Into> Get for IntoU32 { fn get() -> u32 { T::get().into() diff --git a/substrate/frame/message-queue/src/mock.rs b/substrate/frame/message-queue/src/mock.rs index 66a242d5a18ff7f72dd08a4c0a0519c82f1cfbbc..26533cc7c330c00564d0a14a9898ca4568fffbcf 100644 --- a/substrate/frame/message-queue/src/mock.rs +++ b/substrate/frame/message-queue/src/mock.rs @@ -23,9 +23,9 @@ pub use super::mock_helpers::*; use super::*; use crate as pallet_message_queue; +use alloc::collections::btree_map::BTreeMap; use frame_support::{derive_impl, parameter_types}; use sp_runtime::BuildStorage; -use sp_std::collections::btree_map::BTreeMap; type Block = frame_system::mocking::MockBlock; diff --git a/substrate/frame/message-queue/src/mock_helpers.rs b/substrate/frame/message-queue/src/mock_helpers.rs index 28395e27cdd2aaffcda2650fbc0988f764b03f92..873add776e2093977962a084e35b921a92ba7338 100644 --- a/substrate/frame/message-queue/src/mock_helpers.rs +++ b/substrate/frame/message-queue/src/mock_helpers.rs @@ -22,6 +22,7 @@ //! Cannot be put into mock.rs since benchmarks require no-std and mock.rs is std. use crate::*; +use alloc::vec::Vec; use frame_support::traits::Defensive; /// Converts `Self` into a `Weight` by using `Self` for all components. diff --git a/substrate/frame/migrations/Cargo.toml b/substrate/frame/migrations/Cargo.toml index 5a946d3aa05816ef258ef3ce47c65bbf2fdc08d2..5fbed74a4400704db6610ec54e3aba8dd234cdae 100644 --- a/substrate/frame/migrations/Cargo.toml +++ b/substrate/frame/migrations/Cargo.toml @@ -21,7 +21,6 @@ frame-benchmarking = { optional = true, workspace = true } frame-support = { workspace = true } frame-system = { workspace = true } sp-core = { workspace = true } -sp-std = { workspace = true } sp-runtime = { workspace = true } [dev-dependencies] @@ -46,7 +45,6 @@ std = [ "scale-info/std", "sp-core/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ diff --git a/substrate/frame/migrations/src/lib.rs b/substrate/frame/migrations/src/lib.rs index 649bc314a12b5fb96816201028c98f5416e542a9..68041a57eaa2e8f673f5f9c9fb774027587c25cb 100644 --- a/substrate/frame/migrations/src/lib.rs +++ b/substrate/frame/migrations/src/lib.rs @@ -69,22 +69,22 @@ //! either be [`MigrationCursor::Active`] or [`MigrationCursor::Stuck`]. In the active case it //! points to the currently active migration and stores its inner cursor. The inner cursor can then //! be used by the migration to store its inner state and advance. Each time when the migration -//! returns `Some(cursor)`, it signals the pallet that it is not done yet. +//! returns `Some(cursor)`, it signals the pallet that it is not done yet. //! The cursor is reset on each runtime upgrade. This ensures that it starts to execute at the //! first migration in the vector. The pallets cursor is only ever incremented or set to `Stuck` //! once it encounters an error (Goal 4). Once in the stuck state, the pallet will stay stuck until -//! it is fixed through manual governance intervention. +//! it is fixed through manual governance intervention. //! As soon as the cursor of the pallet becomes `Some(_)`; [`MultiStepMigrator::ongoing`] returns //! `true` (Goal 2). This can be used by upstream code to possibly pause transactions. //! In `on_initialize` the pallet will load the current migration and check whether it was already //! executed in the past by checking for membership of its ID in the [`Historic`] set. Historic //! migrations are skipped without causing an error. Each successfully executed migration is added -//! to this set (Goal 5). +//! to this set (Goal 5). //! This proceeds until no more migrations remain. At that point, the event `UpgradeCompleted` is -//! emitted (Goal 1). +//! emitted (Goal 1). //! The execution of each migration happens by calling [`SteppedMigration::transactional_step`]. //! This function wraps the inner `step` function into a transactional layer to allow rollback in -//! the error case (Goal 6). +//! the error case (Goal 6). //! Weight limits must be checked by the migration itself. The pallet provides a [`WeightMeter`] for //! that purpose. The pallet may return [`SteppedMigrationError::InsufficientWeight`] at any point. //! In that scenario, one of two things will happen: if that migration was exclusively executed @@ -145,9 +145,12 @@ pub mod mock_helpers; mod tests; pub mod weights; +extern crate alloc; + pub use pallet::*; pub use weights::WeightInfo; +use alloc::vec::Vec; use codec::{Decode, Encode, MaxEncodedLen}; use core::ops::ControlFlow; use frame_support::{ @@ -159,7 +162,6 @@ use frame_support::{ }; use frame_system::{pallet_prelude::BlockNumberFor, Pallet as System}; use sp_runtime::Saturating; -use sp_std::vec::Vec; /// Points to the next migration to execute. #[derive(Debug, Clone, Eq, PartialEq, Encode, Decode, scale_info::TypeInfo, MaxEncodedLen)] diff --git a/substrate/frame/migrations/src/mock_helpers.rs b/substrate/frame/migrations/src/mock_helpers.rs index d230417d12e6c5691f3538c36c1c6b632544cec9..9d3b4d1193f21e8a0fd35463d161cc4df978146a 100644 --- a/substrate/frame/migrations/src/mock_helpers.rs +++ b/substrate/frame/migrations/src/mock_helpers.rs @@ -19,6 +19,7 @@ #![allow(missing_docs)] +use alloc::{vec, vec::Vec}; use codec::{Decode, Encode}; use frame_support::{ migrations::*, @@ -26,7 +27,6 @@ use frame_support::{ }; use sp_core::ConstU32; use sp_runtime::BoundedVec; -use sp_std::{vec, vec::Vec}; /// Opaque identifier of a migration. pub type MockedIdentifier = BoundedVec>; diff --git a/substrate/frame/mixnet/Cargo.toml b/substrate/frame/mixnet/Cargo.toml index f3bea3d2914752930a4164b8c19ab6ce0c444018..a9980ac268bcbbaf451eef99af000c78ef6bdbd6 100644 --- a/substrate/frame/mixnet/Cargo.toml +++ b/substrate/frame/mixnet/Cargo.toml @@ -28,7 +28,6 @@ sp-arithmetic = { workspace = true } sp-io = { workspace = true } sp-mixnet = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [features] default = ["std"] @@ -45,7 +44,6 @@ std = [ "sp-io/std", "sp-mixnet/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/mixnet/src/lib.rs b/substrate/frame/mixnet/src/lib.rs index c7a5b624157b88610f6728fffc6f70daef59f9ad..c0505a4f010577cbb791d116526f119b603bbe76 100644 --- a/substrate/frame/mixnet/src/lib.rs +++ b/substrate/frame/mixnet/src/lib.rs @@ -21,7 +21,11 @@ #![warn(missing_docs)] #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + +use alloc::vec::Vec; use codec::{Decode, Encode, MaxEncodedLen}; +use core::cmp::Ordering; use frame_support::{ traits::{EstimateNextSessionRotation, Get, OneSessionHandler}, BoundedVec, @@ -41,7 +45,6 @@ use sp_mixnet::types::{ SessionPhase, SessionStatus, KX_PUBLIC_SIZE, }; use sp_runtime::RuntimeDebug; -use sp_std::{cmp::Ordering, vec::Vec}; const LOG_TARGET: &str = "runtime::mixnet"; diff --git a/substrate/frame/multisig/Cargo.toml b/substrate/frame/multisig/Cargo.toml index 329b2e8824e2449ae99ad55f9a6796fd35f1c044..c1571c6c0300abdfe2d73ac60b79ee42c1c89788 100644 --- a/substrate/frame/multisig/Cargo.toml +++ b/substrate/frame/multisig/Cargo.toml @@ -23,7 +23,6 @@ frame-support = { workspace = true } frame-system = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } # third party log = { workspace = true } @@ -43,7 +42,6 @@ std = [ "scale-info/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/multisig/src/lib.rs b/substrate/frame/multisig/src/lib.rs index a83b78e316f500ddc9c615420c2ac627b90ee7e9..51c36773bdad34b4f1bf0f7760998de1fdcbc7fc 100644 --- a/substrate/frame/multisig/src/lib.rs +++ b/substrate/frame/multisig/src/lib.rs @@ -48,6 +48,9 @@ pub mod migrations; mod tests; pub mod weights; +extern crate alloc; + +use alloc::{boxed::Box, vec, vec::Vec}; use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{ dispatch::{ @@ -66,7 +69,6 @@ use sp_runtime::{ traits::{Dispatchable, TrailingZeroInput, Zero}, DispatchError, RuntimeDebug, }; -use sp_std::prelude::*; pub use weights::WeightInfo; pub use pallet::*; diff --git a/substrate/frame/nft-fractionalization/Cargo.toml b/substrate/frame/nft-fractionalization/Cargo.toml index f0613581257e9418e38990e6f74a45065d076493..ca2e70cbe6cefe6b0ac5340ed1268daf3ae9590b 100644 --- a/substrate/frame/nft-fractionalization/Cargo.toml +++ b/substrate/frame/nft-fractionalization/Cargo.toml @@ -25,7 +25,6 @@ frame-system = { workspace = true } pallet-assets = { workspace = true } pallet-nfts = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] pallet-balances = { workspace = true, default-features = true } @@ -48,7 +47,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/nft-fractionalization/src/benchmarking.rs b/substrate/frame/nft-fractionalization/src/benchmarking.rs index 0b54acdab49ea7d66fe0f8646c29a254ecd84cbd..811b5fe1b3177ae82d1d20fc2969405067494028 100644 --- a/substrate/frame/nft-fractionalization/src/benchmarking.rs +++ b/substrate/frame/nft-fractionalization/src/benchmarking.rs @@ -32,7 +32,6 @@ use frame_support::{ use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin as SystemOrigin}; use pallet_nfts::{CollectionConfig, CollectionSettings, ItemConfig, MintSettings}; use sp_runtime::traits::StaticLookup; -use sp_std::prelude::*; use crate::Pallet as NftFractionalization; diff --git a/substrate/frame/nft-fractionalization/src/lib.rs b/substrate/frame/nft-fractionalization/src/lib.rs index cb269f464c48aea9555498c1bdf3f4d261c01895..5fa990ecebe66e5b48069cbc4f90f50f032f528a 100644 --- a/substrate/frame/nft-fractionalization/src/lib.rs +++ b/substrate/frame/nft-fractionalization/src/lib.rs @@ -56,6 +56,7 @@ pub use weights::WeightInfo; #[frame_support::pallet] pub mod pallet { use super::*; + use core::fmt::Display; use frame_support::{ dispatch::DispatchResult, ensure, @@ -83,7 +84,6 @@ pub mod pallet { use frame_system::pallet_prelude::*; use scale_info::prelude::{format, string::String}; use sp_runtime::traits::{One, Zero}; - use sp_std::{fmt::Display, prelude::*}; #[pallet::pallet] pub struct Pallet(_); diff --git a/substrate/frame/nfts/Cargo.toml b/substrate/frame/nfts/Cargo.toml index a1eef3226ecf7ac1b7f5ae91fa471854691dd7fc..e3ffd971a2bb6dafad807fd4be56fd16d4441b22 100644 --- a/substrate/frame/nfts/Cargo.toml +++ b/substrate/frame/nfts/Cargo.toml @@ -26,7 +26,6 @@ frame-system = { workspace = true } sp-core = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] pallet-balances = { workspace = true, default-features = true } @@ -47,7 +46,6 @@ std = [ "sp-io/std", "sp-keystore/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/nfts/runtime-api/Cargo.toml b/substrate/frame/nfts/runtime-api/Cargo.toml index 731f5f5ae7767f918d5cd6f775f4a48c2cc7d6ac..4125aa1aab00b8a8bfe5aa29046a81ca9f98005e 100644 --- a/substrate/frame/nfts/runtime-api/Cargo.toml +++ b/substrate/frame/nfts/runtime-api/Cargo.toml @@ -19,8 +19,7 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { features = ["derive"], workspace = true } pallet-nfts = { workspace = true } sp-api = { workspace = true } -sp-std = { workspace = true } [features] default = ["std"] -std = ["codec/std", "pallet-nfts/std", "sp-api/std", "sp-std/std"] +std = ["codec/std", "pallet-nfts/std", "sp-api/std"] diff --git a/substrate/frame/nfts/runtime-api/src/lib.rs b/substrate/frame/nfts/runtime-api/src/lib.rs index 816088f1b716adb25a83455ee35f0af8e961811f..87faa7909851ed0ec17634071a4f58594ebc5993 100644 --- a/substrate/frame/nfts/runtime-api/src/lib.rs +++ b/substrate/frame/nfts/runtime-api/src/lib.rs @@ -19,8 +19,10 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + +use alloc::vec::Vec; use codec::{Decode, Encode}; -use sp_std::vec::Vec; sp_api::decl_runtime_apis! { pub trait NftsApi diff --git a/substrate/frame/nfts/src/benchmarking.rs b/substrate/frame/nfts/src/benchmarking.rs index 80860bc5a53c432685abd7144e92b85e0c697edf..bc81096b459dcce0d41bf8b8a6acb0ccc849a518 100644 --- a/substrate/frame/nfts/src/benchmarking.rs +++ b/substrate/frame/nfts/src/benchmarking.rs @@ -31,7 +31,6 @@ use frame_support::{ }; use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin as SystemOrigin}; use sp_runtime::traits::{Bounded, One}; -use sp_std::prelude::*; use crate::Pallet as Nfts; diff --git a/substrate/frame/nfts/src/common_functions.rs b/substrate/frame/nfts/src/common_functions.rs index 1ad523d664c7cf884d1a3da7368db776c311958a..2c4778c1444f7dd42e25aa00c77f73aca1f5beea 100644 --- a/substrate/frame/nfts/src/common_functions.rs +++ b/substrate/frame/nfts/src/common_functions.rs @@ -18,6 +18,7 @@ //! Various pieces of common functionality. use crate::*; +use alloc::vec::Vec; use frame_support::pallet_prelude::*; impl, I: 'static> Pallet { diff --git a/substrate/frame/nfts/src/features/metadata.rs b/substrate/frame/nfts/src/features/metadata.rs index 85edd294d50b7d82e578afc0014ce9890ffe903c..260061603e9cc3024b0599b5949094d41af4f443 100644 --- a/substrate/frame/nfts/src/features/metadata.rs +++ b/substrate/frame/nfts/src/features/metadata.rs @@ -18,6 +18,7 @@ //! This module contains helper methods to configure the metadata of collections and items. use crate::*; +use alloc::vec::Vec; use frame_support::pallet_prelude::*; impl, I: 'static> Pallet { diff --git a/substrate/frame/nfts/src/features/roles.rs b/substrate/frame/nfts/src/features/roles.rs index f6d2785fd9cb4094d8565489099097ece7b4377a..aa6394f70bfd4a5d69f2da24f7709bd8eb3918cd 100644 --- a/substrate/frame/nfts/src/features/roles.rs +++ b/substrate/frame/nfts/src/features/roles.rs @@ -18,8 +18,8 @@ //! This module contains helper methods to configure account roles for existing collections. use crate::*; +use alloc::{collections::btree_map::BTreeMap, vec::Vec}; use frame_support::pallet_prelude::*; -use sp_std::collections::btree_map::BTreeMap; impl, I: 'static> Pallet { /// Set the team roles for a specific collection. diff --git a/substrate/frame/nfts/src/impl_nonfungibles.rs b/substrate/frame/nfts/src/impl_nonfungibles.rs index ee7f42cfc689c5852fcf8b2a35bdb0acb33d4b7e..c90655aadbfc643b546c5c415d3baa8ca4fdea95 100644 --- a/substrate/frame/nfts/src/impl_nonfungibles.rs +++ b/substrate/frame/nfts/src/impl_nonfungibles.rs @@ -25,7 +25,6 @@ use frame_support::{ BoundedSlice, }; use sp_runtime::{DispatchError, DispatchResult}; -use sp_std::prelude::*; impl, I: 'static> Inspect<::AccountId> for Pallet { type ItemId = T::ItemId; diff --git a/substrate/frame/nfts/src/lib.rs b/substrate/frame/nfts/src/lib.rs index 0406cac6e2c983da4e7ef3db9e4fd506c1803506..4e5493a3c755192752e2ed231605fe9a4cc6ec99 100644 --- a/substrate/frame/nfts/src/lib.rs +++ b/substrate/frame/nfts/src/lib.rs @@ -48,6 +48,9 @@ mod types; pub mod macros; pub mod weights; +extern crate alloc; + +use alloc::{boxed::Box, vec, vec::Vec}; use codec::{Decode, Encode}; use frame_support::traits::{ tokens::Locker, BalanceStatus::Reserved, Currency, EnsureOriginWithArg, Incrementable, @@ -58,7 +61,6 @@ use sp_runtime::{ traits::{IdentifyAccount, Saturating, StaticLookup, Verify, Zero}, RuntimeDebug, }; -use sp_std::prelude::*; pub use pallet::*; pub use types::*; diff --git a/substrate/frame/nfts/src/tests.rs b/substrate/frame/nfts/src/tests.rs index 4d23aca64ceb1ca604cc69b0918e47bfb0ea0eea..e1b598ca4261c86328ef779d242508a66b8cee7f 100644 --- a/substrate/frame/nfts/src/tests.rs +++ b/substrate/frame/nfts/src/tests.rs @@ -32,7 +32,6 @@ use sp_runtime::{ traits::{Dispatchable, IdentifyAccount}, MultiSignature, MultiSigner, }; -use sp_std::prelude::*; type AccountIdOf = ::AccountId; diff --git a/substrate/frame/nfts/src/types.rs b/substrate/frame/nfts/src/types.rs index 5a9f6ae2f0e215341aba160fc24cd5eebe6dd682..1687a03520afe88c29831b94d6db23567d2ffce9 100644 --- a/substrate/frame/nfts/src/types.rs +++ b/substrate/frame/nfts/src/types.rs @@ -19,6 +19,7 @@ use super::*; use crate::macros::*; +use alloc::{vec, vec::Vec}; use codec::EncodeLike; use enumflags2::{bitflags, BitFlags}; use frame_support::{ diff --git a/substrate/frame/nis/Cargo.toml b/substrate/frame/nis/Cargo.toml index 418c906e2b66cfae53d475ff0007336cbe93b5ea..fb6c25789b26d42cf406be0531239c2d83ea3373 100644 --- a/substrate/frame/nis/Cargo.toml +++ b/substrate/frame/nis/Cargo.toml @@ -24,7 +24,6 @@ frame-system = { workspace = true } sp-arithmetic = { workspace = true } sp-core = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] pallet-balances = { workspace = true, default-features = true } @@ -43,7 +42,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/nis/src/benchmarking.rs b/substrate/frame/nis/src/benchmarking.rs index f6a83b78d518126fcb423d9e3fce5331b1557a31..2c7ad651f990340c3a8ee13a0a3066d3abd94218 100644 --- a/substrate/frame/nis/src/benchmarking.rs +++ b/substrate/frame/nis/src/benchmarking.rs @@ -30,7 +30,6 @@ use sp_runtime::{ traits::{Bounded, One, Zero}, DispatchError, PerThing, }; -use sp_std::prelude::*; use crate::Pallet as Nis; diff --git a/substrate/frame/nis/src/lib.rs b/substrate/frame/nis/src/lib.rs index d815ea6ac115cc3bc3ddbf45d74a6f7c252e5455..016daa4cb78be7adc714d47132a7d335741a7530 100644 --- a/substrate/frame/nis/src/lib.rs +++ b/substrate/frame/nis/src/lib.rs @@ -76,6 +76,8 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + use frame_support::traits::{ fungible::{self, Inspect as FunInspect, Mutate as FunMutate}, tokens::{DepositConsequence, Fortitude, Preservation, Provenance, WithdrawConsequence}, @@ -95,7 +97,7 @@ mod mock; mod tests; pub mod weights; -pub struct WithMaximumOf(sp_std::marker::PhantomData); +pub struct WithMaximumOf(core::marker::PhantomData); impl Convert for WithMaximumOf where A::Type: Clone + Unsigned + From, @@ -116,7 +118,7 @@ where } } -pub struct NoCounterpart(sp_std::marker::PhantomData); +pub struct NoCounterpart(core::marker::PhantomData); impl FunInspect for NoCounterpart { type Balance = u32; fn total_issuance() -> u32 { @@ -171,6 +173,7 @@ impl BenchmarkSetup for () { pub mod pallet { use super::{FunInspect, FunMutate}; pub use crate::weights::WeightInfo; + use alloc::{vec, vec::Vec}; use frame_support::{ pallet_prelude::*, traits::{ @@ -193,7 +196,6 @@ pub mod pallet { traits::{AccountIdConversion, Bounded, Convert, ConvertBack, Saturating, Zero}, Rounding, TokenError, }; - use sp_std::prelude::*; type BalanceOf = <::Currency as FunInspect<::AccountId>>::Balance; @@ -372,7 +374,7 @@ pub mod pallet { pub receipts_on_hold: Balance, } - pub struct OnEmptyQueueTotals(sp_std::marker::PhantomData); + pub struct OnEmptyQueueTotals(core::marker::PhantomData); impl Get> for OnEmptyQueueTotals { fn get() -> QueueTotalsTypeOf { BoundedVec::truncate_from(vec![ @@ -573,7 +575,7 @@ pub mod pallet { // queue is let mut bid = Bid { amount, who: who.clone() }; let net = if queue_full { - sp_std::mem::swap(&mut q[0], &mut bid); + core::mem::swap(&mut q[0], &mut bid); let _ = T::Currency::release( &HoldReason::NftReceipt.into(), &bid.who, diff --git a/substrate/frame/node-authorization/Cargo.toml b/substrate/frame/node-authorization/Cargo.toml index d16e9bc6ead6c3c4e17cd56e27ff504716725436..b56a76ce641aa20bf5e3b6f01bc664a3f383552f 100644 --- a/substrate/frame/node-authorization/Cargo.toml +++ b/substrate/frame/node-authorization/Cargo.toml @@ -23,7 +23,6 @@ frame-system = { workspace = true } sp-core = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [features] default = ["std"] @@ -36,7 +35,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] try-runtime = [ "frame-support/try-runtime", diff --git a/substrate/frame/node-authorization/src/lib.rs b/substrate/frame/node-authorization/src/lib.rs index a7967536079f9cf1c72940ff1cdc8847052e9318..7682b54ea0f242b9c09a72bd6f134aa584598350 100644 --- a/substrate/frame/node-authorization/src/lib.rs +++ b/substrate/frame/node-authorization/src/lib.rs @@ -44,10 +44,12 @@ mod tests; pub mod weights; +extern crate alloc; + +use alloc::{collections::btree_set::BTreeSet, vec::Vec}; pub use pallet::*; use sp_core::OpaquePeerId as PeerId; use sp_runtime::traits::StaticLookup; -use sp_std::{collections::btree_set::BTreeSet, prelude::*}; pub use weights::WeightInfo; type AccountIdLookupOf = <::Lookup as StaticLookup>::Source; diff --git a/substrate/frame/nomination-pools/Cargo.toml b/substrate/frame/nomination-pools/Cargo.toml index 535d5252435f38d3dd85fd0d8c923b29c2e00f34..bfcc92edb7e2ea18c554bebdfa678b921986b46b 100644 --- a/substrate/frame/nomination-pools/Cargo.toml +++ b/substrate/frame/nomination-pools/Cargo.toml @@ -27,7 +27,6 @@ scale-info = { features = [ frame-support = { workspace = true } frame-system = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } sp-staking = { workspace = true } sp-core = { workspace = true } sp-io = { workspace = true } @@ -55,7 +54,6 @@ std = [ "sp-io/std", "sp-runtime/std", "sp-staking/std", - "sp-std/std", "sp-tracing?/std", ] runtime-benchmarks = [ diff --git a/substrate/frame/nomination-pools/benchmarking/Cargo.toml b/substrate/frame/nomination-pools/benchmarking/Cargo.toml index 1516f0154b88f91153e1c4872a297b56eb1bcb7b..e73a208926ee547da736b7a1ce0e114db12ef18d 100644 --- a/substrate/frame/nomination-pools/benchmarking/Cargo.toml +++ b/substrate/frame/nomination-pools/benchmarking/Cargo.toml @@ -34,7 +34,6 @@ pallet-nomination-pools = { workspace = true } sp-runtime = { workspace = true } sp-runtime-interface = { workspace = true } sp-staking = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] pallet-balances = { workspace = true } @@ -64,7 +63,6 @@ std = [ "sp-runtime-interface/std", "sp-runtime/std", "sp-staking/std", - "sp-std/std", ] runtime-benchmarks = [ diff --git a/substrate/frame/nomination-pools/benchmarking/src/inner.rs b/substrate/frame/nomination-pools/benchmarking/src/inner.rs index b8c978945e9ee18657e5307c0aebd1d4aaf742fd..2a455942511123327d1c6cb2826f46d4afea77ba 100644 --- a/substrate/frame/nomination-pools/benchmarking/src/inner.rs +++ b/substrate/frame/nomination-pools/benchmarking/src/inner.rs @@ -17,6 +17,7 @@ //! Benchmarks for the nomination pools coupled with the staking and bags list pallets. +use alloc::{vec, vec::Vec}; use frame_benchmarking::v1::{account, whitelist_account}; use frame_election_provider_support::SortedListProvider; use frame_support::{ @@ -41,7 +42,6 @@ use sp_runtime::{ Perbill, }; use sp_staking::EraIndex; -use sp_std::{vec, vec::Vec}; // `frame_benchmarking::benchmarks!` macro needs this use pallet_nomination_pools::Call; diff --git a/substrate/frame/nomination-pools/benchmarking/src/lib.rs b/substrate/frame/nomination-pools/benchmarking/src/lib.rs index 910cdf2e3dff6353d90a2ba138c4731b0b020a0f..feb73be716818b52ddfface317a4adba3f94b6cf 100644 --- a/substrate/frame/nomination-pools/benchmarking/src/lib.rs +++ b/substrate/frame/nomination-pools/benchmarking/src/lib.rs @@ -20,6 +20,8 @@ #![cfg_attr(not(feature = "std"), no_std)] #![recursion_limit = "256"] +extern crate alloc; + #[cfg(feature = "runtime-benchmarks")] pub mod inner; diff --git a/substrate/frame/nomination-pools/runtime-api/Cargo.toml b/substrate/frame/nomination-pools/runtime-api/Cargo.toml index 2b217e021455fddac8fc1c7efe5719901c7f1d9f..2f91e550bc05371bd01a2cb1a85040a6e39da12d 100644 --- a/substrate/frame/nomination-pools/runtime-api/Cargo.toml +++ b/substrate/frame/nomination-pools/runtime-api/Cargo.toml @@ -18,9 +18,8 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { features = ["derive"], workspace = true } sp-api = { workspace = true } -sp-std = { workspace = true } pallet-nomination-pools = { workspace = true } [features] default = ["std"] -std = ["codec/std", "pallet-nomination-pools/std", "sp-api/std", "sp-std/std"] +std = ["codec/std", "pallet-nomination-pools/std", "sp-api/std"] diff --git a/substrate/frame/nomination-pools/src/adapter.rs b/substrate/frame/nomination-pools/src/adapter.rs index 4809fbc0e9da08f3f8d84f662acec5ce5a4de6cd..4d571855e4fe8a967d80579c4f2b8fa521f43309 100644 --- a/substrate/frame/nomination-pools/src/adapter.rs +++ b/substrate/frame/nomination-pools/src/adapter.rs @@ -83,7 +83,7 @@ impl Member { /// [`DelegateStake`] for more detail. pub trait StakeStrategy { type Balance: frame_support::traits::tokens::Balance; - type AccountId: Clone + sp_std::fmt::Debug; + type AccountId: Clone + core::fmt::Debug; type CoreStaking: StakingInterface; /// The type of staking strategy of the current adapter. diff --git a/substrate/frame/nomination-pools/src/lib.rs b/substrate/frame/nomination-pools/src/lib.rs index 2b5fe8b604121db66c8db94ae27e70ba29ba7afd..70ad06e2a4da3bb0f1a55ba6d8ac850076ac3b70 100644 --- a/substrate/frame/nomination-pools/src/lib.rs +++ b/substrate/frame/nomination-pools/src/lib.rs @@ -351,8 +351,12 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + use adapter::{Member, Pool, StakeStrategy}; +use alloc::{collections::btree_map::BTreeMap, vec::Vec}; use codec::Codec; +use core::{fmt::Debug, ops::Div}; use frame_support::{ defensive, defensive_assert, ensure, pallet_prelude::{MaxEncodedLen, *}, @@ -375,7 +379,6 @@ use sp_runtime::{ FixedPointNumber, Perbill, }; use sp_staking::{EraIndex, StakingInterface}; -use sp_std::{collections::btree_map::BTreeMap, fmt::Debug, ops::Div, vec::Vec}; #[cfg(any(feature = "try-runtime", feature = "fuzzing", test, debug_assertions))] use sp_runtime::TryRuntimeError; @@ -949,14 +952,14 @@ pub struct BondedPool { inner: BondedPoolInner, } -impl sp_std::ops::Deref for BondedPool { +impl core::ops::Deref for BondedPool { type Target = BondedPoolInner; fn deref(&self) -> &Self::Target { &self.inner } } -impl sp_std::ops::DerefMut for BondedPool { +impl core::ops::DerefMut for BondedPool { fn deref_mut(&mut self) -> &mut Self::Target { &mut self.inner } @@ -1982,8 +1985,13 @@ pub mod pallet { #[pallet::call] impl Pallet { - /// Stake funds with a pool. The amount to bond is transferred from the member to the - /// pools account and immediately increases the pools bond. + /// Stake funds with a pool. The amount to bond is transferred from the member to the pool + /// account and immediately increases the pools bond. + /// + /// The method of transferring the amount to the pool account is determined by + /// [`adapter::StakeStrategyType`]. If the pool is configured to use + /// [`adapter::StakeStrategyType::Delegate`], the funds remain in the account of + /// the `origin`, while the pool gains the right to use these funds for staking. /// /// # Note /// @@ -2600,7 +2608,7 @@ pub mod pallet { ) -> DispatchResult { let mut bonded_pool = match ensure_root(origin.clone()) { Ok(()) => BondedPool::::get(pool_id).ok_or(Error::::PoolNotFound)?, - Err(frame_support::error::BadOrigin) => { + Err(sp_runtime::traits::BadOrigin) => { let who = ensure_signed(origin)?; let bonded_pool = BondedPool::::get(pool_id).ok_or(Error::::PoolNotFound)?; diff --git a/substrate/frame/nomination-pools/src/migration.rs b/substrate/frame/nomination-pools/src/migration.rs index a9222ea53d75fde59ac47ca0c6fd4d209aa3177b..d8697364a76c57658e94b9d019fe35f356145e3b 100644 --- a/substrate/frame/nomination-pools/src/migration.rs +++ b/substrate/frame/nomination-pools/src/migration.rs @@ -17,8 +17,8 @@ use super::*; use crate::log; +use alloc::{collections::btree_map::BTreeMap, vec::Vec}; use frame_support::traits::{OnRuntimeUpgrade, UncheckedOnRuntimeUpgrade}; -use sp_std::{collections::btree_map::BTreeMap, vec::Vec}; #[cfg(feature = "try-runtime")] use sp_runtime::TryRuntimeError; @@ -60,7 +60,7 @@ pub mod unversioned { use super::*; /// Checks and updates `TotalValueLocked` if out of sync. - pub struct TotalValueLockedSync(sp_std::marker::PhantomData); + pub struct TotalValueLockedSync(core::marker::PhantomData); impl OnRuntimeUpgrade for TotalValueLockedSync { #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result, TryRuntimeError> { @@ -125,7 +125,7 @@ pub mod unversioned { /// /// If there are pools that fail to migrate or did not fit in the bounds, the remaining pools /// can be migrated via the permission-less extrinsic [`Call::migrate_pool_to_delegate_stake`]. - pub struct DelegationStakeMigration(sp_std::marker::PhantomData<(T, MaxPools)>); + pub struct DelegationStakeMigration(core::marker::PhantomData<(T, MaxPools)>); impl> OnRuntimeUpgrade for DelegationStakeMigration { fn on_runtime_upgrade() -> Weight { @@ -262,7 +262,7 @@ pub mod v8 { } } - pub struct VersionUncheckedMigrateV7ToV8(sp_std::marker::PhantomData); + pub struct VersionUncheckedMigrateV7ToV8(core::marker::PhantomData); impl UncheckedOnRuntimeUpgrade for VersionUncheckedMigrateV7ToV8 { #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result, TryRuntimeError> { @@ -341,7 +341,7 @@ pub(crate) mod v7 { pub type BondedPools = CountedStorageMap, Twox64Concat, PoolId, V7BondedPoolInner>; - pub struct VersionUncheckedMigrateV6ToV7(sp_std::marker::PhantomData); + pub struct VersionUncheckedMigrateV6ToV7(core::marker::PhantomData); impl UncheckedOnRuntimeUpgrade for VersionUncheckedMigrateV6ToV7 { fn on_runtime_upgrade() -> Weight { let migrated = BondedPools::::count(); @@ -402,7 +402,7 @@ mod v6 { /// This migration would restrict reward account of pools to go below ED by doing a named /// freeze on all the existing pools. - pub struct MigrateToV6(sp_std::marker::PhantomData); + pub struct MigrateToV6(core::marker::PhantomData); impl MigrateToV6 { fn freeze_ed(pool_id: PoolId) -> Result<(), ()> { @@ -470,7 +470,7 @@ pub mod v5 { /// This migration adds `total_commission_pending` and `total_commission_claimed` field to every /// `RewardPool`, if any. - pub struct MigrateToV5(sp_std::marker::PhantomData); + pub struct MigrateToV5(core::marker::PhantomData); impl OnRuntimeUpgrade for MigrateToV5 { fn on_runtime_upgrade() -> Weight { let in_code = Pallet::::in_code_storage_version(); @@ -625,7 +625,7 @@ pub mod v4 { #[deprecated( note = "To avoid mangled storage please use `MigrateV3ToV5` instead. See: github.com/paritytech/substrate/pull/13715" )] - pub struct MigrateToV4(sp_std::marker::PhantomData<(T, U)>); + pub struct MigrateToV4(core::marker::PhantomData<(T, U)>); #[allow(deprecated)] impl> OnRuntimeUpgrade for MigrateToV4 { fn on_runtime_upgrade() -> Weight { @@ -707,7 +707,7 @@ pub mod v3 { use super::*; /// This migration removes stale bonded-pool metadata, if any. - pub struct MigrateToV3(sp_std::marker::PhantomData); + pub struct MigrateToV3(core::marker::PhantomData); impl OnRuntimeUpgrade for MigrateToV3 { fn on_runtime_upgrade() -> Weight { let current = Pallet::::in_code_storage_version(); @@ -845,7 +845,7 @@ pub mod v2 { /// Migrate the pool reward scheme to the new version, as per /// . - pub struct MigrateToV2(sp_std::marker::PhantomData); + pub struct MigrateToV2(core::marker::PhantomData); impl MigrateToV2 { fn run(current: StorageVersion) -> Weight { let mut reward_pools_translated = 0u64; @@ -1104,7 +1104,7 @@ pub mod v1 { /// Trivial migration which makes the roles of each pool optional. /// /// Note: The depositor is not optional since they can never change. - pub struct MigrateToV1(sp_std::marker::PhantomData); + pub struct MigrateToV1(core::marker::PhantomData); impl OnRuntimeUpgrade for MigrateToV1 { fn on_runtime_upgrade() -> Weight { let current = Pallet::::in_code_storage_version(); diff --git a/substrate/frame/nomination-pools/src/mock.rs b/substrate/frame/nomination-pools/src/mock.rs index 6c0082073f6827a5d264281bc29e08b708233e35..cc942039760c0208776fc2f045310a9cb501c73a 100644 --- a/substrate/frame/nomination-pools/src/mock.rs +++ b/substrate/frame/nomination-pools/src/mock.rs @@ -136,7 +136,7 @@ impl sp_staking::StakingInterface for StakingMock { Ok(()) } - fn update_payee(_stash: &Self::AccountId, _reward_acc: &Self::AccountId) -> DispatchResult { + fn set_payee(_stash: &Self::AccountId, _reward_acc: &Self::AccountId) -> DispatchResult { unimplemented!("method currently not used in testing") } diff --git a/substrate/frame/offences/Cargo.toml b/substrate/frame/offences/Cargo.toml index 51eb3e4f4381797202b8648e59a0378c56ae72e6..9cf5e911a9d3acbf87eb1fd665ab6814163920c4 100644 --- a/substrate/frame/offences/Cargo.toml +++ b/substrate/frame/offences/Cargo.toml @@ -25,7 +25,6 @@ frame-system = { workspace = true } pallet-balances = { workspace = true } sp-runtime = { workspace = true } sp-staking = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] sp-core = { workspace = true, default-features = true } @@ -45,7 +44,6 @@ std = [ "sp-io/std", "sp-runtime/std", "sp-staking/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-support/runtime-benchmarks", diff --git a/substrate/frame/offences/benchmarking/Cargo.toml b/substrate/frame/offences/benchmarking/Cargo.toml index 037812b3ed114a0f5d7f8111ba83fe9da4ca9dd1..eb97eb3d4132af402e2e1e40fed4c5a9e4d8935a 100644 --- a/substrate/frame/offences/benchmarking/Cargo.toml +++ b/substrate/frame/offences/benchmarking/Cargo.toml @@ -31,7 +31,6 @@ pallet-session = { workspace = true } pallet-staking = { workspace = true } sp-runtime = { workspace = true } sp-staking = { workspace = true } -sp-std = { workspace = true } log = { workspace = true } [dev-dependencies] @@ -62,7 +61,6 @@ std = [ "sp-io/std", "sp-runtime/std", "sp-staking/std", - "sp-std/std", ] runtime-benchmarks = [ diff --git a/substrate/frame/offences/benchmarking/src/inner.rs b/substrate/frame/offences/benchmarking/src/inner.rs index 9aa88f7a0d6d08e41d25c6b9e425fc71ba0f78d2..b16e5be653d1e7354ebe29e62304b1c6d065e80c 100644 --- a/substrate/frame/offences/benchmarking/src/inner.rs +++ b/substrate/frame/offences/benchmarking/src/inner.rs @@ -17,7 +17,7 @@ //! Offences pallet benchmarking. -use sp_std::{prelude::*, vec}; +use alloc::{vec, vec::Vec}; use frame_benchmarking::v1::{account, benchmarks}; use frame_support::traits::{Currency, Get}; diff --git a/substrate/frame/offences/benchmarking/src/lib.rs b/substrate/frame/offences/benchmarking/src/lib.rs index b08955a133297f356a5fa884394b3a88a7e28727..f696546d1f0a0b2934d6b14014c937d9a320be23 100644 --- a/substrate/frame/offences/benchmarking/src/lib.rs +++ b/substrate/frame/offences/benchmarking/src/lib.rs @@ -19,6 +19,8 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + #[cfg(feature = "runtime-benchmarks")] pub mod inner; diff --git a/substrate/frame/offences/src/lib.rs b/substrate/frame/offences/src/lib.rs index a328b2fee4e2e72d3254f0a0a8283951bf5a5fc2..ffea32a1f4703dc4a7074f44bc0986b97d126bac 100644 --- a/substrate/frame/offences/src/lib.rs +++ b/substrate/frame/offences/src/lib.rs @@ -26,16 +26,17 @@ pub mod migration; mod mock; mod tests; -use core::marker::PhantomData; +extern crate alloc; +use alloc::vec::Vec; use codec::Encode; +use core::marker::PhantomData; use frame_support::weights::Weight; use sp_runtime::{traits::Hash, Perbill}; use sp_staking::{ offence::{Kind, Offence, OffenceDetails, OffenceError, OnOffenceHandler, ReportOffence}, SessionIndex, }; -use sp_std::prelude::*; pub use pallet::*; diff --git a/substrate/frame/offences/src/migration.rs b/substrate/frame/offences/src/migration.rs index 199f47491369b8281e414076f35e43be823931c8..abf8acd94875d6da7e3bee281487b7869a4c30dd 100644 --- a/substrate/frame/offences/src/migration.rs +++ b/substrate/frame/offences/src/migration.rs @@ -16,6 +16,7 @@ // limitations under the License. use super::{Config, Kind, OffenceDetails, Pallet, Perbill, SessionIndex, LOG_TARGET}; +use alloc::vec::Vec; use frame_support::{ pallet_prelude::ValueQuery, storage_alias, @@ -24,7 +25,6 @@ use frame_support::{ Twox64Concat, }; use sp_staking::offence::OnOffenceHandler; -use sp_std::vec::Vec; #[cfg(feature = "try-runtime")] use frame_support::ensure; @@ -49,7 +49,7 @@ pub mod v1 { use super::*; - pub struct MigrateToV1(sp_std::marker::PhantomData); + pub struct MigrateToV1(core::marker::PhantomData); impl OnRuntimeUpgrade for MigrateToV1 { #[cfg(feature = "try-runtime")] fn pre_upgrade() -> Result, TryRuntimeError> { diff --git a/substrate/frame/paged-list/Cargo.toml b/substrate/frame/paged-list/Cargo.toml index f5a3a2e5bae196736f9a07943fdc78a42436bba8..597bdd37f57fb5a0bdef24e7caf0f45502d06261 100644 --- a/substrate/frame/paged-list/Cargo.toml +++ b/substrate/frame/paged-list/Cargo.toml @@ -24,7 +24,6 @@ frame-support = { workspace = true } frame-system = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } sp-core = { workspace = true } sp-io = { workspace = true } sp-metadata-ir = { optional = true, workspace = true } @@ -42,7 +41,6 @@ std = [ "sp-io/std", "sp-metadata-ir/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ diff --git a/substrate/frame/paged-list/src/lib.rs b/substrate/frame/paged-list/src/lib.rs index ddeed174f34bb5afac01d0ad839e2cd980b5764a..ed68dac63beb69ed68d5e9f85ba80e78d28c1e1a 100644 --- a/substrate/frame/paged-list/src/lib.rs +++ b/substrate/frame/paged-list/src/lib.rs @@ -58,7 +58,7 @@ //! //! ## Low Level / Implementation Details //! -//! Implementation details are documented in [`paged_list::StoragePagedList`]. +//! Implementation details are documented in [`paged_list::StoragePagedList`]. //! All storage entries are prefixed with a unique prefix that is generated by [`ListPrefix`]. #![cfg_attr(not(feature = "std"), no_std)] @@ -69,6 +69,8 @@ pub mod mock; mod paged_list; mod tests; +extern crate alloc; + use codec::FullCodec; use frame_support::{ pallet_prelude::StorageList, diff --git a/substrate/frame/paged-list/src/paged_list.rs b/substrate/frame/paged-list/src/paged_list.rs index eecc728cd62a1dcd29c4db1d48a642102421be9c..bbd889e2521803c69b4fc2dd344ab5d635ae240d 100644 --- a/substrate/frame/paged-list/src/paged_list.rs +++ b/substrate/frame/paged-list/src/paged_list.rs @@ -23,6 +23,7 @@ #![deny(missing_docs)] #![deny(unsafe_code)] +use alloc::vec::Vec; use codec::{Decode, Encode, EncodeLike, FullCodec}; use core::marker::PhantomData; use frame_support::{ @@ -32,7 +33,6 @@ use frame_support::{ CloneNoBound, DebugNoBound, DefaultNoBound, EqNoBound, PartialEqNoBound, }; use sp_runtime::traits::Saturating; -use sp_std::prelude::*; pub type PageIndex = u32; pub type ValueIndex = u32; @@ -177,7 +177,7 @@ pub struct Page { /// The index of the page. index: PageIndex, /// The remaining values of the page, to be drained by [`Page::next`]. - values: sp_std::iter::Skip>, + values: core::iter::Skip>, } impl Page { @@ -188,7 +188,7 @@ impl Page { ) -> Option { let key = page_key::(index); let values = sp_io::storage::get(&key) - .and_then(|raw| sp_std::vec::Vec::::decode(&mut &raw[..]).ok())?; + .and_then(|raw| alloc::vec::Vec::::decode(&mut &raw[..]).ok())?; if values.is_empty() { // Don't create empty pages. return None diff --git a/substrate/frame/parameters/Cargo.toml b/substrate/frame/parameters/Cargo.toml index b993347d24637a5ffa84c238eeb6fb75bbcb9d64..a97ba1172a503df2efb2f820ef8995f8ff9f4a65 100644 --- a/substrate/frame/parameters/Cargo.toml +++ b/substrate/frame/parameters/Cargo.toml @@ -18,7 +18,6 @@ frame-support = { features = ["experimental"], workspace = true } frame-system = { workspace = true } sp-core = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } frame-benchmarking = { optional = true, workspace = true } [dev-dependencies] @@ -38,7 +37,6 @@ std = [ "serde", "sp-core/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/preimage/Cargo.toml b/substrate/frame/preimage/Cargo.toml index ee572b189b231054c0bea0e429c7a4659e9aa301..425c4e81aa7b3e1e7123fa7be734b3ec29404f52 100644 --- a/substrate/frame/preimage/Cargo.toml +++ b/substrate/frame/preimage/Cargo.toml @@ -20,7 +20,6 @@ frame-system = { workspace = true } sp-core = { optional = true, workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } log = { workspace = true } [dev-dependencies] @@ -48,7 +47,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] try-runtime = [ "frame-support/try-runtime", diff --git a/substrate/frame/preimage/src/benchmarking.rs b/substrate/frame/preimage/src/benchmarking.rs index f2b76a7999d6c61827624b3b9ca6d9e55a0341d9..2d3bec16b818331e99a5072c15da55b45b7b521e 100644 --- a/substrate/frame/preimage/src/benchmarking.rs +++ b/substrate/frame/preimage/src/benchmarking.rs @@ -18,11 +18,11 @@ //! Preimage pallet benchmarking. use super::*; +use alloc::vec; use frame_benchmarking::v1::{account, benchmarks, whitelisted_caller, BenchmarkError}; use frame_support::assert_ok; use frame_system::RawOrigin; use sp_runtime::traits::Bounded; -use sp_std::{prelude::*, vec}; use crate::Pallet as Preimage; diff --git a/substrate/frame/preimage/src/lib.rs b/substrate/frame/preimage/src/lib.rs index dd323a12b8f8479ba5d419243c9585f79ac0385a..30056fc6d9a492bd6b72e44d917af573758bab9d 100644 --- a/substrate/frame/preimage/src/lib.rs +++ b/substrate/frame/preimage/src/lib.rs @@ -37,11 +37,13 @@ mod mock; mod tests; pub mod weights; +extern crate alloc; + +use alloc::{borrow::Cow, vec::Vec}; use sp_runtime::{ traits::{BadOrigin, Hash, Saturating}, Perbill, }; -use sp_std::{borrow::Cow, prelude::*}; use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{ diff --git a/substrate/frame/preimage/src/migration.rs b/substrate/frame/preimage/src/migration.rs index a86109f892a4f5b84b6aa48e89bc869f521bf74c..e38483ee68c62404c50ee4facf7fb1fed6562b9c 100644 --- a/substrate/frame/preimage/src/migration.rs +++ b/substrate/frame/preimage/src/migration.rs @@ -18,11 +18,11 @@ //! Storage migrations for the preimage pallet. use super::*; +use alloc::collections::btree_map::BTreeMap; use frame_support::{ storage_alias, traits::{ConstU32, OnRuntimeUpgrade}, }; -use sp_std::collections::btree_map::BTreeMap; #[cfg(feature = "try-runtime")] use frame_support::ensure; @@ -79,7 +79,7 @@ pub mod v1 { /// /// Note: This needs to be run with the same hashing algorithm as before /// since it is not re-hashing the preimages. - pub struct Migration(sp_std::marker::PhantomData); + pub struct Migration(core::marker::PhantomData); impl OnRuntimeUpgrade for Migration { #[cfg(feature = "try-runtime")] diff --git a/substrate/frame/proxy/Cargo.toml b/substrate/frame/proxy/Cargo.toml index 6b4251e1bcc57b8017a6bb76c99fc3aea94d6345..af2427da380a980f2501e4ffc741f5e6706dcfc2 100644 --- a/substrate/frame/proxy/Cargo.toml +++ b/substrate/frame/proxy/Cargo.toml @@ -23,7 +23,6 @@ frame-support = { workspace = true } frame-system = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] pallet-balances = { workspace = true, default-features = true } @@ -43,7 +42,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/proxy/src/benchmarking.rs b/substrate/frame/proxy/src/benchmarking.rs index e0d14163d21b2c7e1d54a12f3027544a310be7b2..4081af49c2435eefe00a62b988ab7ef3dab9b996 100644 --- a/substrate/frame/proxy/src/benchmarking.rs +++ b/substrate/frame/proxy/src/benchmarking.rs @@ -21,6 +21,7 @@ use super::*; use crate::Pallet as Proxy; +use alloc::{boxed::Box, vec}; use frame_benchmarking::v1::{account, benchmarks, whitelisted_caller}; use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; use sp_runtime::traits::Bounded; diff --git a/substrate/frame/proxy/src/lib.rs b/substrate/frame/proxy/src/lib.rs index 2b3fac5f59e4b1fd48f92bffc314cdbad5ec9c22..d681088165c8ffa583008f1ced8bcbf4fd5ffa9d 100644 --- a/substrate/frame/proxy/src/lib.rs +++ b/substrate/frame/proxy/src/lib.rs @@ -33,6 +33,9 @@ mod benchmarking; mod tests; pub mod weights; +extern crate alloc; + +use alloc::{boxed::Box, vec}; use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{ dispatch::GetDispatchInfo, @@ -47,7 +50,6 @@ use sp_runtime::{ traits::{Dispatchable, Hash, Saturating, StaticLookup, TrailingZeroInput, Zero}, DispatchError, DispatchResult, RuntimeDebug, }; -use sp_std::prelude::*; pub use weights::WeightInfo; type CallHashOf = <::CallHasher as Hash>::Output; diff --git a/substrate/frame/proxy/src/tests.rs b/substrate/frame/proxy/src/tests.rs index 3ed61fbedaaa93ca3bbf9976a7303195537ae671..3edb96026a82b07215569fe3dfa01200cb911ca0 100644 --- a/substrate/frame/proxy/src/tests.rs +++ b/substrate/frame/proxy/src/tests.rs @@ -22,6 +22,7 @@ use super::*; use crate as proxy; +use alloc::{vec, vec::Vec}; use codec::{Decode, Encode}; use frame_support::{ assert_noop, assert_ok, derive_impl, diff --git a/substrate/frame/ranked-collective/Cargo.toml b/substrate/frame/ranked-collective/Cargo.toml index be48d5cad4048b90e0b08971f6b005b125adaf59..dd9b466e0f919eb0957fcff7a623aacbe5a077f4 100644 --- a/substrate/frame/ranked-collective/Cargo.toml +++ b/substrate/frame/ranked-collective/Cargo.toml @@ -26,7 +26,6 @@ sp-arithmetic = { workspace = true } sp-core = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } impl-trait-for-tuples = { workspace = true } [features] @@ -42,7 +41,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/ranked-collective/src/benchmarking.rs b/substrate/frame/ranked-collective/src/benchmarking.rs index 462f55a238d2a867f900e4653369e5fa9368d874..dc7f4aaca7735c2867e6a9dd3bde1250d1bd4417 100644 --- a/substrate/frame/ranked-collective/src/benchmarking.rs +++ b/substrate/frame/ranked-collective/src/benchmarking.rs @@ -20,6 +20,7 @@ use super::*; #[allow(unused_imports)] use crate::Pallet as RankedCollective; +use alloc::vec::Vec; use frame_benchmarking::v1::{ account, benchmarks_instance_pallet, whitelisted_caller, BenchmarkError, diff --git a/substrate/frame/ranked-collective/src/lib.rs b/substrate/frame/ranked-collective/src/lib.rs index 53d5f0c6662d760534e87bf6962aca491fe4e617..e34cf3d8df7114099ee02da5731012a81e38f1d7 100644 --- a/substrate/frame/ranked-collective/src/lib.rs +++ b/substrate/frame/ranked-collective/src/lib.rs @@ -40,7 +40,10 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + use codec::{Decode, Encode, MaxEncodedLen}; +use core::marker::PhantomData; use scale_info::TypeInfo; use sp_arithmetic::traits::Saturating; use sp_runtime::{ @@ -48,7 +51,6 @@ use sp_runtime::{ ArithmeticError::Overflow, DispatchError, Perbill, RuntimeDebug, }; -use sp_std::{marker::PhantomData, prelude::*}; use frame_support::{ dispatch::{DispatchResultWithPostInfo, PostDispatchInfo}, diff --git a/substrate/frame/ranked-collective/src/tests.rs b/substrate/frame/ranked-collective/src/tests.rs index a7827bcc1aa379f6a28d0755feb555ad487f4426..3a85928b76d5e093d9212485b4d7760ad9eb6cce 100644 --- a/substrate/frame/ranked-collective/src/tests.rs +++ b/substrate/frame/ranked-collective/src/tests.rs @@ -20,14 +20,12 @@ use std::collections::BTreeMap; use frame_support::{ - assert_noop, assert_ok, derive_impl, - error::BadOrigin, - parameter_types, + assert_noop, assert_ok, derive_impl, parameter_types, traits::{ConstU16, EitherOf, MapSuccess, Polling}, }; use sp_core::Get; use sp_runtime::{ - traits::{MaybeConvert, ReduceBy, ReplaceWithDefault}, + traits::{BadOrigin, MaybeConvert, ReduceBy, ReplaceWithDefault}, BuildStorage, }; diff --git a/substrate/frame/recovery/Cargo.toml b/substrate/frame/recovery/Cargo.toml index 3b3a382fe6dcf8ccde7d4681b835674149896715..42493b435105c16fc1daa662eb745b1f7aae78a9 100644 --- a/substrate/frame/recovery/Cargo.toml +++ b/substrate/frame/recovery/Cargo.toml @@ -23,7 +23,6 @@ frame-support = { workspace = true } frame-system = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] pallet-balances = { workspace = true, default-features = true } @@ -49,7 +48,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] try-runtime = [ "frame-support/try-runtime", diff --git a/substrate/frame/recovery/src/benchmarking.rs b/substrate/frame/recovery/src/benchmarking.rs index 72f77336212dd6b8c7fb64d7b12a32fd0d9dfa44..b7639742a620271172460ef272a36d12aa902f9b 100644 --- a/substrate/frame/recovery/src/benchmarking.rs +++ b/substrate/frame/recovery/src/benchmarking.rs @@ -20,6 +20,7 @@ use super::*; use crate::Pallet; +use alloc::{boxed::Box, vec, vec::Vec}; use frame_benchmarking::v1::{account, benchmarks, whitelisted_caller}; use frame_support::traits::{Currency, Get}; use frame_system::RawOrigin; diff --git a/substrate/frame/recovery/src/lib.rs b/substrate/frame/recovery/src/lib.rs index 5673147c8e0055fcd445fffa6a29046b880e9e11..69be4df971bc47bde7d2cd367e03f241eba887b0 100644 --- a/substrate/frame/recovery/src/lib.rs +++ b/substrate/frame/recovery/src/lib.rs @@ -150,13 +150,15 @@ // Ensure we're `no_std` when compiling for Wasm. #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + +use alloc::{boxed::Box, vec::Vec}; use codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; use sp_runtime::{ traits::{CheckedAdd, CheckedMul, Dispatchable, SaturatedConversion, StaticLookup}, RuntimeDebug, }; -use sp_std::prelude::*; use frame_support::{ dispatch::{GetDispatchInfo, PostDispatchInfo}, diff --git a/substrate/frame/referenda/Cargo.toml b/substrate/frame/referenda/Cargo.toml index eb30fef7894b48a7a5f0685c76d96a88a0fdd43b..578486714d63626b5b456d5f59684db9e2272c87 100644 --- a/substrate/frame/referenda/Cargo.toml +++ b/substrate/frame/referenda/Cargo.toml @@ -28,7 +28,6 @@ frame-support = { workspace = true } frame-system = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } log = { workspace = true } [dev-dependencies] @@ -55,7 +54,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "assert_matches", diff --git a/substrate/frame/referenda/src/benchmarking.rs b/substrate/frame/referenda/src/benchmarking.rs index 47d43cc0600c076b6fce0e541e0f78c97649921e..67ac82787d31d78a859ed0158d7f6be2b1276aea 100644 --- a/substrate/frame/referenda/src/benchmarking.rs +++ b/substrate/frame/referenda/src/benchmarking.rs @@ -19,6 +19,7 @@ use super::*; use crate::Pallet as Referenda; +use alloc::{vec, vec::Vec}; use assert_matches::assert_matches; use frame_benchmarking::v1::{ account, benchmarks_instance_pallet, whitelist_account, BenchmarkError, @@ -632,7 +633,7 @@ benchmarks_instance_pallet! { } set_some_metadata { - use sp_std::borrow::Cow; + use alloc::borrow::Cow; let origin = T::SubmitOrigin::try_successful_origin(&RawOrigin::Root.into()) .expect("SubmitOrigin has no successful origin required for the benchmark"); let index = create_referendum::(origin.clone()); @@ -643,7 +644,7 @@ benchmarks_instance_pallet! { } clear_metadata { - use sp_std::borrow::Cow; + use alloc::borrow::Cow; let origin = T::SubmitOrigin::try_successful_origin(&RawOrigin::Root.into()) .expect("SubmitOrigin has no successful origin required for the benchmark"); let index = create_referendum::(origin.clone()); diff --git a/substrate/frame/referenda/src/lib.rs b/substrate/frame/referenda/src/lib.rs index 0cdf450d3b6c98e942e3613210f31eb34098b008..e72dd7f11cbb2f8f17f32ec9d9b1768ee015ec2d 100644 --- a/substrate/frame/referenda/src/lib.rs +++ b/substrate/frame/referenda/src/lib.rs @@ -64,7 +64,11 @@ #![recursion_limit = "256"] #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + +use alloc::boxed::Box; use codec::{Codec, Encode}; +use core::fmt::Debug; use frame_support::{ dispatch::DispatchResult, ensure, @@ -84,7 +88,6 @@ use sp_runtime::{ traits::{AtLeast32BitUnsigned, Bounded, Dispatchable, One, Saturating, Zero}, DispatchError, Perbill, }; -use sp_std::{fmt::Debug, prelude::*}; mod branch; pub mod migration; @@ -102,6 +105,7 @@ pub use self::{ }, weights::WeightInfo, }; +pub use alloc::vec::Vec; #[cfg(test)] mod mock; @@ -112,7 +116,6 @@ mod tests; pub mod benchmarking; pub use frame_support::traits::Get; -pub use sp_std::vec::Vec; #[macro_export] macro_rules! impl_tracksinfo_get { diff --git a/substrate/frame/referenda/src/types.rs b/substrate/frame/referenda/src/types.rs index b3c583322cce384bae7e2a9340071d5af6b2f455..1039b288b2aecde8db69453f7883f41be349314a 100644 --- a/substrate/frame/referenda/src/types.rs +++ b/substrate/frame/referenda/src/types.rs @@ -515,7 +515,7 @@ impl Curve { #[cfg(feature = "std")] impl Debug for Curve { - fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { Self::LinearDecreasing { length, floor, ceil } => { write!( diff --git a/substrate/frame/remark/Cargo.toml b/substrate/frame/remark/Cargo.toml index 44cf5ebc3b492a0c414716402308d1b5f22214bd..efc9917428c04304446b69c4b543a18e67e99496 100644 --- a/substrate/frame/remark/Cargo.toml +++ b/substrate/frame/remark/Cargo.toml @@ -25,7 +25,6 @@ frame-system = { workspace = true } sp-core = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] sp-core = { workspace = true } @@ -48,7 +47,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] try-runtime = [ "frame-support/try-runtime", diff --git a/substrate/frame/remark/src/benchmarking.rs b/substrate/frame/remark/src/benchmarking.rs index 831946834963f96748b683c01a9673bdb83b5e11..15b72b4748dd406da7bcb551ffe3be2a29e4fca6 100644 --- a/substrate/frame/remark/src/benchmarking.rs +++ b/substrate/frame/remark/src/benchmarking.rs @@ -20,9 +20,9 @@ #![cfg(feature = "runtime-benchmarks")] use super::*; +use alloc::vec; use frame_benchmarking::v1::{benchmarks, whitelisted_caller}; use frame_system::{EventRecord, Pallet as System, RawOrigin}; -use sp_std::*; #[cfg(test)] use crate::Pallet as Remark; diff --git a/substrate/frame/remark/src/lib.rs b/substrate/frame/remark/src/lib.rs index 8ca3cd395afb5063b6ac70e0c7b6412240e4faa2..eae8e0b83f5d235ad6aaf42e49e170e3706baa30 100644 --- a/substrate/frame/remark/src/lib.rs +++ b/substrate/frame/remark/src/lib.rs @@ -28,7 +28,9 @@ mod mock; #[cfg(test)] mod tests; -use sp_std::prelude::*; +extern crate alloc; + +use alloc::vec::Vec; // Re-export pallet items so that they can be accessed from the crate namespace. pub use pallet::*; diff --git a/substrate/frame/root-offences/src/mock.rs b/substrate/frame/root-offences/src/mock.rs index 3c758b91d52fe851dd279a3e7e3bb3b9dd69ebe3..ab43b723e8a9b86d8720d181eb29f01346f3d169 100644 --- a/substrate/frame/root-offences/src/mock.rs +++ b/substrate/frame/root-offences/src/mock.rs @@ -18,6 +18,7 @@ use super::*; use crate as root_offences; +use alloc::collections::btree_map::BTreeMap; use frame_election_provider_support::{ bounds::{ElectionBounds, ElectionBoundsBuilder}, onchain, SequentialPhragmen, @@ -29,7 +30,6 @@ use frame_support::{ use pallet_staking::StakerStatus; use sp_runtime::{curve::PiecewiseLinear, testing::UintAuthorityId, traits::Zero, BuildStorage}; use sp_staking::{EraIndex, SessionIndex}; -use sp_std::collections::btree_map::BTreeMap; type Block = frame_system::mocking::MockBlock; type AccountId = u64; diff --git a/substrate/frame/root-testing/Cargo.toml b/substrate/frame/root-testing/Cargo.toml index 38d91c8104b902eeaf742ab7fa20540ae0d1d598..96d861362622559e6569f2fe61cde0a08de27d75 100644 --- a/substrate/frame/root-testing/Cargo.toml +++ b/substrate/frame/root-testing/Cargo.toml @@ -23,7 +23,6 @@ frame-system = { workspace = true } sp-core = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [features] try-runtime = [ @@ -40,5 +39,4 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] diff --git a/substrate/frame/safe-mode/Cargo.toml b/substrate/frame/safe-mode/Cargo.toml index 749c4bcdc7000d7d772433e92c327284b686d410..b704818f1adf02dad8900bc2eb28e5ec9272a56b 100644 --- a/substrate/frame/safe-mode/Cargo.toml +++ b/substrate/frame/safe-mode/Cargo.toml @@ -23,7 +23,6 @@ frame-system = { workspace = true } scale-info = { features = ["derive"], workspace = true } sp-arithmetic = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } pallet-balances = { optional = true, workspace = true } pallet-utility = { optional = true, workspace = true } pallet-proxy = { optional = true, workspace = true } @@ -51,7 +50,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/salary/Cargo.toml b/substrate/frame/salary/Cargo.toml index c9b72da2e649fa9f04c32d95fde2b3102b239185..9121f59ff4626f27ca1cc0dc0078432542b0a8e4 100644 --- a/substrate/frame/salary/Cargo.toml +++ b/substrate/frame/salary/Cargo.toml @@ -26,7 +26,6 @@ sp-arithmetic = { workspace = true } sp-core = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } pallet-ranked-collective = { optional = true, workspace = true } [features] @@ -44,7 +43,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/sassafras/Cargo.toml b/substrate/frame/sassafras/Cargo.toml index ecd03c47db6898a41ec5c09ea078b79797cb16ed..0eefca57849aa32211a323dd424117743e22d83a 100644 --- a/substrate/frame/sassafras/Cargo.toml +++ b/substrate/frame/sassafras/Cargo.toml @@ -26,7 +26,6 @@ log = { workspace = true } sp-consensus-sassafras = { features = ["serde"], workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] array-bytes = { workspace = true, default-features = true } @@ -45,7 +44,6 @@ std = [ "sp-consensus-sassafras/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/sassafras/src/lib.rs b/substrate/frame/sassafras/src/lib.rs index d521ed9dd91b87ab46ccc19f0643f44d5a2013a6..285758afbe6db8b214fd788a180d760a01aed263 100644 --- a/substrate/frame/sassafras/src/lib.rs +++ b/substrate/frame/sassafras/src/lib.rs @@ -47,10 +47,13 @@ #![warn(unused_must_use, unsafe_code, unused_variables, unused_imports, missing_docs)] #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + use codec::{Decode, Encode, MaxEncodedLen}; use log::{debug, error, trace, warn}; use scale_info::TypeInfo; +use alloc::vec::Vec; use frame_support::{ dispatch::{DispatchResultWithPostInfo, Pays}, traits::{Defensive, Get}, @@ -72,7 +75,6 @@ use sp_runtime::{ traits::{One, Zero}, BoundToRuntimeAppPublic, }; -use sp_std::prelude::Vec; #[cfg(feature = "runtime-benchmarks")] mod benchmarking; @@ -288,7 +290,7 @@ pub mod pallet { pub epoch_config: EpochConfiguration, /// Phantom config #[serde(skip)] - pub _phantom: sp_std::marker::PhantomData, + pub _phantom: core::marker::PhantomData, } #[pallet::genesis_build] diff --git a/substrate/frame/scheduler/Cargo.toml b/substrate/frame/scheduler/Cargo.toml index 0a6b646fc8c3c41ac262758304e33a48a3a2b39d..29aaaec9aa408f1f26b193ddfcfdd32db3ba359d 100644 --- a/substrate/frame/scheduler/Cargo.toml +++ b/substrate/frame/scheduler/Cargo.toml @@ -21,7 +21,6 @@ frame-support = { workspace = true } frame-system = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } sp-weights = { workspace = true } docify = { workspace = true } @@ -51,7 +50,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", "sp-weights/std", ] try-runtime = [ diff --git a/substrate/frame/scheduler/src/benchmarking.rs b/substrate/frame/scheduler/src/benchmarking.rs index 884f78000384cf66696b22de40238bbd2e5bef95..d0a14fc73d64fdc47205810a29e5cb265784a009 100644 --- a/substrate/frame/scheduler/src/benchmarking.rs +++ b/substrate/frame/scheduler/src/benchmarking.rs @@ -18,6 +18,7 @@ //! Scheduler pallet benchmarking. use super::*; +use alloc::vec; use frame_benchmarking::v1::{account, benchmarks, BenchmarkError}; use frame_support::{ ensure, @@ -25,7 +26,6 @@ use frame_support::{ weights::WeightMeter, }; use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin}; -use sp_std::{prelude::*, vec}; use crate::Pallet as Scheduler; use frame_system::{Call as SystemCall, EventRecord}; diff --git a/substrate/frame/scheduler/src/lib.rs b/substrate/frame/scheduler/src/lib.rs index d19a1e0001dd3aed98369b8691187b5cf8dcdfc7..3eecf6d6f9e884e5bf671d781d4918ad91619615 100644 --- a/substrate/frame/scheduler/src/lib.rs +++ b/substrate/frame/scheduler/src/lib.rs @@ -85,7 +85,11 @@ mod mock; mod tests; pub mod weights; +extern crate alloc; + +use alloc::{boxed::Box, vec::Vec}; use codec::{Decode, Encode, MaxEncodedLen}; +use core::{borrow::Borrow, cmp::Ordering, marker::PhantomData}; use frame_support::{ dispatch::{DispatchResult, GetDispatchInfo, Parameter, RawOrigin}, ensure, @@ -106,7 +110,6 @@ use sp_runtime::{ traits::{BadOrigin, Dispatchable, One, Saturating, Zero}, BoundedVec, DispatchError, RuntimeDebug, }; -use sp_std::{borrow::Borrow, cmp::Ordering, marker::PhantomData, prelude::*}; pub use pallet::*; pub use weights::WeightInfo; diff --git a/substrate/frame/scheduler/src/migration.rs b/substrate/frame/scheduler/src/migration.rs index c2e956035a767031ceb64e4e0d42cebfb527e64d..a304689a120cccb8af21ab5922e8478e36f7848c 100644 --- a/substrate/frame/scheduler/src/migration.rs +++ b/substrate/frame/scheduler/src/migration.rs @@ -305,8 +305,8 @@ pub mod v4 { mod test { use super::*; use crate::mock::*; + use alloc::borrow::Cow; use frame_support::Hashable; - use sp_std::borrow::Cow; use substrate_test_utils::assert_eq_uvec; #[test] diff --git a/substrate/frame/scored-pool/Cargo.toml b/substrate/frame/scored-pool/Cargo.toml index 69ecd527eb7c9d4491400e6815ce17511f43f41a..132799ead62a7c0c0618fa481ade112b30b541b2 100644 --- a/substrate/frame/scored-pool/Cargo.toml +++ b/substrate/frame/scored-pool/Cargo.toml @@ -22,7 +22,6 @@ frame-support = { workspace = true } frame-system = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] pallet-balances = { workspace = true, default-features = true } @@ -39,7 +38,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] try-runtime = [ "frame-support/try-runtime", diff --git a/substrate/frame/scored-pool/src/lib.rs b/substrate/frame/scored-pool/src/lib.rs index 2bf70cbc574c8ff4e2f06abeaba51a6eecb88881..c4464bbbfac0448bf449c02e2d9966895942d2da 100644 --- a/substrate/frame/scored-pool/src/lib.rs +++ b/substrate/frame/scored-pool/src/lib.rs @@ -98,7 +98,11 @@ mod mock; #[cfg(test)] mod tests; +extern crate alloc; + +use alloc::vec::Vec; use codec::{FullCodec, MaxEncodedLen}; +use core::{cmp::Reverse, fmt::Debug}; use frame_support::{ ensure, traits::{ChangeMembers, Currency, Get, InitializeMembers, ReservableCurrency}, @@ -106,7 +110,6 @@ use frame_support::{ }; pub use pallet::*; use sp_runtime::traits::{AtLeast32Bit, StaticLookup, Zero}; -use sp_std::{fmt::Debug, prelude::*}; type BalanceOf = <>::Currency as Currency<::AccountId>>::Balance; diff --git a/substrate/frame/session/Cargo.toml b/substrate/frame/session/Cargo.toml index c7b499548bdb4cce9d5fb7a08a2e45f8fe635e61..09bb93d8c1d09abf9d0b266efa6542163bc8ee9d 100644 --- a/substrate/frame/session/Cargo.toml +++ b/substrate/frame/session/Cargo.toml @@ -28,7 +28,6 @@ sp-io = { workspace = true } sp-runtime = { features = ["serde"], workspace = true } sp-session = { workspace = true } sp-staking = { features = ["serde"], workspace = true } -sp-std = { workspace = true } sp-trie = { optional = true, workspace = true } sp-state-machine = { workspace = true } @@ -48,7 +47,6 @@ std = [ "sp-session/std", "sp-staking/std", "sp-state-machine/std", - "sp-std/std", "sp-trie/std", ] try-runtime = [ diff --git a/substrate/frame/session/README.md b/substrate/frame/session/README.md index fa7c9b3f98348e4c72fac4fd44b94c492d656c09..5a063bffee0b17a9274a26b85e290a9f058ee523 100644 --- a/substrate/frame/session/README.md +++ b/substrate/frame/session/README.md @@ -70,7 +70,7 @@ set. use pallet_session as session; fn validators() -> Vec<::ValidatorId> { - >::validators() + pallet_session::Validators::::get() } ``` diff --git a/substrate/frame/session/benchmarking/Cargo.toml b/substrate/frame/session/benchmarking/Cargo.toml index ba7f7acfd9919f58e5fd3e3e2e50534d118ffde4..9ca3549f681dc4747b02e86944ed78f75752e0ac 100644 --- a/substrate/frame/session/benchmarking/Cargo.toml +++ b/substrate/frame/session/benchmarking/Cargo.toml @@ -25,7 +25,6 @@ pallet-session = { workspace = true } pallet-staking = { workspace = true } sp-runtime = { workspace = true } sp-session = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] codec = { features = ["derive"], workspace = true, default-features = true } @@ -53,7 +52,6 @@ std = [ "sp-io/std", "sp-runtime/std", "sp-session/std", - "sp-std/std", ] runtime-benchmarks = [ diff --git a/substrate/frame/session/benchmarking/src/inner.rs b/substrate/frame/session/benchmarking/src/inner.rs index d86c5d9ad278ea9d914877c63d7a316eebf148c9..9ba47b34ed7a3d57f065884f43be4707340c4b35 100644 --- a/substrate/frame/session/benchmarking/src/inner.rs +++ b/substrate/frame/session/benchmarking/src/inner.rs @@ -18,8 +18,8 @@ //! Benchmarks for the Session Pallet. // This is separated into its own crate due to cyclic dependency issues. +use alloc::{vec, vec::Vec}; use sp_runtime::traits::{One, StaticLookup, TrailingZeroInput}; -use sp_std::{prelude::*, vec}; use codec::Decode; use frame_benchmarking::v1::benchmarks; @@ -152,7 +152,7 @@ fn check_membership_proof_setup( Pallet::::on_initialize(frame_system::pallet_prelude::BlockNumberFor::::one()); // skip sessions until the new validator set is enacted - while Session::::validators().len() < n as usize { + while Validators::::get().len() < n as usize { Session::::rotate_session(); } diff --git a/substrate/frame/session/benchmarking/src/lib.rs b/substrate/frame/session/benchmarking/src/lib.rs index b08955a133297f356a5fa884394b3a88a7e28727..f696546d1f0a0b2934d6b14014c937d9a320be23 100644 --- a/substrate/frame/session/benchmarking/src/lib.rs +++ b/substrate/frame/session/benchmarking/src/lib.rs @@ -19,6 +19,8 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + #[cfg(feature = "runtime-benchmarks")] pub mod inner; diff --git a/substrate/frame/session/src/historical/mod.rs b/substrate/frame/session/src/historical/mod.rs index 618497e3d54db378717561beb47070204af99ab6..fac580b49b3ab6c388e116af07fef1309dd8929e 100644 --- a/substrate/frame/session/src/historical/mod.rs +++ b/substrate/frame/session/src/historical/mod.rs @@ -30,14 +30,15 @@ pub mod offchain; pub mod onchain; mod shared; +use alloc::vec::Vec; use codec::{Decode, Encode}; +use core::fmt::Debug; use sp_runtime::{ traits::{Convert, OpaqueKeys}, KeyTypeId, }; use sp_session::{MembershipProof, ValidatorCount}; use sp_staking::SessionIndex; -use sp_std::{fmt::Debug, prelude::*}; use sp_trie::{ trie_types::{TrieDBBuilder, TrieDBMutBuilderV0}, LayoutV0, MemoryDB, Recorder, StorageProof, Trie, TrieMut, TrieRecorder, @@ -103,7 +104,7 @@ impl Pallet { None => return, // nothing to prune. }; - let up_to = sp_std::cmp::min(up_to, end); + let up_to = core::cmp::min(up_to, end); if up_to < start { return // out of bounds. harmless. @@ -168,7 +169,7 @@ pub trait SessionManager: /// An `SessionManager` implementation that wraps an inner `I` and also /// sets the historical trie root of the ending session. -pub struct NoteHistoricalRoot(sp_std::marker::PhantomData<(T, I)>); +pub struct NoteHistoricalRoot(core::marker::PhantomData<(T, I)>); impl> NoteHistoricalRoot { fn do_new_session(new_index: SessionIndex, is_genesis: bool) -> Option> { @@ -374,6 +375,7 @@ pub(crate) mod tests { use crate::mock::{ force_new_session, set_next_validators, NextValidators, Session, System, Test, }; + use alloc::vec; use sp_runtime::{key_types::DUMMY, testing::UintAuthorityId, BuildStorage}; use sp_state_machine::BasicExternalities; diff --git a/substrate/frame/session/src/historical/offchain.rs b/substrate/frame/session/src/historical/offchain.rs index 95f4d762949eeaa022a998b7d54693189a757c27..685a0be8e191edda97110f9f257b7fba170be5fe 100644 --- a/substrate/frame/session/src/historical/offchain.rs +++ b/substrate/frame/session/src/historical/offchain.rs @@ -23,12 +23,12 @@ //! required data to the offchain validator set. This is used in conjunction with [`ProvingTrie`] //! and the off-chain indexing API. +use alloc::vec::Vec; use sp_runtime::{ offchain::storage::{MutateStorageError, StorageRetrievalError, StorageValueRef}, KeyTypeId, }; use sp_session::MembershipProof; -use sp_std::prelude::*; use super::{shared, Config, IdentificationTuple, ProvingTrie}; use crate::{Pallet as SessionModule, SessionIndex}; @@ -60,9 +60,9 @@ impl ValidatorSet { /// Implement conversion into iterator for usage /// with [ProvingTrie](super::ProvingTrie::generate_for). -impl sp_std::iter::IntoIterator for ValidatorSet { +impl core::iter::IntoIterator for ValidatorSet { type Item = (T::ValidatorId, T::FullIdentification); - type IntoIter = sp_std::vec::IntoIter; + type IntoIter = alloc::vec::IntoIter; fn into_iter(self) -> Self::IntoIter { self.validator_set.into_iter() } diff --git a/substrate/frame/session/src/historical/onchain.rs b/substrate/frame/session/src/historical/onchain.rs index 97a7f02bd096e2ab65d2b0afa2e2004eec56ca8e..a9eb18474b86a68c429afcd1312d331d08b1f164 100644 --- a/substrate/frame/session/src/historical/onchain.rs +++ b/substrate/frame/session/src/historical/onchain.rs @@ -17,9 +17,9 @@ //! On-chain logic to store a validator-set for deferred validation using an off-chain worker. +use alloc::vec::Vec; use codec::Encode; use sp_runtime::traits::Convert; -use sp_std::prelude::*; use super::{shared, Config as HistoricalConfig}; use crate::{Config as SessionConfig, Pallet as SessionModule, SessionIndex}; diff --git a/substrate/frame/session/src/historical/shared.rs b/substrate/frame/session/src/historical/shared.rs index 297385dfb426e5026cae9db478a074070019501d..06b25ec99a4cb62282e87eee1e42e7e87150eeb2 100644 --- a/substrate/frame/session/src/historical/shared.rs +++ b/substrate/frame/session/src/historical/shared.rs @@ -18,9 +18,9 @@ //! Shared logic between on-chain and off-chain components used for slashing using an off-chain //! worker. +use alloc::{borrow::ToOwned, vec::Vec}; use codec::Encode; use sp_staking::SessionIndex; -use sp_std::prelude::*; pub(super) const PREFIX: &[u8] = b"session_historical"; pub(super) const LAST_PRUNE: &[u8] = b"session_historical_last_prune"; diff --git a/substrate/frame/session/src/lib.rs b/substrate/frame/session/src/lib.rs index 9506e98adf7d70004a3caf57adb9c0c1dd44d5f3..e1a2a31911feb1a7765ae4ea034d47feaebefeee 100644 --- a/substrate/frame/session/src/lib.rs +++ b/substrate/frame/session/src/lib.rs @@ -95,7 +95,7 @@ //! use pallet_session as session; //! //! fn validators() -> Vec<::ValidatorId> { -//! >::validators() +//! pallet_session::Validators::::get() //! } //! # fn main(){} //! ``` @@ -115,7 +115,14 @@ mod mock; mod tests; pub mod weights; +extern crate alloc; + +use alloc::{boxed::Box, vec::Vec}; use codec::{Decode, MaxEncodedLen}; +use core::{ + marker::PhantomData, + ops::{Rem, Sub}, +}; use frame_support::{ dispatch::DispatchResult, ensure, @@ -132,11 +139,6 @@ use sp_runtime::{ ConsensusEngineId, DispatchError, KeyTypeId, Permill, RuntimeAppPublic, }; use sp_staking::SessionIndex; -use sp_std::{ - marker::PhantomData, - ops::{Rem, Sub}, - prelude::*, -}; pub use pallet::*; pub use weights::WeightInfo; @@ -445,7 +447,7 @@ pub mod pallet { }); for (account, val, keys) in self.keys.iter().cloned() { - >::inner_set_keys(&val, keys) + Pallet::::inner_set_keys(&val, keys) .expect("genesis config must not contain duplicates; qed"); if frame_system::Pallet::::inc_consumers_without_limit(&account).is_err() { // This will leak a provider reference, however it only happens once (at @@ -477,7 +479,7 @@ pub mod pallet { T::SessionHandler::on_genesis_session::(&queued_keys); Validators::::put(initial_validators_0); - >::put(queued_keys); + QueuedKeys::::put(queued_keys); T::SessionManager::start_session(0); } @@ -485,12 +487,10 @@ pub mod pallet { /// The current set of validators. #[pallet::storage] - #[pallet::getter(fn validators)] pub type Validators = StorageValue<_, Vec, ValueQuery>; /// Current index of the session. #[pallet::storage] - #[pallet::getter(fn current_index)] pub type CurrentIndex = StorageValue<_, SessionIndex, ValueQuery>; /// True if the underlying economic identities or weighting behind the validators @@ -501,7 +501,6 @@ pub mod pallet { /// The queued keys for the next session. When the next session begins, these keys /// will be used to determine the validator's session keys. #[pallet::storage] - #[pallet::getter(fn queued_keys)] pub type QueuedKeys = StorageValue<_, Vec<(T::ValidatorId, T::Keys)>, ValueQuery>; /// Indices of disabled validators. @@ -510,7 +509,6 @@ pub mod pallet { /// disabled using binary search. It gets cleared when `on_session_ending` returns /// a new set of identities. #[pallet::storage] - #[pallet::getter(fn disabled_validators)] pub type DisabledValidators = StorageValue<_, Vec, ValueQuery>; /// The next session keys for a validator. @@ -607,33 +605,53 @@ pub mod pallet { } impl Pallet { + /// Public function to access the current set of validators. + pub fn validators() -> Vec { + Validators::::get() + } + + /// Public function to access the current session index. + pub fn current_index() -> SessionIndex { + CurrentIndex::::get() + } + + /// Public function to access the queued keys. + pub fn queued_keys() -> Vec<(T::ValidatorId, T::Keys)> { + QueuedKeys::::get() + } + + /// Public function to access the disabled validators. + pub fn disabled_validators() -> Vec { + DisabledValidators::::get() + } + /// Move on to next session. Register new validator set and session keys. Changes to the /// validator set have a session of delay to take effect. This allows for equivocation /// punishment after a fork. pub fn rotate_session() { - let session_index = >::get(); + let session_index = CurrentIndex::::get(); log::trace!(target: "runtime::session", "rotating session {:?}", session_index); - let changed = >::get(); + let changed = QueuedChanged::::get(); // Inform the session handlers that a session is going to end. T::SessionHandler::on_before_session_ending(); T::SessionManager::end_session(session_index); // Get queued session keys and validators. - let session_keys = >::get(); + let session_keys = QueuedKeys::::get(); let validators = session_keys.iter().map(|(validator, _)| validator.clone()).collect::>(); Validators::::put(&validators); if changed { // reset disabled validators if active set was changed - >::take(); + DisabledValidators::::take(); } // Increment session index. let session_index = session_index + 1; - >::put(session_index); + CurrentIndex::::put(session_index); T::SessionManager::start_session(session_index); @@ -681,8 +699,8 @@ impl Pallet { (queued_amalgamated, changed) }; - >::put(queued_amalgamated.clone()); - >::put(next_changed); + QueuedKeys::::put(queued_amalgamated.clone()); + QueuedChanged::::put(next_changed); // Record that this happened. Self::deposit_event(Event::NewSession { session_index }); @@ -697,7 +715,7 @@ impl Pallet { return false } - >::mutate(|disabled| { + DisabledValidators::::mutate(|disabled| { if let Err(index) = disabled.binary_search(&i) { disabled.insert(index, i); T::SessionHandler::on_disabled(i); @@ -714,7 +732,7 @@ impl Pallet { /// Returns `false` either if the validator could not be found or it was already /// disabled. pub fn disable(c: &T::ValidatorId) -> bool { - Self::validators() + Validators::::get() .iter() .position(|i| i == c) .map(|i| Self::disable_index(i as u32)) @@ -745,7 +763,7 @@ impl Pallet { let new_ids = T::Keys::key_ids(); // Translate NextKeys, and key ownership relations at the same time. - >::translate::(|val, old_keys| { + NextKeys::::translate::(|val, old_keys| { // Clear all key ownership relations. Typically the overlap should // stay the same, but no guarantees by the upgrade function. for i in old_ids.iter() { @@ -762,7 +780,7 @@ impl Pallet { Some(new_keys) }); - let _ = >::translate::, _>(|k| { + let _ = QueuedKeys::::translate::, _>(|k| { k.map(|k| { k.into_iter() .map(|(val, old_keys)| (val.clone(), upgrade(val, old_keys))) @@ -848,28 +866,28 @@ impl Pallet { } fn load_keys(v: &T::ValidatorId) -> Option { - >::get(v) + NextKeys::::get(v) } fn take_keys(v: &T::ValidatorId) -> Option { - >::take(v) + NextKeys::::take(v) } fn put_keys(v: &T::ValidatorId, keys: &T::Keys) { - >::insert(v, keys); + NextKeys::::insert(v, keys); } /// Query the owner of a session key by returning the owner's validator ID. pub fn key_owner(id: KeyTypeId, key_data: &[u8]) -> Option { - >::get((id, key_data)) + KeyOwner::::get((id, key_data)) } fn put_key_owner(id: KeyTypeId, key_data: &[u8], v: &T::ValidatorId) { - >::insert((id, key_data), v) + KeyOwner::::insert((id, key_data), v) } fn clear_key_owner(id: KeyTypeId, key_data: &[u8]) { - >::remove((id, key_data)); + KeyOwner::::remove((id, key_data)); } } @@ -884,11 +902,11 @@ impl ValidatorSet for Pallet { type ValidatorIdOf = T::ValidatorIdOf; fn session_index() -> sp_staking::SessionIndex { - Pallet::::current_index() + CurrentIndex::::get() } fn validators() -> Vec { - Pallet::::validators() + Validators::::get() } } @@ -906,18 +924,18 @@ impl EstimateNextNewSession> for Pallet { impl frame_support::traits::DisabledValidators for Pallet { fn is_disabled(index: u32) -> bool { - >::disabled_validators().binary_search(&index).is_ok() + DisabledValidators::::get().binary_search(&index).is_ok() } fn disabled_validators() -> Vec { - >::disabled_validators() + DisabledValidators::::get() } } /// Wraps the author-scraping logic for consensus engines that can recover /// the canonical index of an author. This then transforms it into the /// registering account-ID of that session key index. -pub struct FindAccountFromAuthorIndex(sp_std::marker::PhantomData<(T, Inner)>); +pub struct FindAccountFromAuthorIndex(core::marker::PhantomData<(T, Inner)>); impl> FindAuthor for FindAccountFromAuthorIndex @@ -928,7 +946,7 @@ impl> FindAuthor { let i = Inner::find_author(digests)?; - let validators = >::validators(); + let validators = Validators::::get(); validators.get(i as usize).cloned() } } diff --git a/substrate/frame/session/src/tests.rs b/substrate/frame/session/src/tests.rs index 69337e016ea8aa4671c2ccd3cd5f509f43aa9934..f392c2ab7663c73d4b17443d7f9918ca410eceb8 100644 --- a/substrate/frame/session/src/tests.rs +++ b/substrate/frame/session/src/tests.rs @@ -44,7 +44,7 @@ fn initialize_block(block: u64) { fn simple_setup_should_work() { new_test_ext().execute_with(|| { assert_eq!(authorities(), vec![UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(3)]); - assert_eq!(Session::validators(), vec![1, 2, 3]); + assert_eq!(Validators::::get(), vec![1, 2, 3]); }); } @@ -60,7 +60,7 @@ fn put_get_keys() { fn keys_cleared_on_kill() { let mut ext = new_test_ext(); ext.execute_with(|| { - assert_eq!(Session::validators(), vec![1, 2, 3]); + assert_eq!(Validators::::get(), vec![1, 2, 3]); assert_eq!(Session::load_keys(&1), Some(UintAuthorityId(1).into())); let id = DUMMY; @@ -79,7 +79,7 @@ fn keys_cleared_on_kill() { fn purge_keys_works_for_stash_id() { let mut ext = new_test_ext(); ext.execute_with(|| { - assert_eq!(Session::validators(), vec![1, 2, 3]); + assert_eq!(Validators::::get(), vec![1, 2, 3]); TestValidatorIdOf::set(vec![(10, 1), (20, 2), (3, 3)].into_iter().collect()); assert_eq!(Session::load_keys(&1), Some(UintAuthorityId(1).into())); assert_eq!(Session::load_keys(&2), Some(UintAuthorityId(2).into())); @@ -108,10 +108,10 @@ fn authorities_should_track_validators() { force_new_session(); initialize_block(1); assert_eq!( - Session::queued_keys(), + QueuedKeys::::get(), vec![(1, UintAuthorityId(1).into()), (2, UintAuthorityId(2).into()),] ); - assert_eq!(Session::validators(), vec![1, 2, 3]); + assert_eq!(Validators::::get(), vec![1, 2, 3]); assert_eq!(authorities(), vec![UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(3)]); assert!(before_session_end_called()); reset_before_session_end_called(); @@ -119,10 +119,10 @@ fn authorities_should_track_validators() { force_new_session(); initialize_block(2); assert_eq!( - Session::queued_keys(), + QueuedKeys::::get(), vec![(1, UintAuthorityId(1).into()), (2, UintAuthorityId(2).into()),] ); - assert_eq!(Session::validators(), vec![1, 2]); + assert_eq!(Validators::::get(), vec![1, 2]); assert_eq!(authorities(), vec![UintAuthorityId(1), UintAuthorityId(2)]); assert!(before_session_end_called()); reset_before_session_end_called(); @@ -132,28 +132,28 @@ fn authorities_should_track_validators() { force_new_session(); initialize_block(3); assert_eq!( - Session::queued_keys(), + QueuedKeys::::get(), vec![ (1, UintAuthorityId(1).into()), (2, UintAuthorityId(2).into()), (4, UintAuthorityId(4).into()), ] ); - assert_eq!(Session::validators(), vec![1, 2]); + assert_eq!(Validators::::get(), vec![1, 2]); assert_eq!(authorities(), vec![UintAuthorityId(1), UintAuthorityId(2)]); assert!(before_session_end_called()); force_new_session(); initialize_block(4); assert_eq!( - Session::queued_keys(), + QueuedKeys::::get(), vec![ (1, UintAuthorityId(1).into()), (2, UintAuthorityId(2).into()), (4, UintAuthorityId(4).into()), ] ); - assert_eq!(Session::validators(), vec![1, 2, 4]); + assert_eq!(Validators::::get(), vec![1, 2, 4]); assert_eq!(authorities(), vec![UintAuthorityId(1), UintAuthorityId(2), UintAuthorityId(4)]); }); } @@ -164,20 +164,20 @@ fn should_work_with_early_exit() { set_session_length(10); initialize_block(1); - assert_eq!(Session::current_index(), 0); + assert_eq!(CurrentIndex::::get(), 0); initialize_block(2); - assert_eq!(Session::current_index(), 0); + assert_eq!(CurrentIndex::::get(), 0); force_new_session(); initialize_block(3); - assert_eq!(Session::current_index(), 1); + assert_eq!(CurrentIndex::::get(), 1); initialize_block(9); - assert_eq!(Session::current_index(), 1); + assert_eq!(CurrentIndex::::get(), 1); initialize_block(10); - assert_eq!(Session::current_index(), 2); + assert_eq!(CurrentIndex::::get(), 2); }); } @@ -402,7 +402,7 @@ fn upgrade_keys() { // Set `QueuedKeys`. { - let storage_key = >::hashed_key(); + let storage_key = super::QueuedKeys::::hashed_key(); assert!(storage::unhashed::exists(&storage_key)); storage::unhashed::put(&storage_key, &val_keys); } @@ -410,7 +410,7 @@ fn upgrade_keys() { // Set `NextKeys`. { for &(i, ref keys) in val_keys.iter() { - let storage_key = >::hashed_key_for(i); + let storage_key = super::NextKeys::::hashed_key_for(i); assert!(storage::unhashed::exists(&storage_key)); storage::unhashed::put(&storage_key, keys); } @@ -446,12 +446,12 @@ fn upgrade_keys() { // Check queued keys. assert_eq!( - Session::queued_keys(), + QueuedKeys::::get(), vec![(1, mock_keys_for(1)), (2, mock_keys_for(2)), (3, mock_keys_for(3)),], ); for i in 1u64..4 { - assert_eq!(>::get(&i), Some(mock_keys_for(i))); + assert_eq!(super::NextKeys::::get(&i), Some(mock_keys_for(i))); } }) } @@ -466,8 +466,8 @@ fn test_migration_v1() { use frame_support::traits::{PalletInfoAccess, StorageVersion}; new_test_ext().execute_with(|| { - assert!(>::iter_values().count() > 0); - assert!(>::exists()); + assert!(HistoricalSessions::::iter_values().count() > 0); + assert!(StoredRange::::exists()); let old_pallet = "Session"; let new_pallet = ::name(); diff --git a/substrate/frame/society/Cargo.toml b/substrate/frame/society/Cargo.toml index 6582d47f194310250868fb8982685c3098197f33..b6fa70c42efc062291b32c29a322d7bdca36e0ec 100644 --- a/substrate/frame/society/Cargo.toml +++ b/substrate/frame/society/Cargo.toml @@ -21,7 +21,6 @@ rand_chacha = { workspace = true } scale-info = { features = ["derive"], workspace = true } codec = { features = ["derive"], workspace = true } -sp-std = { workspace = true } sp-io = { workspace = true } sp-arithmetic = { workspace = true } sp-runtime = { workspace = true } @@ -52,7 +51,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking", diff --git a/substrate/frame/society/src/benchmarking.rs b/substrate/frame/society/src/benchmarking.rs index 20af6e35ada52136f4ad14459afc0eeb1d19ca45..8c3d2bf32ce73920ff23ad6bf85907f4c89bb220 100644 --- a/substrate/frame/society/src/benchmarking.rs +++ b/substrate/frame/society/src/benchmarking.rs @@ -24,6 +24,7 @@ use super::*; use frame_benchmarking::{account, benchmarks_instance_pallet, whitelisted_caller}; use frame_system::RawOrigin; +use alloc::vec; use sp_runtime::traits::Bounded; use crate::Pallet as Society; diff --git a/substrate/frame/society/src/lib.rs b/substrate/frame/society/src/lib.rs index 5bce245f73f17e02d1301ee9242a356ad291b3ee..b4c5c88af3d6e9abbd66fe51d1b6438d32c43ca3 100644 --- a/substrate/frame/society/src/lib.rs +++ b/substrate/frame/society/src/lib.rs @@ -257,6 +257,9 @@ pub mod weights; pub mod migrations; +extern crate alloc; + +use alloc::vec::Vec; use frame_support::{ impl_ensure_origin_with_arg_ignoring_arg, pallet_prelude::*, @@ -282,7 +285,6 @@ use sp_runtime::{ ArithmeticError::Overflow, Percent, RuntimeDebug, }; -use sp_std::prelude::*; pub use weights::WeightInfo; @@ -1362,7 +1364,7 @@ pub mod pallet { } /// Simple ensure origin struct to filter for the founder account. -pub struct EnsureFounder(sp_std::marker::PhantomData); +pub struct EnsureFounder(core::marker::PhantomData); impl EnsureOrigin<::RuntimeOrigin> for EnsureFounder { type Success = T::AccountId; fn try_origin(o: T::RuntimeOrigin) -> Result { diff --git a/substrate/frame/society/src/migrations.rs b/substrate/frame/society/src/migrations.rs index 7ded1f84f5823696e922a3ef98e4cce45191d21c..396ed787c784c5a73aaccbd90b3df3dcc6cb3b25 100644 --- a/substrate/frame/society/src/migrations.rs +++ b/substrate/frame/society/src/migrations.rs @@ -18,6 +18,7 @@ //! # Migrations for Society Pallet use super::*; +use alloc::{vec, vec::Vec}; use codec::{Decode, Encode}; use frame_support::traits::{Defensive, DefensiveOption, Instance, UncheckedOnRuntimeUpgrade}; diff --git a/substrate/frame/src/lib.rs b/substrate/frame/src/lib.rs index 22befe0375197df1fa199ad241f690d95b7e3a42..9e594f88116fa589c692818dd42b683c866cdcd6 100644 --- a/substrate/frame/src/lib.rs +++ b/substrate/frame/src/lib.rs @@ -132,10 +132,6 @@ pub mod prelude { #[doc(no_inline)] pub use frame_system::pallet_prelude::*; - /// All of the std alternative types. - #[doc(no_inline)] - pub use sp_std::prelude::*; - /// All FRAME-relevant derive macros. #[doc(no_inline)] pub use super::derive::*; @@ -164,7 +160,6 @@ pub mod testing_prelude { pub use frame_system::{self, mocking::*}; pub use sp_io::TestExternalities as TestState; - pub use sp_std::if_std; } /// All of the types and tools needed to build FRAME-based runtimes. @@ -349,13 +344,13 @@ pub mod primitives { /// This is already part of the [`prelude`]. pub mod derive { pub use codec::{Decode, Encode}; + pub use core::fmt::Debug; pub use frame_support::{ CloneNoBound, DebugNoBound, DefaultNoBound, EqNoBound, OrdNoBound, PartialEqNoBound, PartialOrdNoBound, RuntimeDebugNoBound, }; pub use scale_info::TypeInfo; pub use sp_runtime::RuntimeDebug; - pub use sp_std::fmt::Debug; } /// Access to all of the dependencies of this crate. In case the re-exports are not enough, this @@ -375,7 +370,6 @@ pub mod deps { pub use sp_core; pub use sp_io; pub use sp_runtime; - pub use sp_std; pub use codec; pub use scale_info; diff --git a/substrate/frame/staking/Cargo.toml b/substrate/frame/staking/Cargo.toml index afae4652a4ef2ff954d1aa450ebbd453d095adbd..57eeec543634db348164f59fc9f29d090ff70d91 100644 --- a/substrate/frame/staking/Cargo.toml +++ b/substrate/frame/staking/Cargo.toml @@ -24,7 +24,6 @@ scale-info = { features = ["derive", "serde"], workspace = true } sp-io = { workspace = true } sp-runtime = { features = ["serde"], workspace = true } sp-staking = { features = ["serde"], workspace = true } -sp-std = { workspace = true } frame-support = { workspace = true } frame-system = { workspace = true } pallet-session = { features = [ @@ -74,7 +73,6 @@ std = [ "sp-npos-elections/std", "sp-runtime/std", "sp-staking/std", - "sp-std/std", "sp-tracing/std", ] runtime-benchmarks = [ diff --git a/substrate/frame/staking/src/benchmarking.rs b/substrate/frame/staking/src/benchmarking.rs index 3ed33ffea4223847068ded561d9a6a4748843718..1f8580d7a3e67336776517809203a28b0973ebda 100644 --- a/substrate/frame/staking/src/benchmarking.rs +++ b/substrate/frame/staking/src/benchmarking.rs @@ -33,7 +33,6 @@ use sp_runtime::{ Perbill, Percent, Saturating, }; use sp_staking::{currency_to_vote::CurrencyToVote, SessionIndex}; -use sp_std::prelude::*; pub use frame_benchmarking::v1::{ account, benchmarks, impl_benchmark_test_suite, whitelist_account, whitelisted_caller, @@ -169,7 +168,7 @@ impl ListScenario { // burn the entire issuance. let i = T::Currency::burn(T::Currency::total_issuance()); - sp_std::mem::forget(i); + core::mem::forget(i); // create accounts with the origin weight diff --git a/substrate/frame/staking/src/ledger.rs b/substrate/frame/staking/src/ledger.rs index 294918376d82ce5a8473a5353cea0dc5cdd1ba50..dc4b4fc326b819304d719aedbfbefcf3963ec0fd 100644 --- a/substrate/frame/staking/src/ledger.rs +++ b/substrate/frame/staking/src/ledger.rs @@ -36,7 +36,6 @@ use frame_support::{ traits::{Defensive, LockableCurrency}, }; use sp_staking::{StakingAccount, StakingInterface}; -use sp_std::prelude::*; use crate::{ BalanceOf, Bonded, Config, Error, Ledger, Pallet, Payee, RewardDestination, StakingLedger, diff --git a/substrate/frame/staking/src/lib.rs b/substrate/frame/staking/src/lib.rs index 053ecdef2b00b7bb900443153f63e64f51d89252..9e59cbd3d0cb8bc2b2b83c13f07d3951d21c095b 100644 --- a/substrate/frame/staking/src/lib.rs +++ b/substrate/frame/staking/src/lib.rs @@ -304,6 +304,9 @@ pub mod weights; mod pallet; +extern crate alloc; + +use alloc::{collections::btree_map::BTreeMap, vec, vec::Vec}; use codec::{Decode, Encode, HasCompact, MaxEncodedLen}; use frame_support::{ defensive, defensive_assert, @@ -325,7 +328,6 @@ use sp_staking::{ StakingAccount, }; pub use sp_staking::{Exposure, IndividualExposure, StakerStatus}; -use sp_std::{collections::btree_map::BTreeMap, prelude::*}; pub use weights::WeightInfo; pub use pallet::{pallet::*, UseNominatorsAndValidatorsMap, UseValidatorsMap}; @@ -674,7 +676,7 @@ impl StakingLedger { // slightly under-slashed, by at most `MaxUnlockingChunks * ED`, which is not a big // deal. slash_from_target = - sp_std::mem::replace(target, Zero::zero()).saturating_add(slash_from_target) + core::mem::replace(target, Zero::zero()).saturating_add(slash_from_target) } self.total = self.total.saturating_sub(slash_from_target); @@ -916,7 +918,7 @@ impl EraPayout for () { /// Adaptor to turn a `PiecewiseLinear` curve definition into an `EraPayout` impl, used for /// backwards compatibility. -pub struct ConvertCurve(sp_std::marker::PhantomData); +pub struct ConvertCurve(core::marker::PhantomData); impl EraPayout for ConvertCurve where Balance: AtLeast32BitUnsigned + Clone + Copy, @@ -974,7 +976,7 @@ impl Default for Forcing { /// A `Convert` implementation that finds the stash of the given controller account, /// if any. -pub struct StashOf(sp_std::marker::PhantomData); +pub struct StashOf(core::marker::PhantomData); impl Convert> for StashOf { fn convert(controller: T::AccountId) -> Option { @@ -987,7 +989,7 @@ impl Convert> for StashOf { /// /// Active exposure is the exposure of the validator set currently validating, i.e. in /// `active_era`. It can differ from the latest planned exposure in `current_era`. -pub struct ExposureOf(sp_std::marker::PhantomData); +pub struct ExposureOf(core::marker::PhantomData); impl Convert>>> for ExposureOf @@ -1000,7 +1002,7 @@ impl Convert /// Filter historical offences out and only allow those from the bonding period. pub struct FilterHistoricalOffences { - _inner: sp_std::marker::PhantomData<(T, R)>, + _inner: core::marker::PhantomData<(T, R)>, } impl ReportOffence @@ -1033,7 +1035,7 @@ where /// Wrapper struct for Era related information. It is not a pure encapsulation as these storage /// items can be accessed directly but nevertheless, its recommended to use `EraInfo` where we /// can and add more functions to it as needed. -pub struct EraInfo(sp_std::marker::PhantomData); +pub struct EraInfo(core::marker::PhantomData); impl EraInfo { /// Returns true if validator has one or more page of era rewards not claimed yet. // Also looks at legacy storage that can be cleaned up after #433. diff --git a/substrate/frame/staking/src/migrations.rs b/substrate/frame/staking/src/migrations.rs index b2ddf77004f95ecf86df6d177cdb6af454947657..5c9cf861321317aadbef4bc985012dc97d1a8472 100644 --- a/substrate/frame/staking/src/migrations.rs +++ b/substrate/frame/staking/src/migrations.rs @@ -67,7 +67,7 @@ pub mod v15 { // The disabling strategy used by staking pallet type DefaultDisablingStrategy = UpToLimitDisablingStrategy; - pub struct VersionUncheckedMigrateV14ToV15(sp_std::marker::PhantomData); + pub struct VersionUncheckedMigrateV14ToV15(core::marker::PhantomData); impl UncheckedOnRuntimeUpgrade for VersionUncheckedMigrateV14ToV15 { fn on_runtime_upgrade() -> Weight { let mut migrated = v14::OffendingValidators::::take() @@ -382,14 +382,14 @@ pub mod v10 { pub mod v9 { use super::*; #[cfg(feature = "try-runtime")] - use codec::{Decode, Encode}; + use alloc::vec::Vec; #[cfg(feature = "try-runtime")] - use sp_std::vec::Vec; + use codec::{Decode, Encode}; /// Migration implementation that injects all validators into sorted list. /// /// This is only useful for chains that started their `VoterList` just based on nominators. - pub struct InjectValidatorsIntoVoterList(sp_std::marker::PhantomData); + pub struct InjectValidatorsIntoVoterList(core::marker::PhantomData); impl OnRuntimeUpgrade for InjectValidatorsIntoVoterList { fn on_runtime_upgrade() -> Weight { if StorageVersion::::get() == ObsoleteReleases::V8_0_0 { diff --git a/substrate/frame/staking/src/pallet/impls.rs b/substrate/frame/staking/src/pallet/impls.rs index 90374451a3a5266362699e6fc55e957a552ba157..2df3bc084eb0b4f6aef5cbbe665d3f2b66ec80cb 100644 --- a/substrate/frame/staking/src/pallet/impls.rs +++ b/substrate/frame/staking/src/pallet/impls.rs @@ -48,7 +48,6 @@ use sp_staking::{ StakingAccount::{self, Controller, Stash}, StakingInterface, }; -use sp_std::prelude::*; use crate::{ election_size_tracker::StaticTracker, log, slashing, weights::WeightInfo, ActiveEraInfo, @@ -56,6 +55,7 @@ use crate::{ LedgerIntegrityState, MaxNominationsOf, MaxWinnersOf, Nominations, NominationsQuota, PositiveImbalanceOf, RewardDestination, SessionInterface, StakingLedger, ValidatorPrefs, }; +use alloc::{boxed::Box, vec, vec::Vec}; use super::pallet::*; @@ -1584,14 +1584,14 @@ impl ScoreProvider for Pallet { let imbalance = T::Currency::burn(T::Currency::total_issuance()); // kinda ugly, but gets the job done. The fact that this works here is a HUGE exception. // Don't try this pattern in other places. - sp_std::mem::forget(imbalance); + core::mem::forget(imbalance); } } /// A simple sorted list implementation that does not require any additional pallets. Note, this /// does not provide validators in sorted order. If you desire nominators in a sorted order take /// a look at [`pallet-bags-list`]. -pub struct UseValidatorsMap(sp_std::marker::PhantomData); +pub struct UseValidatorsMap(core::marker::PhantomData); impl SortedListProvider for UseValidatorsMap { type Score = BalanceOf; type Error = (); @@ -1657,7 +1657,7 @@ impl SortedListProvider for UseValidatorsMap { /// A simple voter list implementation that does not require any additional pallets. Note, this /// does not provided nominators in sorted ordered. If you desire nominators in a sorted order take /// a look at [`pallet-bags-list]. -pub struct UseNominatorsAndValidatorsMap(sp_std::marker::PhantomData); +pub struct UseNominatorsAndValidatorsMap(core::marker::PhantomData); impl SortedListProvider for UseNominatorsAndValidatorsMap { type Error = (); type Score = VoteWeight; @@ -1779,7 +1779,7 @@ impl StakingInterface for Pallet { .map(|_| ()) } - fn update_payee(stash: &Self::AccountId, reward_acc: &Self::AccountId) -> DispatchResult { + fn set_payee(stash: &Self::AccountId, reward_acc: &Self::AccountId) -> DispatchResult { // Since virtual stakers are not allowed to compound their rewards as this pallet does not // manage their locks, we do not allow reward account to be set same as stash. For // external pallets that manage the virtual bond, they can claim rewards and re-bond them. @@ -1788,12 +1788,12 @@ impl StakingInterface for Pallet { Error::::RewardDestinationRestricted ); - // since controller is deprecated and this function is never used for old ledgers with - // distinct controllers, we can safely assume that stash is the controller. - Self::set_payee( - RawOrigin::Signed(stash.clone()).into(), - RewardDestination::Account(reward_acc.clone()), - ) + let ledger = Self::ledger(Stash(stash.clone()))?; + let _ = ledger + .set_payee(RewardDestination::Account(reward_acc.clone())) + .defensive_proof("ledger was retrieved from storage, thus its bonded; qed.")?; + + Ok(()) } fn chill(who: &Self::AccountId) -> DispatchResult { @@ -1995,7 +1995,7 @@ impl Pallet { /// is resolved, turn warns into check /// failures. fn check_bonded_consistency() -> Result<(), TryRuntimeError> { - use sp_std::collections::btree_set::BTreeSet; + use alloc::collections::btree_set::BTreeSet; let mut count_controller_double = 0; let mut count_double = 0; @@ -2159,8 +2159,8 @@ impl Pallet { /// = exposure.own + exposure.own). /// * Paged exposures metadata (`ErasStakersOverview`) matches the paged exposures state. fn check_paged_exposures() -> Result<(), TryRuntimeError> { + use alloc::collections::btree_map::BTreeMap; use sp_staking::PagedExposureMetadata; - use sp_std::collections::btree_map::BTreeMap; // Sanity check for the paged exposure of the active era. let mut exposures: BTreeMap>> = diff --git a/substrate/frame/staking/src/pallet/mod.rs b/substrate/frame/staking/src/pallet/mod.rs index a76e47edf38039501fe0ac9d3434e13b3fdafe4c..79f9d298ada788ff7ee4278bfb4290eaf44e3c10 100644 --- a/substrate/frame/staking/src/pallet/mod.rs +++ b/substrate/frame/staking/src/pallet/mod.rs @@ -17,6 +17,7 @@ //! Staking FRAME Pallet. +use alloc::vec::Vec; use codec::Codec; use frame_election_provider_support::{ ElectionProvider, ElectionProviderBase, SortedListProvider, VoteWeight, @@ -41,7 +42,6 @@ use sp_staking::{ StakingAccount::{self, Controller, Stash}, StakingInterface, }; -use sp_std::prelude::*; mod impls; @@ -101,7 +101,7 @@ pub mod pallet { + codec::FullCodec + Copy + MaybeSerializeDeserialize - + sp_std::fmt::Debug + + core::fmt::Debug + Default + From + TypeInfo diff --git a/substrate/frame/staking/src/slashing.rs b/substrate/frame/staking/src/slashing.rs index 1fe608cd3358bb8d7ab113ee96d720df4998c759..9bc8197c50b3ec29f8a308128383ce50dba95a77 100644 --- a/substrate/frame/staking/src/slashing.rs +++ b/substrate/frame/staking/src/slashing.rs @@ -54,6 +54,7 @@ use crate::{ NominatorSlashInEra, Pallet, Perbill, SessionInterface, SpanSlash, UnappliedSlash, ValidatorSlashInEra, }; +use alloc::vec::Vec; use codec::{Decode, Encode, MaxEncodedLen}; use frame_support::{ ensure, @@ -65,7 +66,6 @@ use sp_runtime::{ DispatchResult, RuntimeDebug, }; use sp_staking::{EraIndex, StakingInterface}; -use sp_std::vec::Vec; /// The proportion of the slashing reward to be paid out on the first slashing detection. /// This is f_1 in the paper. @@ -148,7 +148,7 @@ impl SlashingSpans { SlashingSpan { index, start, length: Some(length) } }); - sp_std::iter::once(last).chain(prior) + core::iter::once(last).chain(prior) } /// Yields the era index where the most recent non-zero slash occurred. @@ -182,7 +182,7 @@ impl SlashingSpans { }; // readjust the ongoing span, if it started before the beginning of the window. - self.last_start = sp_std::cmp::max(self.last_start, window_start); + self.last_start = core::cmp::max(self.last_start, window_start); pruned } } @@ -408,7 +408,7 @@ struct InspectingSpans<'a, T: Config + 'a> { paid_out: &'a mut BalanceOf, slash_of: &'a mut BalanceOf, reward_proportion: Perbill, - _marker: sp_std::marker::PhantomData, + _marker: core::marker::PhantomData, } // fetches the slashing spans record for a stash account, initializing it if necessary. @@ -433,7 +433,7 @@ fn fetch_spans<'a, T: Config + 'a>( slash_of, paid_out, reward_proportion, - _marker: sp_std::marker::PhantomData, + _marker: core::marker::PhantomData, } } @@ -451,7 +451,7 @@ impl<'a, T: 'a + Config> InspectingSpans<'a, T> { // although `amount` may be zero, as it is only a difference. fn add_slash(&mut self, amount: BalanceOf, slash_era: EraIndex) { *self.slash_of += amount; - self.spans.last_nonzero_slash = sp_std::cmp::max(self.spans.last_nonzero_slash, slash_era); + self.spans.last_nonzero_slash = core::cmp::max(self.spans.last_nonzero_slash, slash_era); } // find the span index of the given era, if covered. diff --git a/substrate/frame/staking/src/testing_utils.rs b/substrate/frame/staking/src/testing_utils.rs index d4938ea43ebe2800b3894a21e17f93e45d591ff5..65aaa5f09de4e8476f961574946f9dcb1f4f4d8d 100644 --- a/substrate/frame/staking/src/testing_utils.rs +++ b/substrate/frame/staking/src/testing_utils.rs @@ -30,7 +30,6 @@ use sp_io::hashing::blake2_256; use frame_election_provider_support::SortedListProvider; use frame_support::{pallet_prelude::*, traits::Currency}; use sp_runtime::{traits::StaticLookup, Perbill}; -use sp_std::prelude::*; const SEED: u32 = 0; diff --git a/substrate/frame/staking/src/tests.rs b/substrate/frame/staking/src/tests.rs index 825b03b8ecaac159e1332a2e73eb5441601f0bf2..0b6aad4a1b0823a7abf7799791b0a0c4b45fc636 100644 --- a/substrate/frame/staking/src/tests.rs +++ b/substrate/frame/staking/src/tests.rs @@ -41,7 +41,6 @@ use sp_staking::{ offence::{OffenceDetails, OnOffenceHandler}, SessionIndex, }; -use sp_std::prelude::*; use substrate_test_utils::assert_eq_uvec; #[test] @@ -7158,7 +7157,7 @@ mod staking_unchecked { // cannot set via set_payee as well. assert_noop!( - ::update_payee(&10, &10), + ::set_payee(&10, &10), Error::::RewardDestinationRestricted ); }); @@ -7220,7 +7219,7 @@ mod staking_unchecked { // migrate them to virtual staker ::migrate_to_virtual_staker(&200); // payee needs to be updated to a non-stash account. - assert_ok!(::update_payee(&200, &201)); + assert_ok!(::set_payee(&200, &201)); // ensure the balance is not locked anymore assert_eq!(Balances::balance_locked(crate::STAKING_ID, &200), 0); @@ -7247,7 +7246,7 @@ mod staking_unchecked { // make 101 a virtual nominator ::migrate_to_virtual_staker(&101); // set payee different to self. - assert_ok!(::update_payee(&101, &102)); + assert_ok!(::set_payee(&101, &102)); // cache values let nominator_stake = Staking::ledger(101.into()).unwrap().active; @@ -7322,7 +7321,7 @@ mod staking_unchecked { // make 101 a virtual nominator ::migrate_to_virtual_staker(&101); // set payee different to self. - assert_ok!(::update_payee(&101, &102)); + assert_ok!(::set_payee(&101, &102)); // cache values let validator_balance = Balances::free_balance(&11); diff --git a/substrate/frame/state-trie-migration/Cargo.toml b/substrate/frame/state-trie-migration/Cargo.toml index 8bb4079715e2a99298239160f04d3bc967633c8c..db8d10dabfdef3cf1d7a69c01bdc05d3885b20df 100644 --- a/substrate/frame/state-trie-migration/Cargo.toml +++ b/substrate/frame/state-trie-migration/Cargo.toml @@ -28,7 +28,6 @@ remote-externalities = { optional = true, workspace = true, default-features = t sp-core = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } substrate-state-trie-migration-rpc = { optional = true, workspace = true, default-features = true } [dev-dependencies] @@ -50,7 +49,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", "sp-tracing/std", ] runtime-benchmarks = [ diff --git a/substrate/frame/state-trie-migration/src/lib.rs b/substrate/frame/state-trie-migration/src/lib.rs index 22ad640d3bd23d96c43d764dfaadddc3a5b687f3..3fe5abb81031345904b38d1a006a5fa208fb4a84 100644 --- a/substrate/frame/state-trie-migration/src/lib.rs +++ b/substrate/frame/state-trie-migration/src/lib.rs @@ -55,6 +55,8 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + pub use pallet::*; pub mod weights; @@ -75,6 +77,8 @@ pub mod pallet { pub use crate::weights::WeightInfo; + use alloc::{vec, vec::Vec}; + use core::ops::Deref; use frame_support::{ dispatch::{DispatchErrorWithPostInfo, PostDispatchInfo}, ensure, @@ -93,7 +97,6 @@ pub mod pallet { self, traits::{Saturating, Zero}, }; - use sp_std::{ops::Deref, prelude::*}; pub(crate) type BalanceOf = <::Currency as Inspect<::AccountId>>::Balance; @@ -169,11 +172,11 @@ pub mod pallet { pub(crate) child_items: u32, #[codec(skip)] - pub(crate) _ph: sp_std::marker::PhantomData, + pub(crate) _ph: core::marker::PhantomData, } - impl> sp_std::fmt::Debug for Progress { - fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { + impl> core::fmt::Debug for Progress { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { Progress::ToStart => f.write_str("To start"), Progress::LastKey(key) => write!(f, "Last: {:?}", HexDisplay::from(key.deref())), @@ -182,8 +185,8 @@ pub mod pallet { } } - impl sp_std::fmt::Debug for MigrationTask { - fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { + impl core::fmt::Debug for MigrationTask { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { f.debug_struct("MigrationTask") .field("top", &self.progress_top) .field("child", &self.progress_child) @@ -953,8 +956,8 @@ pub mod pallet { #[cfg(feature = "runtime-benchmarks")] mod benchmarks { use super::{pallet::Pallet as StateTrieMigration, *}; + use alloc::vec; use frame_support::traits::fungible::{Inspect, Mutate}; - use sp_std::prelude::*; // The size of the key seemingly makes no difference in the read/write time, so we make it // constant. @@ -1080,7 +1083,7 @@ mod benchmarks { process_top_key { let v in 1 .. (4 * 1024 * 1024); - let value = sp_std::vec![1u8; v as usize]; + let value = alloc::vec![1u8; v as usize]; sp_io::storage::set(KEY, &value); }: { let data = sp_io::storage::get(KEY).unwrap(); @@ -1101,6 +1104,7 @@ mod benchmarks { mod mock { use super::*; use crate as pallet_state_trie_migration; + use alloc::{vec, vec::Vec}; use frame_support::{derive_impl, parameter_types, traits::Hooks, weights::Weight}; use frame_system::{EnsureRoot, EnsureSigned}; use sp_core::{ diff --git a/substrate/frame/statement/Cargo.toml b/substrate/frame/statement/Cargo.toml index 233b7255fc5dbc0e617c53c427252431052cf891..000e5033d8f1979f81ffc71f99ada7adc1bef55d 100644 --- a/substrate/frame/statement/Cargo.toml +++ b/substrate/frame/statement/Cargo.toml @@ -22,7 +22,6 @@ frame-system = { workspace = true } sp-statement-store = { workspace = true } sp-api = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } sp-io = { workspace = true } sp-core = { workspace = true } log = { workspace = true } @@ -44,7 +43,6 @@ std = [ "sp-io/std", "sp-runtime/std", "sp-statement-store/std", - "sp-std/std", ] try-runtime = [ "frame-support/try-runtime", diff --git a/substrate/frame/statement/src/lib.rs b/substrate/frame/statement/src/lib.rs index c68dac2d297227f337d765c1cb3a361ad0a36322..6a7f577ab0869cbf5762ad2d8edd4e015a9b8242 100644 --- a/substrate/frame/statement/src/lib.rs +++ b/substrate/frame/statement/src/lib.rs @@ -92,7 +92,7 @@ pub mod pallet { } #[pallet::pallet] - pub struct Pallet(sp_std::marker::PhantomData); + pub struct Pallet(core::marker::PhantomData); #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] diff --git a/substrate/frame/sudo/Cargo.toml b/substrate/frame/sudo/Cargo.toml index 5d5d09d692342746557c3a80190ff6257de37a53..1a94753728b248dbce2a5448adf1ed3647b9c312 100644 --- a/substrate/frame/sudo/Cargo.toml +++ b/substrate/frame/sudo/Cargo.toml @@ -23,7 +23,6 @@ frame-support = { workspace = true } frame-system = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } docify = { workspace = true } @@ -41,7 +40,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/sudo/src/benchmarking.rs b/substrate/frame/sudo/src/benchmarking.rs index e64233fe7480a9d82c9c07709dd9b403544bff6a..dee7d09c9d0c63426fb70fbc45188034d48bae38 100644 --- a/substrate/frame/sudo/src/benchmarking.rs +++ b/substrate/frame/sudo/src/benchmarking.rs @@ -19,6 +19,7 @@ use super::*; use crate::Pallet; +use alloc::{boxed::Box, vec}; use frame_benchmarking::v2::*; use frame_system::RawOrigin; diff --git a/substrate/frame/sudo/src/extension.rs b/substrate/frame/sudo/src/extension.rs index e90286e5a7c6bae73794bae7efd5fda4a496bb25..fb7eaf7894806bf816be381c430da95378078961 100644 --- a/substrate/frame/sudo/src/extension.rs +++ b/substrate/frame/sudo/src/extension.rs @@ -17,6 +17,7 @@ use crate::{Config, Key}; use codec::{Decode, Encode}; +use core::{fmt, marker::PhantomData}; use frame_support::{dispatch::DispatchInfo, ensure}; use scale_info::TypeInfo; use sp_runtime::{ @@ -26,7 +27,6 @@ use sp_runtime::{ UnknownTransaction, ValidTransaction, }, }; -use sp_std::{fmt, marker::PhantomData}; /// Ensure that signed transactions are only valid if they are signed by sudo account. /// diff --git a/substrate/frame/sudo/src/lib.rs b/substrate/frame/sudo/src/lib.rs index 63b68e694307ecb4ee3986118f780df1ae49f609..07296e90b64859975f164d75cfc056ab63b0c860 100644 --- a/substrate/frame/sudo/src/lib.rs +++ b/substrate/frame/sudo/src/lib.rs @@ -121,8 +121,11 @@ #![deny(missing_docs)] #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + +use alloc::boxed::Box; + use sp_runtime::{traits::StaticLookup, DispatchResult}; -use sp_std::prelude::*; use frame_support::{dispatch::GetDispatchInfo, traits::UnfilteredDispatchable}; diff --git a/substrate/frame/support/procedural/src/construct_runtime/expand/inherent.rs b/substrate/frame/support/procedural/src/construct_runtime/expand/inherent.rs index da483fa6cf0b6aaa724792f724482e88027fa696..c5fe8440d21bebc68347c0d09dab313628e0ccbf 100644 --- a/substrate/frame/support/procedural/src/construct_runtime/expand/inherent.rs +++ b/substrate/frame/support/procedural/src/construct_runtime/expand/inherent.rs @@ -58,17 +58,17 @@ pub fn expand_outer_inherent( trait InherentDataExt { fn create_extrinsics(&self) -> - #scrate::__private::sp_std::vec::Vec<<#block as #scrate::sp_runtime::traits::Block>::Extrinsic>; + #scrate::__private::Vec<<#block as #scrate::sp_runtime::traits::Block>::Extrinsic>; fn check_extrinsics(&self, block: &#block) -> #scrate::inherent::CheckInherentsResult; } impl InherentDataExt for #scrate::inherent::InherentData { fn create_extrinsics(&self) -> - #scrate::__private::sp_std::vec::Vec<<#block as #scrate::sp_runtime::traits::Block>::Extrinsic> + #scrate::__private::Vec<<#block as #scrate::sp_runtime::traits::Block>::Extrinsic> { use #scrate::inherent::ProvideInherent; - let mut inherents = #scrate::__private::sp_std::vec::Vec::new(); + let mut inherents = #scrate::__private::Vec::new(); #( #pallet_attrs diff --git a/substrate/frame/support/procedural/src/construct_runtime/expand/metadata.rs b/substrate/frame/support/procedural/src/construct_runtime/expand/metadata.rs index 0e76f9a92469a73d3a616da454dc46ded5034afc..daef1b171617fbbd87ea13fc73989bd4b01738a2 100644 --- a/substrate/frame/support/procedural/src/construct_runtime/expand/metadata.rs +++ b/substrate/frame/support/procedural/src/construct_runtime/expand/metadata.rs @@ -111,7 +111,7 @@ pub fn expand_runtime_metadata( >(); #scrate::__private::metadata_ir::MetadataIR { - pallets: #scrate::__private::sp_std::vec![ #(#pallets),* ], + pallets: #scrate::__private::vec![ #(#pallets),* ], extrinsic: #scrate::__private::metadata_ir::ExtrinsicMetadataIR { ty, version: <#extrinsic as #scrate::sp_runtime::traits::ExtrinsicMetadata>::VERSION, @@ -156,7 +156,7 @@ pub fn expand_runtime_metadata( }) } - pub fn metadata_versions() -> #scrate::__private::sp_std::vec::Vec { + pub fn metadata_versions() -> #scrate::__private::Vec { #scrate::__private::metadata_ir::supported_versions() } } diff --git a/substrate/frame/support/procedural/src/construct_runtime/expand/origin.rs b/substrate/frame/support/procedural/src/construct_runtime/expand/origin.rs index 83049919d01c34f05ce7be6725ab8bc60731f47b..4a14853c04eec327ddcdf403819301cb58f71d39 100644 --- a/substrate/frame/support/procedural/src/construct_runtime/expand/origin.rs +++ b/substrate/frame/support/procedural/src/construct_runtime/expand/origin.rs @@ -105,25 +105,25 @@ pub fn expand_outer_origin( #[derive(Clone)] pub struct RuntimeOrigin { pub caller: OriginCaller, - filter: #scrate::__private::sp_std::rc::Rc::RuntimeCall) -> bool>>, + filter: #scrate::__private::Rc<#scrate::__private::Box::RuntimeCall) -> bool>>, } #[cfg(not(feature = "std"))] - impl #scrate::__private::sp_std::fmt::Debug for RuntimeOrigin { + impl core::fmt::Debug for RuntimeOrigin { fn fmt( &self, - fmt: &mut #scrate::__private::sp_std::fmt::Formatter, - ) -> #scrate::__private::sp_std::result::Result<(), #scrate::__private::sp_std::fmt::Error> { + fmt: &mut core::fmt::Formatter, + ) -> core::result::Result<(), core::fmt::Error> { fmt.write_str("") } } #[cfg(feature = "std")] - impl #scrate::__private::sp_std::fmt::Debug for RuntimeOrigin { + impl core::fmt::Debug for RuntimeOrigin { fn fmt( &self, - fmt: &mut #scrate::__private::sp_std::fmt::Formatter, - ) -> #scrate::__private::sp_std::result::Result<(), #scrate::__private::sp_std::fmt::Error> { + fmt: &mut core::fmt::Formatter, + ) -> core::result::Result<(), core::fmt::Error> { fmt.debug_struct("Origin") .field("caller", &self.caller) .field("filter", &"[function ptr]") @@ -139,7 +139,7 @@ pub fn expand_outer_origin( fn add_filter(&mut self, filter: impl Fn(&Self::Call) -> bool + 'static) { let f = self.filter.clone(); - self.filter = #scrate::__private::sp_std::rc::Rc::new(Box::new(move |call| { + self.filter = #scrate::__private::Rc::new(#scrate::__private::Box::new(move |call| { f(call) && filter(call) })); } @@ -150,7 +150,7 @@ pub fn expand_outer_origin( as #scrate::traits::Contains<<#runtime as #system_path::Config>::RuntimeCall> >::contains; - self.filter = #scrate::__private::sp_std::rc::Rc::new(Box::new(filter)); + self.filter = #scrate::__private::Rc::new(#scrate::__private::Box::new(filter)); } fn set_caller_from(&mut self, other: impl Into) { @@ -252,7 +252,7 @@ pub fn expand_outer_origin( impl TryFrom for #system_path::Origin<#runtime> { type Error = OriginCaller; fn try_from(x: OriginCaller) - -> #scrate::__private::sp_std::result::Result<#system_path::Origin<#runtime>, OriginCaller> + -> core::result::Result<#system_path::Origin<#runtime>, OriginCaller> { if let OriginCaller::system(l) = x { Ok(l) @@ -275,7 +275,7 @@ pub fn expand_outer_origin( fn from(x: OriginCaller) -> Self { let mut o = RuntimeOrigin { caller: x, - filter: #scrate::__private::sp_std::rc::Rc::new(Box::new(|_| true)), + filter: #scrate::__private::Rc::new(#scrate::__private::Box::new(|_| true)), }; #scrate::traits::OriginTrait::reset_filter(&mut o); @@ -284,7 +284,7 @@ pub fn expand_outer_origin( } } - impl From for #scrate::__private::sp_std::result::Result<#system_path::Origin<#runtime>, RuntimeOrigin> { + impl From for core::result::Result<#system_path::Origin<#runtime>, RuntimeOrigin> { /// NOTE: converting to pallet origin loses the origin filter information. fn from(val: RuntimeOrigin) -> Self { if let OriginCaller::system(l) = val.caller { @@ -349,7 +349,7 @@ fn expand_origin_caller_variant( } fn expand_origin_pallet_conversions( - scrate: &TokenStream, + _scrate: &TokenStream, runtime: &Ident, pallet: &Pallet, instance: Option<&Ident>, @@ -394,7 +394,7 @@ fn expand_origin_pallet_conversions( } #attr - impl From for #scrate::__private::sp_std::result::Result<#pallet_origin, RuntimeOrigin> { + impl From for core::result::Result<#pallet_origin, RuntimeOrigin> { /// NOTE: converting to pallet origin loses the origin filter information. fn from(val: RuntimeOrigin) -> Self { if let OriginCaller::#variant_name(l) = val.caller { @@ -410,7 +410,7 @@ fn expand_origin_pallet_conversions( type Error = OriginCaller; fn try_from( x: OriginCaller, - ) -> #scrate::__private::sp_std::result::Result<#pallet_origin, OriginCaller> { + ) -> core::result::Result<#pallet_origin, OriginCaller> { if let OriginCaller::#variant_name(l) = x { Ok(l) } else { @@ -424,7 +424,7 @@ fn expand_origin_pallet_conversions( type Error = (); fn try_from( x: &'a OriginCaller, - ) -> #scrate::__private::sp_std::result::Result<&'a #pallet_origin, ()> { + ) -> core::result::Result<&'a #pallet_origin, ()> { if let OriginCaller::#variant_name(l) = x { Ok(&l) } else { @@ -438,7 +438,7 @@ fn expand_origin_pallet_conversions( type Error = (); fn try_from( x: &'a RuntimeOrigin, - ) -> #scrate::__private::sp_std::result::Result<&'a #pallet_origin, ()> { + ) -> core::result::Result<&'a #pallet_origin, ()> { if let OriginCaller::#variant_name(l) = &x.caller { Ok(&l) } else { diff --git a/substrate/frame/support/procedural/src/construct_runtime/mod.rs b/substrate/frame/support/procedural/src/construct_runtime/mod.rs index 1505d158895f0fa172884eef6aa748f44734e042..17042c2487803eb102ac1c4db4470b9ee232d766 100644 --- a/substrate/frame/support/procedural/src/construct_runtime/mod.rs +++ b/substrate/frame/support/procedural/src/construct_runtime/mod.rs @@ -470,7 +470,7 @@ fn construct_runtime_final_expansion( #[doc(hidden)] trait InternalConstructRuntime { #[inline(always)] - fn runtime_metadata(&self) -> #scrate::__private::sp_std::vec::Vec<#scrate::__private::metadata_ir::RuntimeApiMetadataIR> { + fn runtime_metadata(&self) -> #scrate::__private::Vec<#scrate::__private::metadata_ir::RuntimeApiMetadataIR> { Default::default() } } @@ -669,10 +669,10 @@ pub(crate) fn decl_pallet_runtime_setup( impl #scrate::traits::PalletInfo for PalletInfo { fn index() -> Option { - let type_id = #scrate::__private::sp_std::any::TypeId::of::

(); + let type_id = core::any::TypeId::of::

(); #( #pallet_attrs - if type_id == #scrate::__private::sp_std::any::TypeId::of::<#names>() { + if type_id == core::any::TypeId::of::<#names>() { return Some(#indices) } )* @@ -681,10 +681,10 @@ pub(crate) fn decl_pallet_runtime_setup( } fn name() -> Option<&'static str> { - let type_id = #scrate::__private::sp_std::any::TypeId::of::

(); + let type_id = core::any::TypeId::of::

(); #( #pallet_attrs - if type_id == #scrate::__private::sp_std::any::TypeId::of::<#names>() { + if type_id == core::any::TypeId::of::<#names>() { return Some(#name_strings) } )* @@ -693,10 +693,10 @@ pub(crate) fn decl_pallet_runtime_setup( } fn name_hash() -> Option<[u8; 16]> { - let type_id = #scrate::__private::sp_std::any::TypeId::of::

(); + let type_id = core::any::TypeId::of::

(); #( #pallet_attrs - if type_id == #scrate::__private::sp_std::any::TypeId::of::<#names>() { + if type_id == core::any::TypeId::of::<#names>() { return Some(#name_hashes) } )* @@ -705,10 +705,10 @@ pub(crate) fn decl_pallet_runtime_setup( } fn module_name() -> Option<&'static str> { - let type_id = #scrate::__private::sp_std::any::TypeId::of::

(); + let type_id = core::any::TypeId::of::

(); #( #pallet_attrs - if type_id == #scrate::__private::sp_std::any::TypeId::of::<#names>() { + if type_id == core::any::TypeId::of::<#names>() { return Some(#module_names) } )* @@ -717,10 +717,10 @@ pub(crate) fn decl_pallet_runtime_setup( } fn crate_version() -> Option<#scrate::traits::CrateVersion> { - let type_id = #scrate::__private::sp_std::any::TypeId::of::

(); + let type_id = core::any::TypeId::of::

(); #( #pallet_attrs - if type_id == #scrate::__private::sp_std::any::TypeId::of::<#names>() { + if type_id == core::any::TypeId::of::<#names>() { return Some( <#pallet_structs as #scrate::traits::PalletInfoAccess>::crate_version() ) diff --git a/substrate/frame/support/procedural/src/pallet/expand/constants.rs b/substrate/frame/support/procedural/src/pallet/expand/constants.rs index d7fbb5a718973c9d2a9ed9f32ab384536265f3d6..a36df790bd2987ba422d04fa4d36d3b74dcc5c76 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/constants.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/constants.rs @@ -88,7 +88,7 @@ pub fn expand_constants(def: &mut Def) -> proc_macro2::TokenStream { name: #ident_str, ty: #frame_support::__private::scale_info::meta_type::<#const_type>(), value: { #default_byte_impl }, - docs: #frame_support::__private::sp_std::vec![ #( #doc ),* ], + docs: #frame_support::__private::vec![ #( #doc ),* ], } }) }); @@ -98,9 +98,9 @@ pub fn expand_constants(def: &mut Def) -> proc_macro2::TokenStream { #[doc(hidden)] pub fn pallet_constants_metadata() - -> #frame_support::__private::sp_std::vec::Vec<#frame_support::__private::metadata_ir::PalletConstantMetadataIR> + -> #frame_support::__private::Vec<#frame_support::__private::metadata_ir::PalletConstantMetadataIR> { - #frame_support::__private::sp_std::vec![ #( #consts ),* ] + #frame_support::__private::vec![ #( #consts ),* ] } } ) diff --git a/substrate/frame/support/procedural/src/pallet/expand/documentation.rs b/substrate/frame/support/procedural/src/pallet/expand/documentation.rs index ec19f889a9f20a57e5b0096f9873623baa06d59f..e2c72ee921c4609875ed1300cf345f32f9c44ec8 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/documentation.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/documentation.rs @@ -163,9 +163,9 @@ pub fn expand_documentation(def: &mut Def) -> proc_macro2::TokenStream { #[doc(hidden)] pub fn pallet_documentation_metadata() - -> #frame_support::__private::sp_std::vec::Vec<&'static str> + -> #frame_support::__private::Vec<&'static str> { - #frame_support::__private::sp_std::vec![ #( #docs ),* ] + #frame_support::__private::vec![ #( #docs ),* ] } } ) diff --git a/substrate/frame/support/procedural/src/pallet/expand/error.rs b/substrate/frame/support/procedural/src/pallet/expand/error.rs index b921d66ff9e73895fef8e1e0985fc205446b60e8..05478ee3908416f4fe67ac142428f7dd1c039bf6 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/error.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/error.rs @@ -66,7 +66,7 @@ pub fn expand_error(def: &mut Def) -> proc_macro2::TokenStream { #[doc(hidden)] #[codec(skip)] __Ignore( - #frame_support::__private::sp_std::marker::PhantomData<(#type_use_gen)>, + core::marker::PhantomData<(#type_use_gen)>, #frame_support::Never, ) ); @@ -124,11 +124,11 @@ pub fn expand_error(def: &mut Def) -> proc_macro2::TokenStream { } quote::quote_spanned!(error.attr_span => - impl<#type_impl_gen> #frame_support::__private::sp_std::fmt::Debug for #error_ident<#type_use_gen> + impl<#type_impl_gen> core::fmt::Debug for #error_ident<#type_use_gen> #config_where_clause { - fn fmt(&self, f: &mut #frame_support::__private::sp_std::fmt::Formatter<'_>) - -> #frame_support::__private::sp_std::fmt::Result + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) + -> core::fmt::Result { f.write_str(self.as_str()) } diff --git a/substrate/frame/support/procedural/src/pallet/expand/hooks.rs b/substrate/frame/support/procedural/src/pallet/expand/hooks.rs index 3623b595268d081ee7b5750a5431f208383f8517..d7b1ca14f574b4aa9fd9ca49bab576c582e72b74 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/hooks.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/hooks.rs @@ -255,7 +255,7 @@ pub fn expand_hooks(def: &mut Def) -> proc_macro2::TokenStream { } #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result<#frame_support::__private::sp_std::vec::Vec, #frame_support::sp_runtime::TryRuntimeError> { + fn pre_upgrade() -> Result<#frame_support::__private::Vec, #frame_support::sp_runtime::TryRuntimeError> { < Self as @@ -264,7 +264,7 @@ pub fn expand_hooks(def: &mut Def) -> proc_macro2::TokenStream { } #[cfg(feature = "try-runtime")] - fn post_upgrade(state: #frame_support::__private::sp_std::vec::Vec) -> Result<(), #frame_support::sp_runtime::TryRuntimeError> { + fn post_upgrade(state: #frame_support::__private::Vec) -> Result<(), #frame_support::sp_runtime::TryRuntimeError> { #post_storage_version_check < diff --git a/substrate/frame/support/procedural/src/pallet/expand/pallet_struct.rs b/substrate/frame/support/procedural/src/pallet/expand/pallet_struct.rs index 7cdf6bde9de87d0bd4eed70de93173bc9bf4e3ff..7ebc4bb2e9dc28c825a91e99b4feaf3ed6e0bcd8 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/pallet_struct.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/pallet_struct.rs @@ -54,7 +54,7 @@ pub fn expand_pallet_struct(def: &mut Def) -> proc_macro2::TokenStream { if let Some(field) = pallet_item.fields.iter_mut().next() { if field.ty == syn::parse_quote!(_) { field.ty = syn::parse_quote!( - #frame_support::__private::sp_std::marker::PhantomData<(#type_use_gen)> + core::marker::PhantomData<(#type_use_gen)> ); } } @@ -139,10 +139,10 @@ pub fn expand_pallet_struct(def: &mut Def) -> proc_macro2::TokenStream { #storages_where_clauses { fn storage_info() - -> #frame_support::__private::sp_std::vec::Vec<#frame_support::traits::StorageInfo> + -> #frame_support::__private::Vec<#frame_support::traits::StorageInfo> { #[allow(unused_mut)] - let mut res = #frame_support::__private::sp_std::vec![]; + let mut res = #frame_support::__private::vec![]; #( #(#storage_cfg_attrs)* @@ -179,8 +179,8 @@ pub fn expand_pallet_struct(def: &mut Def) -> proc_macro2::TokenStream { let whitelisted_storage_keys_impl = quote::quote![ use #frame_support::traits::{StorageInfoTrait, TrackedStorageKey, WhitelistedStorageKeys}; impl<#type_impl_gen> WhitelistedStorageKeys for #pallet_ident<#type_use_gen> #storages_where_clauses { - fn whitelisted_storage_keys() -> #frame_support::__private::sp_std::vec::Vec { - use #frame_support::__private::sp_std::vec; + fn whitelisted_storage_keys() -> #frame_support::__private::Vec { + use #frame_support::__private::vec; vec![#( TrackedStorageKey::new(#whitelisted_storage_idents::<#type_use_gen>::hashed_key().to_vec()) ),*] @@ -272,7 +272,7 @@ pub fn expand_pallet_struct(def: &mut Def) -> proc_macro2::TokenStream { #config_where_clause { fn count() -> usize { 1 } - fn infos() -> #frame_support::__private::sp_std::vec::Vec<#frame_support::traits::PalletInfoData> { + fn infos() -> #frame_support::__private::Vec<#frame_support::traits::PalletInfoData> { use #frame_support::traits::PalletInfoAccess; let item = #frame_support::traits::PalletInfoData { index: Self::index(), @@ -280,7 +280,7 @@ pub fn expand_pallet_struct(def: &mut Def) -> proc_macro2::TokenStream { module_name: Self::module_name(), crate_version: Self::crate_version(), }; - #frame_support::__private::sp_std::vec![item] + #frame_support::__private::vec![item] } } diff --git a/substrate/frame/support/procedural/src/pallet/expand/storage.rs b/substrate/frame/support/procedural/src/pallet/expand/storage.rs index 3cc8a843e3b1669aa054040a49101ee4ae8d3f5f..267b0f2dd3ba43960fd4711e3feb0bc245a04587 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/storage.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/storage.rs @@ -423,7 +423,7 @@ pub fn expand_storages(def: &mut Def) -> proc_macro2::TokenStream { #(#cfg_attrs)* { <#full_ident as #frame_support::storage::StorageEntryMetadataBuilder>::build_metadata( - #frame_support::__private::sp_std::vec![ + #frame_support::__private::vec![ #( #docs, )* ], &mut entries, @@ -853,7 +853,7 @@ pub fn expand_storages(def: &mut Def) -> proc_macro2::TokenStream { impl<#type_impl_gen> #frame_support::traits::TryDecodeEntireStorage for #pallet_ident<#type_use_gen> #completed_where_clause { - fn try_decode_entire_state() -> Result> { + fn try_decode_entire_state() -> Result> { let pallet_name = <::PalletInfo as #frame_support::traits::PalletInfo> ::name::<#pallet_ident<#type_use_gen>>() .expect("Every active pallet has a name in the runtime; qed"); @@ -861,7 +861,7 @@ pub fn expand_storages(def: &mut Def) -> proc_macro2::TokenStream { #frame_support::__private::log::debug!(target: "runtime::try-decode-state", "trying to decode pallet: {pallet_name}"); // NOTE: for now, we have to exclude storage items that are feature gated. - let mut errors = #frame_support::__private::sp_std::vec::Vec::new(); + let mut errors = #frame_support::__private::Vec::new(); let mut decoded = 0usize; #( @@ -902,7 +902,7 @@ pub fn expand_storages(def: &mut Def) -> proc_macro2::TokenStream { .expect("No name found for the pallet in the runtime! This usually means that the pallet wasn't added to `construct_runtime!`."), entries: { #[allow(unused_mut)] - let mut entries = #frame_support::__private::sp_std::vec![]; + let mut entries = #frame_support::__private::vec![]; #( #entries_builder )* entries }, diff --git a/substrate/frame/support/procedural/src/pallet/expand/tasks.rs b/substrate/frame/support/procedural/src/pallet/expand/tasks.rs index 6697e5c822a31b1ef719f03b47eb1ae32169fd03..7201c352d92cd062a2066fa33b4f8224516ae79b 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/tasks.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/tasks.rs @@ -159,7 +159,6 @@ impl ToTokens for TasksDef { let task_fn_names = self.tasks.iter().map(|task| &task.item.sig.ident); let task_arg_names = self.tasks.iter().map(|task| &task.arg_names).collect::>(); - let sp_std = quote!(#scrate::__private::sp_std); let impl_generics = &self.item_impl.generics; tokens.extend(quote! { impl #impl_generics #enum_use @@ -169,13 +168,13 @@ impl ToTokens for TasksDef { impl #impl_generics #scrate::traits::Task for #enum_use { - type Enumeration = #sp_std::vec::IntoIter<#enum_use>; + type Enumeration = #scrate::__private::IntoIter<#enum_use>; fn iter() -> Self::Enumeration { - let mut all_tasks = #sp_std::vec![]; + let mut all_tasks = #scrate::__private::vec![]; #(all_tasks .extend(#task_iters.map(|(#(#task_arg_names),*)| #enum_ident::#task_fn_idents { #(#task_arg_names: #task_arg_names.clone()),* }) - .collect::<#sp_std::vec::Vec<_>>()); + .collect::<#scrate::__private::Vec<_>>()); )* all_tasks.into_iter() } diff --git a/substrate/frame/support/procedural/src/pallet/parse/tests/tasks.rs b/substrate/frame/support/procedural/src/pallet/parse/tests/tasks.rs index 9f143628404734d5510de9e5997deec2a63644ea..7df91ae777d7f5974d5d4ba283048bd3a454ea96 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/tests/tasks.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/tests/tasks.rs @@ -124,10 +124,10 @@ fn test_parse_pallet_manual_tasks_impl_without_manual_tasks_enum() { where T: TypeInfo, { - type Enumeration = sp_std::vec::IntoIter>; + type Enumeration = alloc::vec::IntoIter>; fn iter() -> Self::Enumeration { - sp_std::vec![Task::increment, Task::decrement].into_iter() + alloc::vec![Task::increment, Task::decrement].into_iter() } } diff --git a/substrate/frame/support/procedural/src/runtime/expand/mod.rs b/substrate/frame/support/procedural/src/runtime/expand/mod.rs index 3cdfb06cb6eaa65c71777688421d5ef28a77fb11..f34ab1cef5436ffd6fccfff628a94d149a9ed5f5 100644 --- a/substrate/frame/support/procedural/src/runtime/expand/mod.rs +++ b/substrate/frame/support/procedural/src/runtime/expand/mod.rs @@ -280,7 +280,7 @@ fn construct_runtime_final_expansion( #[doc(hidden)] trait InternalConstructRuntime { #[inline(always)] - fn runtime_metadata(&self) -> #scrate::__private::sp_std::vec::Vec<#scrate::__private::metadata_ir::RuntimeApiMetadataIR> { + fn runtime_metadata(&self) -> #scrate::__private::Vec<#scrate::__private::metadata_ir::RuntimeApiMetadataIR> { Default::default() } } diff --git a/substrate/frame/support/src/dispatch.rs b/substrate/frame/support/src/dispatch.rs index 4a313551aca634b88bed7d0f989943f7075a5050..351ba3a15efcc9db4ce684190aa53268f068813b 100644 --- a/substrate/frame/support/src/dispatch.rs +++ b/substrate/frame/support/src/dispatch.rs @@ -20,6 +20,7 @@ use crate::traits::UnfilteredDispatchable; use codec::{Codec, Decode, Encode, EncodeLike, MaxEncodedLen}; +use core::fmt; use scale_info::TypeInfo; #[cfg(feature = "std")] use serde::{Deserialize, Serialize}; @@ -28,7 +29,6 @@ use sp_runtime::{ traits::SignedExtension, DispatchError, RuntimeDebug, }; -use sp_std::fmt; use sp_weights::Weight; /// The return type of a `Dispatchable` in frame. When returned explicitly from @@ -220,14 +220,14 @@ pub trait OneOrMany { } impl OneOrMany for DispatchClass { - type Iter = sp_std::iter::Once; + type Iter = core::iter::Once; fn into_iter(self) -> Self::Iter { - sp_std::iter::once(self) + core::iter::once(self) } } impl<'a> OneOrMany for &'a [DispatchClass] { - type Iter = sp_std::iter::Cloned>; + type Iter = core::iter::Cloned>; fn into_iter(self) -> Self::Iter { self.iter().cloned() } diff --git a/substrate/frame/support/src/dispatch_context.rs b/substrate/frame/support/src/dispatch_context.rs index 254302c8f14d2db1987353155ab7cacde65a5bb3..b34c6bdada3d484b00745dd02154af849c124c0a 100644 --- a/substrate/frame/support/src/dispatch_context.rs +++ b/substrate/frame/support/src/dispatch_context.rs @@ -81,11 +81,11 @@ //! In your pallet you will only have to use [`with_context`], because as described above //! [`run_in_context`] will be handled by FRAME for you. -use sp_std::{ - any::{Any, TypeId}, +use alloc::{ boxed::Box, collections::btree_map::{BTreeMap, Entry}, }; +use core::any::{Any, TypeId}; environmental::environmental!(DISPATCH_CONTEXT: BTreeMap>); @@ -158,7 +158,7 @@ pub fn with_context(callback: impl FnOnce(&mut Value) -> R) -> if value.is_none() { log::error!( "Failed to downcast value for type {} in dispatch context!", - sp_std::any::type_name::(), + core::any::type_name::(), ); } diff --git a/substrate/frame/support/src/genesis_builder_helper.rs b/substrate/frame/support/src/genesis_builder_helper.rs index 7389c5a787d76d01ec759658da28857bc85ff08f..662ea2cb1862dd003c1c5a5d3979ececb096f3b1 100644 --- a/substrate/frame/support/src/genesis_builder_helper.rs +++ b/substrate/frame/support/src/genesis_builder_helper.rs @@ -41,7 +41,7 @@ pub fn build_state(json: Vec) -> BuildResult { /// to [`sp_genesis_builder::GenesisBuilder::get_preset`]. pub fn get_preset( name: &Option, - preset_for_name: impl FnOnce(&sp_genesis_builder::PresetId) -> Option>, + preset_for_name: impl FnOnce(&sp_genesis_builder::PresetId) -> Option>, ) -> Option> where GC: BuildGenesisConfig + Default, diff --git a/substrate/frame/support/src/hash.rs b/substrate/frame/support/src/hash.rs index 9c48f4b187ad3666ed5fc44229656c35b84e0a81..a09890560c644797dcf831ebf32550f039b4d882 100644 --- a/substrate/frame/support/src/hash.rs +++ b/substrate/frame/support/src/hash.rs @@ -17,10 +17,10 @@ //! Hash utilities. +use alloc::vec::Vec; use codec::{Codec, MaxEncodedLen}; use sp_io::hashing::{blake2_128, blake2_256, twox_128, twox_256, twox_64}; use sp_metadata_ir as metadata_ir; -use sp_std::prelude::Vec; // This trait must be kept coherent with frame-support-procedural HasherKind usage pub trait Hashable: Sized { diff --git a/substrate/frame/support/src/lib.rs b/substrate/frame/support/src/lib.rs index 264914962fc4e427fcd9760fab40b32fcde81b19..3ad8c5fabaa2c320be0155d69354734be39618a8 100644 --- a/substrate/frame/support/src/lib.rs +++ b/substrate/frame/support/src/lib.rs @@ -33,11 +33,20 @@ #[doc(hidden)] extern crate self as frame_support; +#[doc(hidden)] +extern crate alloc; + /// Private exports that are being used by macros. /// /// The exports are not stable and should not be relied on. #[doc(hidden)] pub mod __private { + pub use alloc::{ + boxed::Box, + rc::Rc, + vec, + vec::{IntoIter, Vec}, + }; pub use codec; pub use frame_metadata as metadata; pub use log; @@ -261,7 +270,7 @@ macro_rules! parameter_types { ) => ( $( #[ $attr ] )* $vis struct $name $( - < $($ty_params),* >( $($crate::__private::sp_std::marker::PhantomData<$ty_params>),* ) + < $($ty_params),* >( $(core::marker::PhantomData<$ty_params>),* ) )?; $crate::parameter_types!(IMPL_CONST $name , $type , $value $( $(, $ty_params)* )?); $crate::parameter_types!( $( $rest )* ); @@ -273,7 +282,7 @@ macro_rules! parameter_types { ) => ( $( #[ $attr ] )* $vis struct $name $( - < $($ty_params),* >( $($crate::__private::sp_std::marker::PhantomData<$ty_params>),* ) + < $($ty_params),* >( $(core::marker::PhantomData<$ty_params>),* ) )?; $crate::parameter_types!(IMPL $name, $type, $value $( $(, $ty_params)* )?); $crate::parameter_types!( $( $rest )* ); @@ -285,7 +294,7 @@ macro_rules! parameter_types { ) => ( $( #[ $attr ] )* $vis struct $name $( - < $($ty_params),* >( $($crate::__private::sp_std::marker::PhantomData<$ty_params>),* ) + < $($ty_params),* >( $(core::marker::PhantomData<$ty_params>),* ) )?; $crate::parameter_types!(IMPL_STORAGE $name, $type, $value $( $(, $ty_params)* )?); $crate::parameter_types!( $( $rest )* ); @@ -468,7 +477,7 @@ macro_rules! ord_parameter_types { (IMPL $name:ident , $type:ty , $value:expr) => { impl $crate::traits::SortedMembers<$type> for $name { fn contains(t: &$type) -> bool { &$value == t } - fn sorted_members() -> $crate::__private::sp_std::prelude::Vec<$type> { vec![$value] } + fn sorted_members() -> $crate::__private::Vec<$type> { vec![$value] } fn count() -> usize { 1 } #[cfg(feature = "runtime-benchmarks")] fn add(_: &$type) {} @@ -499,7 +508,7 @@ macro_rules! runtime_print { } /// Print out the debuggable type. -pub fn debug(data: &impl sp_std::fmt::Debug) { +pub fn debug(data: &impl core::fmt::Debug) { runtime_print!("{:?}", data); } @@ -926,6 +935,7 @@ pub mod pallet_prelude { pub use codec::{Decode, Encode, MaxEncodedLen}; pub use frame_support::pallet_macros::*; + pub use core::marker::PhantomData; /// The optional attribute `#[inject_runtime_type]` can be attached to `RuntimeCall`, /// `RuntimeEvent`, `RuntimeOrigin` or `PalletInfo` in an impl statement that has /// `#[register_default_impl]` attached to indicate that this item is generated by @@ -954,7 +964,6 @@ pub mod pallet_prelude { }, DispatchError, RuntimeDebug, MAX_MODULE_ERROR_ENCODED_SIZE, }; - pub use sp_std::marker::PhantomData; pub use sp_weights::Weight; } @@ -1285,7 +1294,7 @@ pub mod pallet_macros { /// # use frame_support::pallet_prelude::*; /// # use frame_support::inherent::IsFatalError; /// # use sp_timestamp::InherentError; - /// # use sp_std::result; + /// # use core::result; /// # /// // Example inherent identifier /// pub const INHERENT_IDENTIFIER: InherentIdentifier = *b"timstap0"; @@ -1911,7 +1920,7 @@ pub mod pallet_macros { /// Field types in enum variants must also implement [`frame_support::PalletError`], /// otherwise the pallet will fail to compile. Rust primitive types have already /// implemented the [`frame_support::PalletError`] trait along with some commonly used - /// stdlib types such as [`Option`] and [`sp_std::marker::PhantomData`], and hence + /// stdlib types such as [`Option`] and [`core::marker::PhantomData`], and hence /// in most use cases, a manual implementation is not necessary and is discouraged. /// /// The generic `T` must not bound anything and a `where` clause is not allowed. That said, @@ -2343,13 +2352,13 @@ pub mod pallet_macros { /// the storage type, additional key specifications may be needed. /// /// #### Example - // #[doc = docify::embed!("src/lib.rs", example_storage_value_append)] + #[doc = docify::embed!("src/lib.rs", example_storage_value_append)] /// Similarly, there also exists a `::try_append()` method, which can be used when handling /// types where an append operation might fail, such as a /// [`BoundedVec`](frame_support::BoundedVec). /// /// #### Example - // #[doc = docify::embed!("src/lib.rs", example_storage_value_try_append)] + #[doc = docify::embed!("src/lib.rs", example_storage_value_try_append)] /// ### Optimized Length Decoding /// /// All storage items — such as @@ -2358,7 +2367,7 @@ pub mod pallet_macros { /// incorporate the `::decode_len()` method. This method allows for efficient retrieval of /// a collection's length without the necessity of decoding the entire dataset. /// #### Example - // #[doc = docify::embed!("src/lib.rs", example_storage_value_decode_len)] + #[doc = docify::embed!("src/lib.rs", example_storage_value_decode_len)] /// ### Hashers /// /// For all storage types, except @@ -2406,7 +2415,7 @@ pub mod pallet_macros { /// map. /// /// #### Example - // #[doc = docify::embed!("src/lib.rs", example_storage_value_map_prefixes)] + #[doc = docify::embed!("src/lib.rs", example_storage_value_map_prefixes)] /// ## Related Macros /// /// The following attribute macros can be used in conjunction with the `#[storage]` macro: diff --git a/substrate/frame/support/src/migrations.rs b/substrate/frame/support/src/migrations.rs index fa018d743653f2131944d188af7b0dd74057f143..7f74614695640dfd07771f689bb93971199baf10 100644 --- a/substrate/frame/support/src/migrations.rs +++ b/substrate/frame/support/src/migrations.rs @@ -24,13 +24,14 @@ use crate::{ }, weights::{RuntimeDbWeight, Weight, WeightMeter}, }; +use alloc::vec::Vec; use codec::{Decode, Encode, MaxEncodedLen}; +use core::marker::PhantomData; use impl_trait_for_tuples::impl_for_tuples; use sp_arithmetic::traits::Bounded; use sp_core::Get; use sp_io::{hashing::twox_128, storage::clear_prefix, KillStorageResult}; use sp_runtime::traits::Zero; -use sp_std::{marker::PhantomData, vec::Vec}; /// Handles storage migration pallet versioning. /// @@ -71,7 +72,7 @@ use sp_std::{marker::PhantomData, vec::Vec}; /// /// - https://internals.rust-lang.org/t/lang-team-minutes-private-in-public-rules/4504/40 /// mod version_unchecked { /// use super::*; -/// pub struct VersionUncheckedMigrateV5ToV6(sp_std::marker::PhantomData); +/// pub struct VersionUncheckedMigrateV5ToV6(core::marker::PhantomData); /// impl UncheckedOnRuntimeUpgrade for VersionUncheckedMigrateV5ToV6 { /// // `UncheckedOnRuntimeUpgrade` implementation... /// } @@ -102,7 +103,7 @@ pub struct VersionedMigration), + MigrationExecuted(alloc::vec::Vec), /// This migration is a noop, do not run post_upgrade checks. Noop, } @@ -125,7 +126,7 @@ impl< /// [`VersionedPostUpgradeData`] before passing them to post_upgrade, so it knows whether the /// migration ran or not. #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { + fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { let on_chain_version = Pallet::on_chain_storage_version(); if on_chain_version == FROM { Ok(VersionedPostUpgradeData::MigrationExecuted(Inner::pre_upgrade()?).encode()) @@ -175,7 +176,7 @@ impl< /// the migration ran, and [`VersionedPostUpgradeData::Noop`] otherwise. #[cfg(feature = "try-runtime")] fn post_upgrade( - versioned_post_upgrade_data_bytes: sp_std::vec::Vec, + versioned_post_upgrade_data_bytes: alloc::vec::Vec, ) -> Result<(), sp_runtime::TryRuntimeError> { use codec::DecodeAll; match ::decode_all(&mut &versioned_post_upgrade_data_bytes[..]) @@ -339,7 +340,7 @@ impl, DbWeight: Get> frame_support::traits } #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { + fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { use crate::storage::unhashed::contains_prefixed_key; let hashed_prefix = twox_128(P::get().as_bytes()); @@ -350,11 +351,11 @@ impl, DbWeight: Get> frame_support::traits P::get() ), }; - Ok(sp_std::vec::Vec::new()) + Ok(alloc::vec::Vec::new()) } #[cfg(feature = "try-runtime")] - fn post_upgrade(_state: sp_std::vec::Vec) -> Result<(), sp_runtime::TryRuntimeError> { + fn post_upgrade(_state: alloc::vec::Vec) -> Result<(), sp_runtime::TryRuntimeError> { use crate::storage::unhashed::contains_prefixed_key; let hashed_prefix = twox_128(P::get().as_bytes()); @@ -450,7 +451,7 @@ impl, S: Get<&'static str>, DbWeight: Get> } #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { + fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { use crate::storage::unhashed::contains_prefixed_key; let hashed_prefix = storage_prefix(P::get().as_bytes(), S::get().as_bytes()); @@ -466,7 +467,7 @@ impl, S: Get<&'static str>, DbWeight: Get> } #[cfg(feature = "try-runtime")] - fn post_upgrade(_state: sp_std::vec::Vec) -> Result<(), sp_runtime::TryRuntimeError> { + fn post_upgrade(_state: alloc::vec::Vec) -> Result<(), sp_runtime::TryRuntimeError> { use crate::storage::unhashed::contains_prefixed_key; let hashed_prefix = storage_prefix(P::get().as_bytes(), S::get().as_bytes()); diff --git a/substrate/frame/support/src/storage/bounded_btree_map.rs b/substrate/frame/support/src/storage/bounded_btree_map.rs index 91196be9e802c2eb9016abbcf86bfc0fb7fcb934..d3560dd5f0d4d566e6ed3dbacb9f148ad8ad4ed7 100644 --- a/substrate/frame/support/src/storage/bounded_btree_map.rs +++ b/substrate/frame/support/src/storage/bounded_btree_map.rs @@ -26,9 +26,9 @@ impl StorageDecodeLength for BoundedBTreeMap {} pub mod test { use super::*; use crate::Twox128; + use alloc::collections::btree_map::BTreeMap; use frame_support::traits::{ConstU32, Get}; use sp_io::TestExternalities; - use sp_std::collections::btree_map::BTreeMap; #[crate::storage_alias] type Foo = StorageValue>>; diff --git a/substrate/frame/support/src/storage/bounded_btree_set.rs b/substrate/frame/support/src/storage/bounded_btree_set.rs index cf801eb47874f048966aab8adb8a8b3eef5c14f6..70ab2304cab0176f69e6a4d08cc5b4b3915f5eb3 100644 --- a/substrate/frame/support/src/storage/bounded_btree_set.rs +++ b/substrate/frame/support/src/storage/bounded_btree_set.rs @@ -26,9 +26,9 @@ impl StorageDecodeNonDedupLength for BoundedBTreeSet {} pub mod test { use super::*; use crate::Twox128; + use alloc::collections::btree_set::BTreeSet; use frame_support::traits::{ConstU32, Get}; use sp_io::TestExternalities; - use sp_std::collections::btree_set::BTreeSet; #[crate::storage_alias] type Foo = StorageValue>>; diff --git a/substrate/frame/support/src/storage/child.rs b/substrate/frame/support/src/storage/child.rs index 76e6f4ee4023ec08c8c080929f5aba8f3bfd7509..5ebba269365851b488b8af4eacc3d498c874c2b2 100644 --- a/substrate/frame/support/src/storage/child.rs +++ b/substrate/frame/support/src/storage/child.rs @@ -21,10 +21,10 @@ // NOTE: could replace unhashed by having only one kind of storage (top trie being the child info // of null length parent storage key). +use alloc::vec::Vec; use codec::{Codec, Decode, Encode}; pub use sp_core::storage::{ChildInfo, ChildType, StateVersion}; pub use sp_io::{KillStorageResult, MultiRemovalResults}; -use sp_std::prelude::*; /// Return the value of the item in storage under `key`, or `None` if there is no explicit entry. pub fn get(child_info: &ChildInfo, key: &[u8]) -> Option { diff --git a/substrate/frame/support/src/storage/generator/double_map.rs b/substrate/frame/support/src/storage/generator/double_map.rs index a4c1f58203e3caf0cd200d0daf5b7b7aeba36702..b68f3fa495ff9a63cf4e17ec2f9e0e263257e2ed 100644 --- a/substrate/frame/support/src/storage/generator/double_map.rs +++ b/substrate/frame/support/src/storage/generator/double_map.rs @@ -20,8 +20,8 @@ use crate::{ storage::{self, storage_prefix, unhashed, KeyPrefixIterator, PrefixIterator, StorageAppend}, Never, }; +use alloc::vec::Vec; use codec::{Decode, Encode, EncodeLike, FullCodec, FullEncode}; -use sp_std::prelude::*; /// Generator for `StorageDoubleMap` used by `decl_storage`. /// @@ -516,6 +516,7 @@ mod test_iterators { unhashed, }, }; + use alloc::vec; use codec::Encode; #[test] diff --git a/substrate/frame/support/src/storage/generator/map.rs b/substrate/frame/support/src/storage/generator/map.rs index 257aa7e7bcf9a4f1d79b2242b5e09f4c0c8be601..b41f9c7171670363111419f4e150bd5653099f5c 100644 --- a/substrate/frame/support/src/storage/generator/map.rs +++ b/substrate/frame/support/src/storage/generator/map.rs @@ -20,9 +20,8 @@ use crate::{ storage::{self, storage_prefix, unhashed, KeyPrefixIterator, PrefixIterator, StorageAppend}, Never, }; +use alloc::vec::Vec; use codec::{Decode, Encode, EncodeLike, FullCodec, FullEncode}; -#[cfg(not(feature = "std"))] -use sp_std::prelude::*; /// Generator for `StorageMap` used by `decl_storage`. /// @@ -80,7 +79,7 @@ pub struct StorageMapIterator { prefix: Vec, previous_key: Vec, drain: bool, - _phantom: ::sp_std::marker::PhantomData<(K, V, Hasher)>, + _phantom: ::core::marker::PhantomData<(K, V, Hasher)>, } impl Iterator @@ -370,6 +369,7 @@ mod test_iterators { unhashed, }, }; + use alloc::vec; use codec::Encode; #[test] diff --git a/substrate/frame/support/src/storage/generator/mod.rs b/substrate/frame/support/src/storage/generator/mod.rs index dd6d622852db161cbe686115663e00a6bd9cd4b0..b0b1bda24bb7409264e66568ad4eea442a2fe9f6 100644 --- a/substrate/frame/support/src/storage/generator/mod.rs +++ b/substrate/frame/support/src/storage/generator/mod.rs @@ -36,6 +36,7 @@ pub use value::StorageValue; #[cfg(test)] mod tests { + use alloc::vec::Vec; use codec::Encode; use sp_io::TestExternalities; use sp_runtime::{generic, traits::BlakeTwo256, BuildStorage}; diff --git a/substrate/frame/support/src/storage/generator/nmap.rs b/substrate/frame/support/src/storage/generator/nmap.rs index 4b49ad3eb38d434a897ed2b1020156e541b02a96..0466583a27955665090c33e6527caa9182abf90f 100755 --- a/substrate/frame/support/src/storage/generator/nmap.rs +++ b/substrate/frame/support/src/storage/generator/nmap.rs @@ -40,9 +40,8 @@ use crate::{ }, Never, }; +use alloc::vec::Vec; use codec::{Decode, Encode, EncodeLike, FullCodec}; -#[cfg(not(feature = "std"))] -use sp_std::prelude::*; /// Generator for `StorageNMap` used by `decl_storage` and storage types. /// @@ -464,6 +463,7 @@ mod test_iterators { unhashed, }, }; + use alloc::vec; use codec::Encode; #[test] diff --git a/substrate/frame/support/src/storage/hashed.rs b/substrate/frame/support/src/storage/hashed.rs index 6633adce8ff655aa7d5e3df0b63be77a645812f7..d823eb98879949ea53cf36c0695f12a06d3b039a 100644 --- a/substrate/frame/support/src/storage/hashed.rs +++ b/substrate/frame/support/src/storage/hashed.rs @@ -18,8 +18,8 @@ //! Operation on runtime storage using hashed keys. use super::unhashed; +use alloc::vec::Vec; use codec::{Decode, Encode}; -use sp_std::prelude::*; /// Return the value of the item in storage under `key`, or `None` if there is no explicit entry. pub fn get(hash: &HashFn, key: &[u8]) -> Option diff --git a/substrate/frame/support/src/storage/migration.rs b/substrate/frame/support/src/storage/migration.rs index 252625cf4f7d02aa82418ca50b45334c53692766..1dd690c3ed67b9b7f69db9534cdbace481c845a1 100644 --- a/substrate/frame/support/src/storage/migration.rs +++ b/substrate/frame/support/src/storage/migration.rs @@ -22,8 +22,8 @@ use crate::{ storage::{storage_prefix, unhashed}, StorageHasher, Twox128, }; +use alloc::{vec, vec::Vec}; use codec::{Decode, Encode}; -use sp_std::prelude::*; use super::PrefixIterator; @@ -32,7 +32,7 @@ pub struct StorageIterator { prefix: Vec, previous_key: Vec, drain: bool, - _phantom: ::sp_std::marker::PhantomData, + _phantom: ::core::marker::PhantomData, } impl StorageIterator { @@ -95,7 +95,7 @@ pub struct StorageKeyIterator { prefix: Vec, previous_key: Vec, drain: bool, - _phantom: ::sp_std::marker::PhantomData<(K, T, H)>, + _phantom: ::core::marker::PhantomData<(K, T, H)>, } impl StorageKeyIterator { diff --git a/substrate/frame/support/src/storage/mod.rs b/substrate/frame/support/src/storage/mod.rs index f7d7447482d06ccd64e59c3b8e49aec18696fdee..7fb991d377923a936abf808ca07627ca9fbead3f 100644 --- a/substrate/frame/support/src/storage/mod.rs +++ b/substrate/frame/support/src/storage/mod.rs @@ -24,10 +24,11 @@ use crate::{ ReversibleKeyGenerator, TupleToEncodedIter, }, }; +use alloc::{collections::btree_set::BTreeSet, vec::Vec}; use codec::{Decode, Encode, EncodeLike, FullCodec, FullEncode}; +use core::marker::PhantomData; use sp_core::storage::ChildInfo; use sp_runtime::generic::{Digest, DigestItem}; -use sp_std::{collections::btree_set::BTreeSet, marker::PhantomData, prelude::*}; pub use self::{ stream_iter::StorageStreamIter, diff --git a/substrate/frame/support/src/storage/storage_noop_guard.rs b/substrate/frame/support/src/storage/storage_noop_guard.rs index c4d40fa99a35cef9a05d55b71f27de1717a72cee..23201e58db5b70157188409808c5c51d0358026d 100644 --- a/substrate/frame/support/src/storage/storage_noop_guard.rs +++ b/substrate/frame/support/src/storage/storage_noop_guard.rs @@ -38,7 +38,7 @@ /// ``` #[must_use] pub struct StorageNoopGuard<'a> { - storage_root: sp_std::vec::Vec, + storage_root: alloc::vec::Vec, error_message: &'a str, } @@ -71,7 +71,8 @@ impl<'a> StorageNoopGuard<'a> { impl<'a> Drop for StorageNoopGuard<'a> { fn drop(&mut self) { // No need to double panic, eg. inside a test assertion failure. - if sp_std::thread::panicking() { + #[cfg(feature = "std")] + if std::thread::panicking() { return } assert_eq!( @@ -85,9 +86,10 @@ impl<'a> Drop for StorageNoopGuard<'a> { #[cfg(test)] mod tests { - use super::*; use sp_io::TestExternalities; + use super::*; + #[test] #[should_panic(expected = "`StorageNoopGuard` detected an attempted storage change.")] fn storage_noop_guard_panics_on_changed() { @@ -112,7 +114,7 @@ mod tests { TestExternalities::default().execute_with(|| { let guard = StorageNoopGuard::default(); frame_support::storage::unhashed::put(b"key", b"value"); - sp_std::mem::drop(guard); + std::mem::drop(guard); frame_support::storage::unhashed::kill(b"key"); }); } @@ -122,7 +124,7 @@ mod tests { TestExternalities::default().execute_with(|| { let guard = StorageNoopGuard::default(); frame_support::storage::unhashed::put(b"key", b"value"); - sp_std::mem::forget(guard); + std::mem::forget(guard); }); } diff --git a/substrate/frame/support/src/storage/stream_iter.rs b/substrate/frame/support/src/storage/stream_iter.rs index 529b2f387c71cc86b52f648f8630bd9f2339dd69..0d1e5582f841b853f0f7a1726fe5a018756abb75 100644 --- a/substrate/frame/support/src/storage/stream_iter.rs +++ b/substrate/frame/support/src/storage/stream_iter.rs @@ -16,8 +16,8 @@ // limitations under the License. use crate::{BoundedBTreeMap, BoundedBTreeSet, BoundedVec, WeakBoundedVec}; +use alloc::vec::Vec; use codec::Decode; -use sp_std::vec::Vec; /// Provides the sealed trait `StreamIter`. mod private { @@ -26,7 +26,7 @@ mod private { /// Used as marker trait for types that support stream iteration. pub trait StreamIter { /// The actual iterator implementation. - type Iterator: sp_std::iter::Iterator; + type Iterator: core::iter::Iterator; /// Create the stream iterator for the value found at `key`. fn stream_iter(key: Vec) -> Self::Iterator; @@ -40,7 +40,7 @@ mod private { } } - impl StreamIter for sp_std::collections::btree_set::BTreeSet { + impl StreamIter for alloc::collections::btree_set::BTreeSet { type Iterator = ScaleContainerStreamIter; fn stream_iter(key: Vec) -> Self::Iterator { @@ -49,7 +49,7 @@ mod private { } impl StreamIter - for sp_std::collections::btree_map::BTreeMap + for alloc::collections::btree_map::BTreeMap { type Iterator = ScaleContainerStreamIter<(K, V)>; @@ -116,14 +116,14 @@ impl(len) ++ data`. -/// This type provides an [`Iterator`](sp_std::iter::Iterator) implementation that decodes +/// This type provides an [`Iterator`](core::iter::Iterator) implementation that decodes /// one item after another with each call to [`next`](Self::next). The bytes representing /// the container are also not read at once into memory and instead being read in chunks. As long /// as individual items are smaller than these chunks the memory usage of this iterator should /// be constant. On decoding errors [`next`](Self::next) will return `None` to signal that the /// iterator is finished. pub struct ScaleContainerStreamIter { - marker: sp_std::marker::PhantomData, + marker: core::marker::PhantomData, input: StorageInput, length: u32, read: u32, @@ -156,7 +156,7 @@ impl ScaleContainerStreamIter { 0 }; - Self { marker: sp_std::marker::PhantomData, input, length, read: 0 } + Self { marker: core::marker::PhantomData, input, length, read: 0 } } /// Creates a new instance of the stream iterator. @@ -168,11 +168,11 @@ impl ScaleContainerStreamIter { let mut input = StorageInput::new(key); let length = if input.exists() { codec::Compact::::decode(&mut input)?.0 } else { 0 }; - Ok(Self { marker: sp_std::marker::PhantomData, input, length, read: 0 }) + Ok(Self { marker: core::marker::PhantomData, input, length, read: 0 }) } } -impl sp_std::iter::Iterator for ScaleContainerStreamIter { +impl core::iter::Iterator for ScaleContainerStreamIter { type Item = T; fn next(&mut self) -> Option { @@ -235,7 +235,7 @@ impl StorageInput { /// /// - `key`: The storage key of the storage item that this input will read. fn new(key: Vec) -> Self { - let mut buffer = sp_std::vec![0; STORAGE_INPUT_BUFFER_CAPACITY]; + let mut buffer = alloc::vec![0; STORAGE_INPUT_BUFFER_CAPACITY]; unsafe { buffer.set_len(buffer.capacity()); } @@ -270,7 +270,7 @@ impl StorageInput { sp_io::storage::read(&self.key, &mut self.buffer[present_bytes..], self.offset) { let bytes_read = - sp_std::cmp::min(length_minus_offset as usize, self.buffer.len() - present_bytes); + core::cmp::min(length_minus_offset as usize, self.buffer.len() - present_bytes); let buffer_len = present_bytes + bytes_read; unsafe { self.buffer.set_len(buffer_len); diff --git a/substrate/frame/support/src/storage/types/counted_map.rs b/substrate/frame/support/src/storage/types/counted_map.rs index 0444e269928ab68e6da1ebada37425d77bdcc288..9adcb33ae07434010b3a63fa09112ab71d69f17b 100644 --- a/substrate/frame/support/src/storage/types/counted_map.rs +++ b/substrate/frame/support/src/storage/types/counted_map.rs @@ -29,11 +29,11 @@ use crate::{ traits::{Get, GetDefault, StorageInfo, StorageInfoTrait, StorageInstance}, Never, }; +use alloc::{vec, vec::Vec}; use codec::{Decode, Encode, EncodeLike, FullCodec, MaxEncodedLen, Ref}; use sp_io::MultiRemovalResults; use sp_metadata_ir::StorageEntryMetadataIR; use sp_runtime::traits::Saturating; -use sp_std::prelude::*; /// A wrapper around a [`StorageMap`] and a [`StorageValue`] (with the value being `u32`) to keep /// track of how many items are in a map, without needing to iterate all the values. diff --git a/substrate/frame/support/src/storage/types/counted_nmap.rs b/substrate/frame/support/src/storage/types/counted_nmap.rs index 51cde93f28c01d8dab45da49fddb0b5eeb1c54d1..13c1b10be39c47dfe4792b9f91cf84944f2867ae 100644 --- a/substrate/frame/support/src/storage/types/counted_nmap.rs +++ b/substrate/frame/support/src/storage/types/counted_nmap.rs @@ -28,10 +28,10 @@ use crate::{ traits::{Get, GetDefault, StorageInfo, StorageInstance}, Never, }; +use alloc::{vec, vec::Vec}; use codec::{Decode, Encode, EncodeLike, FullCodec, MaxEncodedLen, Ref}; use sp_metadata_ir::StorageEntryMetadataIR; use sp_runtime::traits::Saturating; -use sp_std::prelude::*; /// A wrapper around a [`StorageNMap`] and a [`StorageValue`] (with the value being `u32`) to keep /// track of how many items are in a map, without needing to iterate all the values. @@ -683,6 +683,7 @@ mod test { hash::{StorageHasher as _, *}, storage::types::{Key as NMapKey, ValueQuery}, }; + use alloc::boxed::Box; use sp_io::{hashing::twox_128, TestExternalities}; use sp_metadata_ir::{StorageEntryModifierIR, StorageEntryTypeIR, StorageHasherIR}; diff --git a/substrate/frame/support/src/storage/types/double_map.rs b/substrate/frame/support/src/storage/types/double_map.rs index c1443b2ae660cee26a5c7a6996d31f7a645b68f7..3d227feb902f304f8596f20bc288487e272316cc 100644 --- a/substrate/frame/support/src/storage/types/double_map.rs +++ b/substrate/frame/support/src/storage/types/double_map.rs @@ -26,11 +26,11 @@ use crate::{ traits::{Get, GetDefault, StorageInfo, StorageInstance}, StorageHasher, Twox128, }; +use alloc::{vec, vec::Vec}; use codec::{Decode, Encode, EncodeLike, FullCodec, MaxEncodedLen}; use frame_support::storage::StorageDecodeNonDedupLength; use sp_arithmetic::traits::SaturatedConversion; use sp_metadata_ir::{StorageEntryMetadataIR, StorageEntryTypeIR}; -use sp_std::prelude::*; /// A type representing a *double map* in storage. This structure associates a pair of keys with a /// value of a specified type stored on-chain. @@ -91,7 +91,7 @@ use sp_std::prelude::*; /// When `Hasher1` and `Hasher2` implement the /// [`ReversibleStorageHasher`](frame_support::ReversibleStorageHasher) trait, the first key `k1` /// can be used to partially iterate over keys and values of the double map, and to delete items. -// #[doc = docify::embed!("src/storage/types/double_map.rs", example_double_map_partial_operations)] +#[doc = docify::embed!("src/storage/types/double_map.rs", example_double_map_partial_operations)] pub struct StorageDoubleMap< Prefix, Hasher1, diff --git a/substrate/frame/support/src/storage/types/key.rs b/substrate/frame/support/src/storage/types/key.rs index 90cf09dd1d341eefc9280c3a086ff6c311248141..b9b497b61d949be4cf7933cc56b3111e91917f1c 100755 --- a/substrate/frame/support/src/storage/types/key.rs +++ b/substrate/frame/support/src/storage/types/key.rs @@ -18,10 +18,10 @@ //! Storage key type. use crate::hash::{ReversibleStorageHasher, StorageHasher}; +use alloc::{boxed::Box, vec::Vec}; use codec::{Encode, EncodeLike, FullCodec, MaxEncodedLen}; use paste::paste; use scale_info::StaticTypeInfo; -use sp_std::prelude::*; /// A type used exclusively by storage maps as their key type. /// @@ -203,19 +203,19 @@ impl<'a, T: EncodeLike + EncodeLikeTuple, U: Encode> EncodeLikeTuple /// Trait to indicate that a tuple can be converted into an iterator of a vector of encoded bytes. pub trait TupleToEncodedIter { - fn to_encoded_iter(&self) -> sp_std::vec::IntoIter>; + fn to_encoded_iter(&self) -> alloc::vec::IntoIter>; } #[impl_trait_for_tuples::impl_for_tuples(1, 18)] #[tuple_types_custom_trait_bound(Encode)] impl TupleToEncodedIter for Tuple { - fn to_encoded_iter(&self) -> sp_std::vec::IntoIter> { + fn to_encoded_iter(&self) -> alloc::vec::IntoIter> { [for_tuples!( #(self.Tuple.encode()),* )].to_vec().into_iter() } } impl TupleToEncodedIter for &T { - fn to_encoded_iter(&self) -> sp_std::vec::IntoIter> { + fn to_encoded_iter(&self) -> alloc::vec::IntoIter> { (*self).to_encoded_iter() } } @@ -223,7 +223,7 @@ impl TupleToEncodedIter for &T { impl<'a, T: EncodeLike + TupleToEncodedIter, U: Encode> TupleToEncodedIter for codec::Ref<'a, T, U> { - fn to_encoded_iter(&self) -> sp_std::vec::IntoIter> { + fn to_encoded_iter(&self) -> alloc::vec::IntoIter> { use core::ops::Deref as _; self.deref().to_encoded_iter() } diff --git a/substrate/frame/support/src/storage/types/map.rs b/substrate/frame/support/src/storage/types/map.rs index b79a6ae9b8482090c3f3ebe42b7b23aa8824b657..b70026eea50e130cb2fd7c7dc743aec744b8e5d8 100644 --- a/substrate/frame/support/src/storage/types/map.rs +++ b/substrate/frame/support/src/storage/types/map.rs @@ -26,11 +26,11 @@ use crate::{ traits::{Get, GetDefault, StorageInfo, StorageInstance}, StorageHasher, Twox128, }; +use alloc::{vec, vec::Vec}; use codec::{Decode, Encode, EncodeLike, FullCodec, MaxEncodedLen}; use frame_support::storage::StorageDecodeNonDedupLength; use sp_arithmetic::traits::SaturatedConversion; use sp_metadata_ir::{StorageEntryMetadataIR, StorageEntryTypeIR}; -use sp_std::prelude::*; /// A type representing a *map* in storage. A *storage map* is a mapping of keys to values of a /// given type stored on-chain. diff --git a/substrate/frame/support/src/storage/types/mod.rs b/substrate/frame/support/src/storage/types/mod.rs index 631410f425d17a169f16cd0380a3ffa3f22f6611..b063e11621d61a7481c5a3dd409321bd76e33597 100644 --- a/substrate/frame/support/src/storage/types/mod.rs +++ b/substrate/frame/support/src/storage/types/mod.rs @@ -18,9 +18,9 @@ //! Storage types to build abstraction on storage, they implements storage traits such as //! StorageMap and others. +use alloc::vec::Vec; use codec::FullCodec; use sp_metadata_ir::{StorageEntryMetadataIR, StorageEntryModifierIR}; -use sp_std::prelude::*; mod counted_map; mod counted_nmap; @@ -93,7 +93,7 @@ where } /// Implements [`QueryKindTrait`] with `Query` type being `Result`. -pub struct ResultQuery(sp_std::marker::PhantomData); +pub struct ResultQuery(core::marker::PhantomData); impl QueryKindTrait for ResultQuery where Value: FullCodec + 'static, diff --git a/substrate/frame/support/src/storage/types/nmap.rs b/substrate/frame/support/src/storage/types/nmap.rs index 253f02a14f0796f7ecba7e81af8e5be7b7ec0e42..c3dfd5b3e48c9dc742499e5b9c7de032d7066d72 100755 --- a/substrate/frame/support/src/storage/types/nmap.rs +++ b/substrate/frame/support/src/storage/types/nmap.rs @@ -28,10 +28,10 @@ use crate::{ }, traits::{Get, GetDefault, StorageInfo, StorageInstance}, }; +use alloc::{vec, vec::Vec}; use codec::{Decode, Encode, EncodeLike, FullCodec, MaxEncodedLen}; use sp_metadata_ir::{StorageEntryMetadataIR, StorageEntryTypeIR}; use sp_runtime::SaturatedConversion; -use sp_std::prelude::*; /// A type representing an *NMap* in storage. This structure associates an arbitrary number of keys /// with a value of a specified type stored on-chain. @@ -655,6 +655,7 @@ mod test { hash::{StorageHasher as _, *}, storage::types::{Key as NMapKey, ValueQuery}, }; + use alloc::boxed::Box; use sp_io::{hashing::twox_128, TestExternalities}; use sp_metadata_ir::{StorageEntryModifierIR, StorageHasherIR}; diff --git a/substrate/frame/support/src/storage/types/value.rs b/substrate/frame/support/src/storage/types/value.rs index a2d93a6a165ffca205f1597dfa0952c9c4900313..9cc985b36d8c60aa1969286912ca46c6ae446827 100644 --- a/substrate/frame/support/src/storage/types/value.rs +++ b/substrate/frame/support/src/storage/types/value.rs @@ -25,11 +25,11 @@ use crate::{ }, traits::{Get, GetDefault, StorageInfo, StorageInstance}, }; +use alloc::{vec, vec::Vec}; use codec::{Decode, Encode, EncodeLike, FullCodec, MaxEncodedLen}; use frame_support::storage::StorageDecodeNonDedupLength; use sp_arithmetic::traits::SaturatedConversion; use sp_metadata_ir::{StorageEntryMetadataIR, StorageEntryTypeIR}; -use sp_std::prelude::*; /// A type representing a *value* in storage. A *storage value* is a single value of a given type /// stored on-chain. diff --git a/substrate/frame/support/src/storage/unhashed.rs b/substrate/frame/support/src/storage/unhashed.rs index 776c7d0f3c3a8d761d7c048e292d590056b374c3..7f9bc93d7d818ff5f025617e721c3f79587347cb 100644 --- a/substrate/frame/support/src/storage/unhashed.rs +++ b/substrate/frame/support/src/storage/unhashed.rs @@ -17,8 +17,8 @@ //! Operation on unhashed runtime storage. +use alloc::vec::Vec; use codec::{Decode, Encode}; -use sp_std::prelude::*; /// Return the value of the item in storage under `key`, or `None` if there is no explicit entry. pub fn get(key: &[u8]) -> Option { diff --git a/substrate/frame/support/src/traits/dynamic_params.rs b/substrate/frame/support/src/traits/dynamic_params.rs index 32dae6799eaf7c9061851896ada9fe4e8a1a3e0d..3ef298fc5a5a092b06f886cab0ad3e7d1fdca670 100644 --- a/substrate/frame/support/src/traits/dynamic_params.rs +++ b/substrate/frame/support/src/traits/dynamic_params.rs @@ -85,7 +85,7 @@ impl AggregatedKeyValue for () { /// /// This concretization is useful when configuring pallets, since a pallet will require a parameter /// store for its own KV type and not the aggregated runtime-wide KV type. -pub struct ParameterStoreAdapter(sp_std::marker::PhantomData<(PS, KV)>); +pub struct ParameterStoreAdapter(core::marker::PhantomData<(PS, KV)>); impl ParameterStore for ParameterStoreAdapter where diff --git a/substrate/frame/support/src/traits/filter.rs b/substrate/frame/support/src/traits/filter.rs index 44f9f136cfc2a14c05d0f2a938530d8b2b597515..ff62449847d2542da9ca1fc1c32e780d06a5fb11 100644 --- a/substrate/frame/support/src/traits/filter.rs +++ b/substrate/frame/support/src/traits/filter.rs @@ -18,7 +18,7 @@ //! Traits and associated utilities for dealing with abstract constraint filters. pub use super::members::Contains; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; /// Trait to add a constraint onto the filter. pub trait FilterStack: Contains { @@ -103,7 +103,7 @@ macro_rules! impl_filter_stack { mod $module { #[allow(unused_imports)] use super::*; - use $crate::__private::sp_std::{boxed::Box, cell::RefCell, mem::{swap, take}, vec::Vec}; + use std::{boxed::Box, cell::RefCell, mem::{swap, take}, vec::Vec}; use $crate::traits::filter::{Contains, FilterStack}; thread_local! { diff --git a/substrate/frame/support/src/traits/hooks.rs b/substrate/frame/support/src/traits/hooks.rs index 1a687cade79f5973a8b2816d0cba40ef250c4b3a..012a74d0ae92f1dcc9c3797f62d2ffc9d137485c 100644 --- a/substrate/frame/support/src/traits/hooks.rs +++ b/substrate/frame/support/src/traits/hooks.rs @@ -24,9 +24,10 @@ use crate::weights::Weight; use impl_trait_for_tuples::impl_for_tuples; use sp_runtime::traits::AtLeast32BitUnsigned; -use sp_std::prelude::*; use sp_weights::WeightMeter; +#[cfg(feature = "try-runtime")] +use alloc::vec::Vec; #[cfg(feature = "try-runtime")] use sp_runtime::TryRuntimeError; @@ -707,7 +708,7 @@ mod tests { #[test] fn on_idle_round_robin_works() { - static mut ON_IDLE_INVOCATION_ORDER: sp_std::vec::Vec<&str> = sp_std::vec::Vec::new(); + static mut ON_IDLE_INVOCATION_ORDER: alloc::vec::Vec<&str> = alloc::vec::Vec::new(); struct Test1; struct Test2; diff --git a/substrate/frame/support/src/traits/members.rs b/substrate/frame/support/src/traits/members.rs index 53de84ab22455f2d778c1fd64ba94c348c685db0..89b6b6cdfad954ea70c88b41cb2be95ff6a5add2 100644 --- a/substrate/frame/support/src/traits/members.rs +++ b/substrate/frame/support/src/traits/members.rs @@ -17,10 +17,11 @@ //! Traits for dealing with the idea of membership. +use alloc::vec::Vec; +use core::marker::PhantomData; use impl_trait_for_tuples::impl_for_tuples; use sp_arithmetic::traits::AtLeast16BitUnsigned; use sp_runtime::DispatchResult; -use sp_std::{marker::PhantomData, prelude::*}; /// A trait for querying whether a type can be said to "contain" a value. pub trait Contains { diff --git a/substrate/frame/support/src/traits/messages.rs b/substrate/frame/support/src/traits/messages.rs index 2eec606b6d18b20a086e4ce7b44a877c3b8fb4d5..d28716237119e8972b7069a806a82cbca0c26169 100644 --- a/substrate/frame/support/src/traits/messages.rs +++ b/substrate/frame/support/src/traits/messages.rs @@ -19,15 +19,15 @@ use super::storage::Footprint; use codec::{Decode, Encode, FullCodec, MaxEncodedLen}; +use core::{fmt::Debug, marker::PhantomData}; use scale_info::TypeInfo; use sp_core::{ConstU32, Get, TypedGet}; use sp_runtime::{traits::Convert, BoundedSlice, RuntimeDebug}; -use sp_std::{fmt::Debug, marker::PhantomData, prelude::*}; use sp_weights::{Weight, WeightMeter}; /// Errors that can happen when attempting to process a message with /// [`ProcessMessage::process_message()`]. -#[derive(Copy, Clone, Eq, PartialEq, Encode, Decode, TypeInfo, RuntimeDebug)] +#[derive(Copy, Clone, Eq, PartialEq, Encode, Decode, TypeInfo, Debug)] pub enum ProcessMessageError { /// The message data format is unknown (e.g. unrecognised header) BadFormat, diff --git a/substrate/frame/support/src/traits/metadata.rs b/substrate/frame/support/src/traits/metadata.rs index 8bda4186bc967b29a6342ea96dd0a1cdc5072438..1e46470a3911ff840baff2230a8d9af753363757 100644 --- a/substrate/frame/support/src/traits/metadata.rs +++ b/substrate/frame/support/src/traits/metadata.rs @@ -17,10 +17,11 @@ //! Traits for managing information attached to pallets and their constituents. +use alloc::{vec, vec::Vec}; use codec::{Decode, Encode}; +use core::ops::Add; use impl_trait_for_tuples::impl_for_tuples; use sp_runtime::RuntimeDebug; -use sp_std::{ops::Add, prelude::*}; /// Provides information about the pallet itself and its setup in the runtime. /// @@ -146,16 +147,16 @@ impl CrateVersion { } } -impl sp_std::cmp::Ord for CrateVersion { - fn cmp(&self, other: &Self) -> sp_std::cmp::Ordering { +impl Ord for CrateVersion { + fn cmp(&self, other: &Self) -> core::cmp::Ordering { self.major .cmp(&other.major) .then_with(|| self.minor.cmp(&other.minor).then_with(|| self.patch.cmp(&other.patch))) } } -impl sp_std::cmp::PartialOrd for CrateVersion { - fn partial_cmp(&self, other: &Self) -> Option { +impl PartialOrd for CrateVersion { + fn partial_cmp(&self, other: &Self) -> Option { Some(::cmp(self, other)) } } @@ -248,7 +249,7 @@ impl PartialEq for StorageVersion { } impl PartialOrd for StorageVersion { - fn partial_cmp(&self, other: &u16) -> Option { + fn partial_cmp(&self, other: &u16) -> Option { Some(self.0.cmp(other)) } } diff --git a/substrate/frame/support/src/traits/misc.rs b/substrate/frame/support/src/traits/misc.rs index bc7407a7be6248f25866a78f3b95bb0107ff19ae..7c8c22d1ae5a3f49906b71890758608857332534 100644 --- a/substrate/frame/support/src/traits/misc.rs +++ b/substrate/frame/support/src/traits/misc.rs @@ -18,19 +18,20 @@ //! Smaller traits used in FRAME which don't need their own file. use crate::dispatch::{DispatchResult, Parameter}; +use alloc::{vec, vec::Vec}; use codec::{CompactLen, Decode, DecodeLimit, Encode, EncodeLike, Input, MaxEncodedLen}; use impl_trait_for_tuples::impl_for_tuples; use scale_info::{build::Fields, meta_type, Path, Type, TypeInfo, TypeParameter}; use sp_arithmetic::traits::{CheckedAdd, CheckedMul, CheckedSub, One, Saturating}; use sp_core::bounded::bounded_vec::TruncateFrom; +use core::cmp::Ordering; #[doc(hidden)] pub use sp_runtime::traits::{ ConstBool, ConstI128, ConstI16, ConstI32, ConstI64, ConstI8, ConstU128, ConstU16, ConstU32, ConstU64, ConstU8, Get, GetDefault, TryCollect, TypedGet, }; use sp_runtime::{traits::Block as BlockT, DispatchError}; -use sp_std::{cmp::Ordering, prelude::*}; #[doc(hidden)] pub const DEFENSIVE_OP_PUBLIC_ERROR: &str = "a defensive failure has been triggered; please report the block number at https://github.com/paritytech/substrate/issues"; @@ -48,7 +49,7 @@ impl VariantCount for () { } /// Adapter for `Get` to access `VARIANT_COUNT` from `trait pub trait VariantCount {`. -pub struct VariantCountOf(sp_std::marker::PhantomData); +pub struct VariantCountOf(core::marker::PhantomData); impl Get for VariantCountOf { fn get() -> u32 { T::VARIANT_COUNT @@ -190,10 +191,10 @@ pub trait DefensiveOption { /// Defensively transform this option to a result, mapping `None` to the return value of an /// error closure. - fn defensive_ok_or_else E>(self, err: F) -> Result; + fn defensive_ok_or_else E>(self, err: F) -> Result; /// Defensively transform this option to a result, mapping `None` to a default value. - fn defensive_ok_or(self, err: E) -> Result; + fn defensive_ok_or(self, err: E) -> Result; /// Exactly the same as `map`, but it prints the appropriate warnings if the value being mapped /// is `None`. @@ -252,7 +253,7 @@ impl Defensive for Option { } } -impl Defensive for Result { +impl Defensive for Result { fn defensive_unwrap_or(self, or: T) -> T { match self { Ok(inner) => inner, @@ -307,7 +308,7 @@ impl Defensive for Result { } } -impl DefensiveResult for Result { +impl DefensiveResult for Result { fn defensive_map_err F>(self, o: O) -> Result { self.map_err(|e| { defensive!(e); @@ -357,7 +358,7 @@ impl DefensiveOption for Option { ) } - fn defensive_ok_or_else E>(self, err: F) -> Result { + fn defensive_ok_or_else E>(self, err: F) -> Result { self.ok_or_else(|| { let err_value = err(); defensive!(err_value); @@ -365,7 +366,7 @@ impl DefensiveOption for Option { }) } - fn defensive_ok_or(self, err: E) -> Result { + fn defensive_ok_or(self, err: E) -> Result { self.ok_or_else(|| { defensive!(err); err @@ -416,11 +417,11 @@ impl DefensiveSatura } fn defensive_saturating_accrue(&mut self, other: Self) { // Use `replace` here since `take` would require `T: Default`. - *self = sp_std::mem::replace(self, One::one()).defensive_saturating_add(other); + *self = core::mem::replace(self, One::one()).defensive_saturating_add(other); } fn defensive_saturating_reduce(&mut self, other: Self) { // Use `replace` here since `take` would require `T: Default`. - *self = sp_std::mem::replace(self, One::one()).defensive_saturating_sub(other); + *self = core::mem::replace(self, One::one()).defensive_saturating_sub(other); } fn defensive_saturating_inc(&mut self) { self.defensive_saturating_accrue(One::one()); @@ -510,7 +511,7 @@ pub trait DefensiveMin { impl DefensiveMin for T where - T: sp_std::cmp::PartialOrd, + T: PartialOrd, { fn defensive_min(self, other: T) -> Self { if self <= other { @@ -574,7 +575,7 @@ pub trait DefensiveMax { impl DefensiveMax for T where - T: sp_std::cmp::PartialOrd, + T: PartialOrd, { fn defensive_max(self, other: T) -> Self { if self >= other { @@ -1050,7 +1051,7 @@ impl TypeInfo for WrapperOpaque { #[derive(Debug, Eq, PartialEq, Default, Clone)] pub struct WrapperKeepOpaque { data: Vec, - _phantom: sp_std::marker::PhantomData, + _phantom: core::marker::PhantomData, } impl WrapperKeepOpaque { @@ -1073,7 +1074,7 @@ impl WrapperKeepOpaque { /// Create from the given encoded `data`. pub fn from_encoded(data: Vec) -> Self { - Self { data, _phantom: sp_std::marker::PhantomData } + Self { data, _phantom: core::marker::PhantomData } } } @@ -1100,7 +1101,7 @@ impl Encode for WrapperKeepOpaque { impl Decode for WrapperKeepOpaque { fn decode(input: &mut I) -> Result { - Ok(Self { data: Vec::::decode(input)?, _phantom: sp_std::marker::PhantomData }) + Ok(Self { data: Vec::::decode(input)?, _phantom: core::marker::PhantomData }) } fn skip(input: &mut I) -> Result<(), codec::Error> { @@ -1212,8 +1213,8 @@ pub trait AccountTouch { #[cfg(test)] mod test { use super::*; + use core::marker::PhantomData; use sp_core::bounded::{BoundedSlice, BoundedVec}; - use sp_std::marker::PhantomData; #[test] fn defensive_assert_works() { diff --git a/substrate/frame/support/src/traits/preimages.rs b/substrate/frame/support/src/traits/preimages.rs index 647af029c16dce07f998e34c30cb076f6a670d4c..80020d8d00809af048334d8614e8d7f8953c6525 100644 --- a/substrate/frame/support/src/traits/preimages.rs +++ b/substrate/frame/support/src/traits/preimages.rs @@ -17,6 +17,7 @@ //! Stuff for dealing with hashed preimages. +use alloc::borrow::Cow; use codec::{Decode, Encode, EncodeLike, MaxEncodedLen}; use scale_info::TypeInfo; use sp_core::RuntimeDebug; @@ -24,7 +25,6 @@ use sp_runtime::{ traits::{ConstU32, Hash}, DispatchError, }; -use sp_std::borrow::Cow; pub type BoundedInline = crate::BoundedVec>; @@ -37,7 +37,7 @@ pub enum Bounded { /// A hash with no preimage length. We do not support creation of this except /// for transitioning from legacy state. In the future we will make this a pure /// `Dummy` item storing only the final `dummy` field. - Legacy { hash: H::Output, dummy: sp_std::marker::PhantomData }, + Legacy { hash: H::Output, dummy: core::marker::PhantomData }, /// A an bounded `Call`. Its encoding must be at most 128 bytes. Inline(BoundedInline), /// A hash of the call together with an upper limit for its size.` @@ -61,7 +61,7 @@ impl Bounded { { use Bounded::*; match self { - Legacy { hash, .. } => Legacy { hash, dummy: sp_std::marker::PhantomData }, + Legacy { hash, .. } => Legacy { hash, dummy: core::marker::PhantomData }, Inline(x) => Inline(x), Lookup { hash, len } => Lookup { hash, len }, } @@ -123,7 +123,7 @@ impl Bounded { /// Constructs a `Legacy` bounded item. #[deprecated = "This API is only for transitioning to Scheduler v3 API"] pub fn from_legacy_hash(hash: impl Into) -> Self { - Self::Legacy { hash: hash.into(), dummy: sp_std::marker::PhantomData } + Self::Legacy { hash: hash.into(), dummy: core::marker::PhantomData } } } diff --git a/substrate/frame/support/src/traits/schedule.rs b/substrate/frame/support/src/traits/schedule.rs index f41c73fe69a8883d8d2ee8bb7ffcdf72bc2e5ba2..a302e28d4ce24fe4c6c1b7cc7a4fcb79d0e107c2 100644 --- a/substrate/frame/support/src/traits/schedule.rs +++ b/substrate/frame/support/src/traits/schedule.rs @@ -19,10 +19,11 @@ #[allow(deprecated)] use super::PreimageProvider; +use alloc::vec::Vec; use codec::{Codec, Decode, Encode, EncodeLike, MaxEncodedLen}; +use core::{fmt::Debug, result::Result}; use scale_info::TypeInfo; use sp_runtime::{traits::Saturating, DispatchError, RuntimeDebug}; -use sp_std::{fmt::Debug, prelude::*, result::Result}; /// Information relating to the period of a scheduled task. First item is the length of the /// period and the second is the number of times it should be executed in total before the task @@ -182,7 +183,7 @@ pub mod v1 { /// A type that can be used as a scheduler. pub trait Named { /// An address which can be used for removing a scheduled task. - type Address: Codec + Clone + Eq + EncodeLike + sp_std::fmt::Debug + MaxEncodedLen; + type Address: Codec + Clone + Eq + EncodeLike + core::fmt::Debug + MaxEncodedLen; /// Schedule a dispatch to happen at the beginning of some block in the future. /// @@ -353,7 +354,7 @@ pub mod v2 { /// A type that can be used as a scheduler. pub trait Named { /// An address which can be used for removing a scheduled task. - type Address: Codec + Clone + Eq + EncodeLike + sp_std::fmt::Debug + MaxEncodedLen; + type Address: Codec + Clone + Eq + EncodeLike + core::fmt::Debug + MaxEncodedLen; /// A means of expressing a call by the hash of its encoded data. type Hash; @@ -448,7 +449,7 @@ pub mod v3 { /// A type that can be used as a scheduler. pub trait Named { /// An address which can be used for removing a scheduled task. - type Address: Codec + MaxEncodedLen + Clone + Eq + EncodeLike + sp_std::fmt::Debug; + type Address: Codec + MaxEncodedLen + Clone + Eq + EncodeLike + core::fmt::Debug; /// The hasher used in the runtime. type Hasher: sp_runtime::traits::Hash; diff --git a/substrate/frame/support/src/traits/storage.rs b/substrate/frame/support/src/traits/storage.rs index 875ff56bea19e3c9f5770365833092da58fca6f4..22fb28e4c0e795e676b56d1b0a43834cf9e7b46b 100644 --- a/substrate/frame/support/src/traits/storage.rs +++ b/substrate/frame/support/src/traits/storage.rs @@ -17,6 +17,7 @@ //! Traits for encoding data related to pallet's storage items. +use alloc::{collections::btree_set::BTreeSet, vec, vec::Vec}; use codec::{Encode, FullCodec, MaxEncodedLen}; use core::marker::PhantomData; use impl_trait_for_tuples::impl_for_tuples; @@ -27,7 +28,6 @@ use sp_runtime::{ traits::{Convert, Member, Saturating}, DispatchError, RuntimeDebug, }; -use sp_std::{collections::btree_set::BTreeSet, prelude::*}; /// An instance of a pallet in the storage. /// diff --git a/substrate/frame/support/src/traits/tasks.rs b/substrate/frame/support/src/traits/tasks.rs index 42b837e55970def3c4d99f3c5f3cc9ca5dacaaf3..0b5d0c082509d1ca61c83b6ceaf05f8ab54918ac 100644 --- a/substrate/frame/support/src/traits/tasks.rs +++ b/substrate/frame/support/src/traits/tasks.rs @@ -18,20 +18,22 @@ //! Contains the [`Task`] trait, which defines a general-purpose way for defining and executing //! service work, and supporting types. +use alloc::{vec, vec::IntoIter}; use codec::FullCodec; +use core::{fmt::Debug, iter::Iterator}; use scale_info::TypeInfo; use sp_runtime::DispatchError; -use sp_std::{fmt::Debug, iter::Iterator, vec, vec::IntoIter}; use sp_weights::Weight; /// Contain's re-exports of all the supporting types for the [`Task`] trait. Used in the macro /// expansion of `RuntimeTask`. #[doc(hidden)] pub mod __private { + pub use alloc::{vec, vec::IntoIter}; pub use codec::FullCodec; + pub use core::{fmt::Debug, iter::Iterator}; pub use scale_info::TypeInfo; pub use sp_runtime::DispatchError; - pub use sp_std::{fmt::Debug, iter::Iterator, vec, vec::IntoIter}; pub use sp_weights::Weight; } diff --git a/substrate/frame/support/src/traits/tokens/currency/reservable.rs b/substrate/frame/support/src/traits/tokens/currency/reservable.rs index ff8b0c6eea838e8ec3cd5869190bf741ca140d65..60ea9a71805fcfb9068561dc23a073d3f6271e4b 100644 --- a/substrate/frame/support/src/traits/tokens/currency/reservable.rs +++ b/substrate/frame/support/src/traits/tokens/currency/reservable.rs @@ -242,7 +242,7 @@ pub trait NamedReservableCurrency: ReservableCurrency { /// /// All "anonymous" operations are then implemented as their named counterparts with the given `Id`. pub struct WithName( - sp_std::marker::PhantomData<(NamedReservable, Id, AccountId)>, + core::marker::PhantomData<(NamedReservable, Id, AccountId)>, ); impl< NamedReservable: NamedReservableCurrency, diff --git a/substrate/frame/support/src/traits/tokens/fungible/imbalance.rs b/substrate/frame/support/src/traits/tokens/fungible/imbalance.rs index 020dffe28c85b7a0f1bb213173342e4dd9e907d7..41907b2aa009d42aceae6b5eb3b69fd4a2fc9989 100644 --- a/substrate/frame/support/src/traits/tokens/fungible/imbalance.rs +++ b/substrate/frame/support/src/traits/tokens/fungible/imbalance.rs @@ -26,9 +26,9 @@ use crate::traits::{ misc::{SameOrOther, TryDrop}, tokens::{AssetId, Balance}, }; +use core::marker::PhantomData; use frame_support_procedural::{EqNoBound, PartialEqNoBound, RuntimeDebugNoBound}; use sp_runtime::traits::Zero; -use sp_std::marker::PhantomData; /// Handler for when an imbalance gets dropped. This could handle either a credit (negative) or /// debt (positive) imbalance. @@ -93,7 +93,7 @@ impl, OppositeOnDrop: HandleImbalance /// Forget the imbalance without invoking the on-drop handler. pub(crate) fn forget(imbalance: Self) { - sp_std::mem::forget(imbalance); + core::mem::forget(imbalance); } } @@ -108,7 +108,7 @@ impl, OppositeOnDrop: HandleImbalance fn drop_zero(self) -> Result<(), Self> { if self.amount.is_zero() { - sp_std::mem::forget(self); + core::mem::forget(self); Ok(()) } else { Err(self) @@ -118,7 +118,7 @@ impl, OppositeOnDrop: HandleImbalance fn split(self, amount: B) -> (Self, Self) { let first = self.amount.min(amount); let second = self.amount - first; - sp_std::mem::forget(self); + core::mem::forget(self); (Imbalance::new(first), Imbalance::new(second)) } @@ -130,19 +130,19 @@ impl, OppositeOnDrop: HandleImbalance fn merge(mut self, other: Self) -> Self { self.amount = self.amount.saturating_add(other.amount); - sp_std::mem::forget(other); + core::mem::forget(other); self } fn subsume(&mut self, other: Self) { self.amount = self.amount.saturating_add(other.amount); - sp_std::mem::forget(other); + core::mem::forget(other); } fn offset( self, other: Imbalance, ) -> SameOrOther> { let (a, b) = (self.amount, other.amount); - sp_std::mem::forget((self, other)); + core::mem::forget((self, other)); if a == b { SameOrOther::None diff --git a/substrate/frame/support/src/traits/tokens/fungible/item_of.rs b/substrate/frame/support/src/traits/tokens/fungible/item_of.rs index 2aa53d622dbff7280cb4f2b742f490249c73ca69..c9f366911a8b62932ffbbb757d13e72a31b3c718 100644 --- a/substrate/frame/support/src/traits/tokens/fungible/item_of.rs +++ b/substrate/frame/support/src/traits/tokens/fungible/item_of.rs @@ -39,7 +39,7 @@ pub struct ItemOf< F: fungibles::Inspect, A: Get<>::AssetId>, AccountId, ->(sp_std::marker::PhantomData<(F, A, AccountId)>); +>(core::marker::PhantomData<(F, A, AccountId)>); impl< F: fungibles::Inspect, @@ -361,7 +361,7 @@ impl< } pub struct ConvertImbalanceDropHandler( - sp_std::marker::PhantomData<(AccountId, Balance, AssetIdType, AssetId, Handler)>, + core::marker::PhantomData<(AccountId, Balance, AssetIdType, AssetId, Handler)>, ); impl< diff --git a/substrate/frame/support/src/traits/tokens/fungible/mod.rs b/substrate/frame/support/src/traits/tokens/fungible/mod.rs index a113cb01c982dd8f35c9ab28ead961a65219cd71..f40e494b930d5f836c47b2700d4ff58b336c7fea 100644 --- a/substrate/frame/support/src/traits/tokens/fungible/mod.rs +++ b/substrate/frame/support/src/traits/tokens/fungible/mod.rs @@ -65,7 +65,7 @@ //! "stack". This means that if an account has 3 freezes for 100 units, the account can spend its //! funds for any reason down to 100 units, at which point the freezes will start to come into //! play. -//! +//! //! It's important to note that the frozen balance can exceed the total balance of the account. //! This is useful, eg, in cases where you want to prevent a user from transferring any fund. In //! such a case, setting the frozen balance to `Balance::MAX` would serve that purpose @@ -161,9 +161,9 @@ mod regular; mod union_of; use codec::{Decode, Encode, MaxEncodedLen}; +use core::marker::PhantomData; use frame_support_procedural::{CloneNoBound, EqNoBound, PartialEqNoBound, RuntimeDebugNoBound}; use scale_info::TypeInfo; -use sp_std::marker::PhantomData; use super::{ Fortitude::{Force, Polite}, diff --git a/substrate/frame/support/src/traits/tokens/fungible/regular.rs b/substrate/frame/support/src/traits/tokens/fungible/regular.rs index c46614be4734c659d50619fde3734a34be14783e..54a04444649d2715938d7e6a60400527dc952ceb 100644 --- a/substrate/frame/support/src/traits/tokens/fungible/regular.rs +++ b/substrate/frame/support/src/traits/tokens/fungible/regular.rs @@ -36,9 +36,9 @@ use crate::{ SameOrOther, TryDrop, }, }; +use core::marker::PhantomData; use sp_arithmetic::traits::{CheckedAdd, CheckedSub, One}; use sp_runtime::{traits::Saturating, ArithmeticError, DispatchError, TokenError}; -use sp_std::marker::PhantomData; use super::{Credit, Debt, HandleImbalanceDrop, Imbalance}; diff --git a/substrate/frame/support/src/traits/tokens/fungible/union_of.rs b/substrate/frame/support/src/traits/tokens/fungible/union_of.rs index 63791b05223701ae8c689f00c4769cb510c6e208..3adbbdda31431ee1f7b8e7646825bee1964131f7 100644 --- a/substrate/frame/support/src/traits/tokens/fungible/union_of.rs +++ b/substrate/frame/support/src/traits/tokens/fungible/union_of.rs @@ -21,6 +21,7 @@ //! See the [`crate::traits::fungible`] doc for more information about fungible traits. use codec::{Decode, Encode, MaxEncodedLen}; +use core::cmp::Ordering; use frame_support::traits::{ fungible::imbalance, tokens::{ @@ -36,7 +37,6 @@ use sp_runtime::{ Either::{Left, Right}, RuntimeDebug, }; -use sp_std::cmp::Ordering; /// The `NativeOrWithId` enum classifies an asset as either `Native` to the current chain or as an /// asset with a specific ID. @@ -101,7 +101,7 @@ impl Convert, Either<(), AssetId>> for Nat /// - `AssetKind` is a superset type encompassing asset kinds from `Left` and `Right` sets. /// - `AccountId` is an account identifier type. pub struct UnionOf( - sp_std::marker::PhantomData<(Left, Right, Criterion, AssetKind, AccountId)>, + core::marker::PhantomData<(Left, Right, Criterion, AssetKind, AccountId)>, ); impl< @@ -664,7 +664,7 @@ pub struct ConvertImbalanceDropHandler< Balance, AssetId, AccountId, ->(sp_std::marker::PhantomData<(Left, Right, Criterion, AssetKind, Balance, AssetId, AccountId)>); +>(core::marker::PhantomData<(Left, Right, Criterion, AssetKind, Balance, AssetId, AccountId)>); impl< Left: fungible::HandleImbalanceDrop, diff --git a/substrate/frame/support/src/traits/tokens/fungibles/imbalance.rs b/substrate/frame/support/src/traits/tokens/fungibles/imbalance.rs index bb0d83721a481e11f80f1ae9fa75292528f7c8a0..c3b213cc8fc86eae3c2d9704e369b307211c84d4 100644 --- a/substrate/frame/support/src/traits/tokens/fungibles/imbalance.rs +++ b/substrate/frame/support/src/traits/tokens/fungibles/imbalance.rs @@ -26,9 +26,9 @@ use crate::traits::{ misc::{SameOrOther, TryDrop}, tokens::{imbalance::Imbalance as ImbalanceT, AssetId, Balance}, }; +use core::marker::PhantomData; use frame_support_procedural::{EqNoBound, PartialEqNoBound, RuntimeDebugNoBound}; use sp_runtime::traits::Zero; -use sp_std::marker::PhantomData; /// Handler for when an imbalance gets dropped. This could handle either a credit (negative) or /// debt (positive) imbalance. @@ -98,12 +98,12 @@ impl< /// Forget the imbalance without invoking the on-drop handler. pub(crate) fn forget(imbalance: Self) { - sp_std::mem::forget(imbalance); + core::mem::forget(imbalance); } pub fn drop_zero(self) -> Result<(), Self> { if self.amount.is_zero() { - sp_std::mem::forget(self); + core::mem::forget(self); Ok(()) } else { Err(self) @@ -114,7 +114,7 @@ impl< let first = self.amount.min(amount); let second = self.amount - first; let asset = self.asset.clone(); - sp_std::mem::forget(self); + core::mem::forget(self); (Imbalance::new(asset.clone(), first), Imbalance::new(asset, second)) } @@ -129,7 +129,7 @@ impl< pub fn merge(mut self, other: Self) -> Result { if self.asset == other.asset { self.amount = self.amount.saturating_add(other.amount); - sp_std::mem::forget(other); + core::mem::forget(other); Ok(self) } else { Err((self, other)) @@ -138,7 +138,7 @@ impl< pub fn subsume(&mut self, other: Self) -> Result<(), Self> { if self.asset == other.asset { self.amount = self.amount.saturating_add(other.amount); - sp_std::mem::forget(other); + core::mem::forget(other); Ok(()) } else { Err(other) @@ -154,7 +154,7 @@ impl< if self.asset == other.asset { let (a, b) = (self.amount, other.amount); let asset = self.asset.clone(); - sp_std::mem::forget((self, other)); + core::mem::forget((self, other)); if a == b { Ok(SameOrOther::None) diff --git a/substrate/frame/support/src/traits/tokens/fungibles/metadata.rs b/substrate/frame/support/src/traits/tokens/fungibles/metadata.rs index ab722426dadf6fa759340ac12609e58c1139ff02..27f663e57509568846601ee260ba0d4190c24f37 100644 --- a/substrate/frame/support/src/traits/tokens/fungibles/metadata.rs +++ b/substrate/frame/support/src/traits/tokens/fungibles/metadata.rs @@ -20,7 +20,7 @@ //! See the [`crate::traits::fungibles`] doc for more information about fungibles traits. use crate::dispatch::DispatchResult; -use sp_std::vec::Vec; +use alloc::vec::Vec; pub trait Inspect: super::Inspect { // Get name for an AssetId. diff --git a/substrate/frame/support/src/traits/tokens/fungibles/regular.rs b/substrate/frame/support/src/traits/tokens/fungibles/regular.rs index 946c4756cff6035a7619cf859cb1d71d520b4298..3985da7856d75f424050310985893736b4b38c56 100644 --- a/substrate/frame/support/src/traits/tokens/fungibles/regular.rs +++ b/substrate/frame/support/src/traits/tokens/fungibles/regular.rs @@ -19,7 +19,7 @@ //! //! See the [`crate::traits::fungibles`] doc for more information about fungibles traits. -use sp_std::marker::PhantomData; +use core::marker::PhantomData; use crate::{ ensure, diff --git a/substrate/frame/support/src/traits/tokens/fungibles/union_of.rs b/substrate/frame/support/src/traits/tokens/fungibles/union_of.rs index f4259a78f0a25ae15c7413be07df0bc299342122..77047150e00cee0481eaf555e001bfe1a73be431 100644 --- a/substrate/frame/support/src/traits/tokens/fungibles/union_of.rs +++ b/substrate/frame/support/src/traits/tokens/fungibles/union_of.rs @@ -41,7 +41,7 @@ use sp_runtime::{ /// - `AssetKind` is a superset type encompassing asset kinds from `Left` and `Right` sets. /// - `AccountId` is an account identifier type. pub struct UnionOf( - sp_std::marker::PhantomData<(Left, Right, Criterion, AssetKind, AccountId)>, + core::marker::PhantomData<(Left, Right, Criterion, AssetKind, AccountId)>, ); impl< @@ -622,7 +622,7 @@ pub struct ConvertImbalanceDropHandler< Balance, AccountId, >( - sp_std::marker::PhantomData<( + core::marker::PhantomData<( Left, Right, LeftAssetId, diff --git a/substrate/frame/support/src/traits/tokens/imbalance/on_unbalanced.rs b/substrate/frame/support/src/traits/tokens/imbalance/on_unbalanced.rs index ecb8de8841f91ca65a05eca687da5eaa8164a4a2..4bf9af3fbb18693a745b69d97c8286eb80993bba 100644 --- a/substrate/frame/support/src/traits/tokens/imbalance/on_unbalanced.rs +++ b/substrate/frame/support/src/traits/tokens/imbalance/on_unbalanced.rs @@ -17,9 +17,9 @@ //! Trait for handling imbalances. +use core::marker::PhantomData; use frame_support::traits::{fungible, fungibles, misc::TryDrop}; use sp_core::TypedGet; -use sp_std::marker::PhantomData; /// Handler for when some currency "account" decreased in balance for /// some reason. diff --git a/substrate/frame/support/src/traits/tokens/imbalance/signed_imbalance.rs b/substrate/frame/support/src/traits/tokens/imbalance/signed_imbalance.rs index 03e821b161b694a554effc51c09292ea6df718c2..eec892cc31154c30b282101845c345efeeafe3f6 100644 --- a/substrate/frame/support/src/traits/tokens/imbalance/signed_imbalance.rs +++ b/substrate/frame/support/src/traits/tokens/imbalance/signed_imbalance.rs @@ -20,8 +20,8 @@ use super::super::imbalance::Imbalance; use crate::traits::misc::SameOrOther; use codec::FullCodec; +use core::fmt::Debug; use sp_runtime::traits::{AtLeast32BitUnsigned, MaybeSerializeDeserialize}; -use sp_std::fmt::Debug; /// Either a positive or a negative imbalance. pub enum SignedImbalance> { diff --git a/substrate/frame/support/src/traits/tokens/imbalance/split_two_ways.rs b/substrate/frame/support/src/traits/tokens/imbalance/split_two_ways.rs index 59a582389ba61f3eb65fbc7f3710b1edba0a56ab..d79ae562ec6765d008072b1be87385640f65182d 100644 --- a/substrate/frame/support/src/traits/tokens/imbalance/split_two_ways.rs +++ b/substrate/frame/support/src/traits/tokens/imbalance/split_two_ways.rs @@ -18,8 +18,8 @@ //! Means for splitting an imbalance into two and handling them differently. use super::super::imbalance::{Imbalance, OnUnbalanced}; +use core::{marker::PhantomData, ops::Div}; use sp_runtime::traits::Saturating; -use sp_std::{marker::PhantomData, ops::Div}; /// Split an unbalanced amount two ways between a common divisor. pub struct SplitTwoWays( diff --git a/substrate/frame/support/src/traits/tokens/misc.rs b/substrate/frame/support/src/traits/tokens/misc.rs index e1ff1e058ae7aabd8ce9e0725b51f292c406a1a5..9fa1df862097f48e9555f27ad097b84e9ee30021 100644 --- a/substrate/frame/support/src/traits/tokens/misc.rs +++ b/substrate/frame/support/src/traits/tokens/misc.rs @@ -19,13 +19,13 @@ use crate::{traits::Contains, TypeInfo}; use codec::{Decode, Encode, FullCodec, MaxEncodedLen}; +use core::fmt::Debug; use sp_arithmetic::traits::{AtLeast32BitUnsigned, Zero}; use sp_core::RuntimeDebug; use sp_runtime::{ traits::{Convert, MaybeSerializeDeserialize}, ArithmeticError, DispatchError, TokenError, }; -use sp_std::fmt::Debug; /// The origin of funds to be used for a deposit operation. #[derive(Copy, Clone, RuntimeDebug, Eq, PartialEq)] @@ -351,7 +351,7 @@ pub trait GetSalary { } /// Adapter for a rank-to-salary `Convert` implementation into a `GetSalary` implementation. -pub struct ConvertRank(sp_std::marker::PhantomData); +pub struct ConvertRank(core::marker::PhantomData); impl> GetSalary for ConvertRank { fn get_salary(rank: R, _: &A) -> B { C::convert(rank) diff --git a/substrate/frame/support/src/traits/tokens/nonfungible.rs b/substrate/frame/support/src/traits/tokens/nonfungible.rs index e3fc84f1d57b2cf1d47a01a81eb13478a6e8830b..249f84b22759317f928a7fa7b76106c813f049a9 100644 --- a/substrate/frame/support/src/traits/tokens/nonfungible.rs +++ b/substrate/frame/support/src/traits/tokens/nonfungible.rs @@ -26,9 +26,9 @@ use super::nonfungibles; use crate::{dispatch::DispatchResult, traits::Get}; +use alloc::vec::Vec; use codec::{Decode, Encode}; use sp_runtime::TokenError; -use sp_std::prelude::*; /// Trait for providing an interface to a read-only NFT-like set of items. pub trait Inspect { @@ -125,7 +125,7 @@ pub struct ItemOf< F: nonfungibles::Inspect, A: Get<>::CollectionId>, AccountId, ->(sp_std::marker::PhantomData<(F, A, AccountId)>); +>(core::marker::PhantomData<(F, A, AccountId)>); impl< F: nonfungibles::Inspect, diff --git a/substrate/frame/support/src/traits/tokens/nonfungible_v2.rs b/substrate/frame/support/src/traits/tokens/nonfungible_v2.rs index 05f76e2859d2ead6b998d0c63304e2fa818db7a2..5775162e34ed0e0e07c36ee610ccf2cf7da2b6bd 100644 --- a/substrate/frame/support/src/traits/tokens/nonfungible_v2.rs +++ b/substrate/frame/support/src/traits/tokens/nonfungible_v2.rs @@ -29,9 +29,9 @@ use crate::{ dispatch::{DispatchResult, Parameter}, traits::Get, }; +use alloc::vec::Vec; use codec::{Decode, Encode}; use sp_runtime::TokenError; -use sp_std::prelude::*; /// Trait for providing an interface to a read-only NFT-like item. pub trait Inspect { @@ -207,7 +207,7 @@ pub struct ItemOf< F: nonfungibles::Inspect, A: Get<>::CollectionId>, AccountId, ->(sp_std::marker::PhantomData<(F, A, AccountId)>); +>(core::marker::PhantomData<(F, A, AccountId)>); impl< F: nonfungibles::Inspect, diff --git a/substrate/frame/support/src/traits/tokens/nonfungibles.rs b/substrate/frame/support/src/traits/tokens/nonfungibles.rs index 615e79c29c85f4ccef502e2e50a0ecfd56a3c909..22358cf806fb1af2a8fe0f952145216e8a431dbe 100644 --- a/substrate/frame/support/src/traits/tokens/nonfungibles.rs +++ b/substrate/frame/support/src/traits/tokens/nonfungibles.rs @@ -28,9 +28,9 @@ //! `nonfungible` traits by using the `nonfungible::ItemOf` type adapter. use crate::dispatch::DispatchResult; +use alloc::vec::Vec; use codec::{Decode, Encode}; use sp_runtime::{DispatchError, TokenError}; -use sp_std::prelude::*; /// Trait for providing an interface to many read-only NFT-like sets of items. pub trait Inspect { diff --git a/substrate/frame/support/src/traits/tokens/nonfungibles_v2.rs b/substrate/frame/support/src/traits/tokens/nonfungibles_v2.rs index c0209b6d5123dbefb8e813d11f6478b00c9e82bb..edf1c2b8023df0a2683cf999615667372d0af9da 100644 --- a/substrate/frame/support/src/traits/tokens/nonfungibles_v2.rs +++ b/substrate/frame/support/src/traits/tokens/nonfungibles_v2.rs @@ -28,9 +28,9 @@ //! `nonfungible` traits by using the `nonfungible::ItemOf` type adapter. use crate::dispatch::{DispatchResult, Parameter}; +use alloc::vec::Vec; use codec::{Decode, Encode}; use sp_runtime::{DispatchError, TokenError}; -use sp_std::prelude::*; /// Trait for providing an interface to many read-only NFT-like sets of items. pub trait Inspect { diff --git a/substrate/frame/support/src/traits/tokens/pay.rs b/substrate/frame/support/src/traits/tokens/pay.rs index 62d7a056a3f1bfcf950897ce48598c9b9f67fbc6..5a7ed4d6aa130ebc87399ecd8d7f19a805d95966 100644 --- a/substrate/frame/support/src/traits/tokens/pay.rs +++ b/substrate/frame/support/src/traits/tokens/pay.rs @@ -18,10 +18,10 @@ //! The Pay trait and associated types. use codec::{Decode, Encode, FullCodec, MaxEncodedLen}; +use core::fmt::Debug; use scale_info::TypeInfo; use sp_core::{RuntimeDebug, TypedGet}; use sp_runtime::DispatchError; -use sp_std::fmt::Debug; use super::{fungible, fungibles, Balance, Preservation::Expendable}; diff --git a/substrate/frame/support/src/traits/try_runtime/decode_entire_state.rs b/substrate/frame/support/src/traits/try_runtime/decode_entire_state.rs index d5dc93fcf28fe32046c8895aad8775911937c681..8dbeecd8e860eeaaacbaf4edb5a6f098e9d19d39 100644 --- a/substrate/frame/support/src/traits/try_runtime/decode_entire_state.rs +++ b/substrate/frame/support/src/traits/try_runtime/decode_entire_state.rs @@ -26,10 +26,10 @@ use crate::{ traits::{PartialStorageInfoTrait, StorageInfo}, StorageHasher, }; +use alloc::{vec, vec::Vec}; use codec::{Decode, DecodeAll, FullCodec}; use impl_trait_for_tuples::impl_for_tuples; use sp_core::Get; -use sp_std::prelude::*; /// Decode the entire data under the given storage type. /// @@ -82,8 +82,8 @@ impl core::fmt::Display for TryDecodeEntireStorageError { write!( f, "`{}::{}` key `{}` is undecodable", - &sp_std::str::from_utf8(&self.info.pallet_name).unwrap_or(""), - &sp_std::str::from_utf8(&self.info.storage_name).unwrap_or(""), + &alloc::str::from_utf8(&self.info.pallet_name).unwrap_or(""), + &alloc::str::from_utf8(&self.info.storage_name).unwrap_or(""), array_bytes::bytes2hex("0x", &self.key) ) } diff --git a/substrate/frame/support/src/traits/try_runtime/mod.rs b/substrate/frame/support/src/traits/try_runtime/mod.rs index c1bf1feb19e54fe3c94abfb242e9f2321d43d0df..09c33c01440677e14eacbd92063f7ffafb267c71 100644 --- a/substrate/frame/support/src/traits/try_runtime/mod.rs +++ b/substrate/frame/support/src/traits/try_runtime/mod.rs @@ -22,10 +22,10 @@ pub use decode_entire_state::{TryDecodeEntireStorage, TryDecodeEntireStorageErro use super::StorageInstance; +use alloc::vec::Vec; use impl_trait_for_tuples::impl_for_tuples; use sp_arithmetic::traits::AtLeast32BitUnsigned; use sp_runtime::TryRuntimeError; -use sp_std::prelude::*; /// Which state tests to execute. #[derive(codec::Encode, codec::Decode, Clone, scale_info::TypeInfo)] @@ -55,15 +55,15 @@ impl Default for Select { } } -impl sp_std::fmt::Debug for Select { - fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { +impl core::fmt::Debug for Select { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { match self { Select::RoundRobin(x) => write!(f, "RoundRobin({})", x), Select::Only(x) => write!( f, "Only({:?})", x.iter() - .map(|x| sp_std::str::from_utf8(x).unwrap_or("")) + .map(|x| alloc::str::from_utf8(x).unwrap_or("")) .collect::>(), ), Select::All => write!(f, "All"), @@ -73,7 +73,7 @@ impl sp_std::fmt::Debug for Select { } #[cfg(feature = "std")] -impl sp_std::str::FromStr for Select { +impl std::str::FromStr for Select { type Err = &'static str; fn from_str(s: &str) -> Result { match s { @@ -153,9 +153,7 @@ pub trait TryState { #[cfg_attr(all(not(feature = "tuples-96"), not(feature = "tuples-128")), impl_for_tuples(64))] #[cfg_attr(all(feature = "tuples-96", not(feature = "tuples-128")), impl_for_tuples(96))] #[cfg_attr(all(feature = "tuples-128"), impl_for_tuples(128))] -impl TryState - for Tuple -{ +impl TryState for Tuple { for_tuples!( where #( Tuple: crate::traits::PalletInfoAccess )* ); fn try_state(n: BlockNumber, targets: Select) -> Result<(), TryRuntimeError> { match targets { @@ -221,7 +219,7 @@ impl TryState { /// Initializes a new tally. @@ -74,7 +74,7 @@ impl PollStatus { } } -pub struct ClassCountOf(sp_std::marker::PhantomData<(P, T)>); +pub struct ClassCountOf(core::marker::PhantomData<(P, T)>); impl> sp_runtime::traits::Get for ClassCountOf { fn get() -> u32 { P::classes().len() as u32 diff --git a/substrate/frame/support/test/Cargo.toml b/substrate/frame/support/test/Cargo.toml index 697e14ae1d38893428f19f41aec441c19cfd1711..82ac1d2c7475bb9761d3d4891f3ed11dd296b7cf 100644 --- a/substrate/frame/support/test/Cargo.toml +++ b/substrate/frame/support/test/Cargo.toml @@ -28,7 +28,6 @@ frame-support = { features = ["experimental"], workspace = true } frame-benchmarking = { workspace = true } sp-runtime = { workspace = true } sp-core = { workspace = true } -sp-std = { workspace = true } sp-version = { workspace = true } sp-metadata-ir = { workspace = true } trybuild = { features = ["diff"], workspace = true } @@ -57,7 +56,6 @@ std = [ "sp-metadata-ir/std", "sp-runtime/std", "sp-state-machine/std", - "sp-std/std", "sp-version/std", "test-pallet/std", ] diff --git a/substrate/frame/support/test/src/lib.rs b/substrate/frame/support/test/src/lib.rs index a8a723375033a48e10e3f7f2941bb025991ac869..b080740b0a4b1116e5f69790d3795a14befdf34b 100644 --- a/substrate/frame/support/test/src/lib.rs +++ b/substrate/frame/support/test/src/lib.rs @@ -127,7 +127,7 @@ pub mod pallet_prelude { /// Provides an implementation of [`frame_support::traits::Randomness`] that should only be used in /// tests! -pub struct TestRandomness(sp_std::marker::PhantomData); +pub struct TestRandomness(core::marker::PhantomData); impl frame_support::traits::Randomness> for TestRandomness diff --git a/substrate/frame/support/test/tests/issue2219.rs b/substrate/frame/support/test/tests/issue2219.rs index 20c2773406ff111ebd03d08a89924ddf30cccdba..7a2138d056a09a5373ae5beead9d0d7a1fd67c0e 100644 --- a/substrate/frame/support/test/tests/issue2219.rs +++ b/substrate/frame/support/test/tests/issue2219.rs @@ -139,7 +139,7 @@ mod module { pub enable_storage_role: bool, pub request_life_time: u64, #[serde(skip)] - pub _config: sp_std::marker::PhantomData, + pub _config: core::marker::PhantomData, } #[pallet::genesis_build] diff --git a/substrate/frame/support/test/tests/origin.rs b/substrate/frame/support/test/tests/origin.rs index 4f14bda184c867b54aa10246a995943835abf375..e6dd0cfc0e31596a868b5e0958b98af8a59e7b52 100644 --- a/substrate/frame/support/test/tests/origin.rs +++ b/substrate/frame/support/test/tests/origin.rs @@ -65,7 +65,7 @@ mod nested { #[derive(frame_support::DefaultNoBound)] pub struct GenesisConfig { #[serde(skip)] - pub _config: sp_std::marker::PhantomData, + pub _config: core::marker::PhantomData, } #[pallet::genesis_build] @@ -135,7 +135,7 @@ pub mod module { #[derive(frame_support::DefaultNoBound)] pub struct GenesisConfig { #[serde(skip)] - pub _config: sp_std::marker::PhantomData, + pub _config: core::marker::PhantomData, } #[pallet::genesis_build] diff --git a/substrate/frame/support/test/tests/pallet.rs b/substrate/frame/support/test/tests/pallet.rs index c441d4c371af0926a0508025ae5473c77fb98346..6f8af949cc313f8826d06b8934ba13b7993d0693 100644 --- a/substrate/frame/support/test/tests/pallet.rs +++ b/substrate/frame/support/test/tests/pallet.rs @@ -446,7 +446,7 @@ pub mod pallet { T::AccountId: From + SomeAssociation1 + From, { #[serde(skip)] - _config: sp_std::marker::PhantomData, + _config: core::marker::PhantomData, _myfield: u32, } diff --git a/substrate/frame/support/test/tests/pallet_instance.rs b/substrate/frame/support/test/tests/pallet_instance.rs index dfe4caa476d3b9e1fa2a1024adb48eea5cdf9be9..09a49617044da4a24b3adc4607a8c0c4b144f6e8 100644 --- a/substrate/frame/support/test/tests/pallet_instance.rs +++ b/substrate/frame/support/test/tests/pallet_instance.rs @@ -15,6 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. +use core::any::TypeId; use frame_support::{ derive_impl, dispatch::{DispatchClass, DispatchInfo, GetDispatchInfo, Pays}, @@ -33,7 +34,6 @@ use sp_io::{ TestExternalities, }; use sp_runtime::{DispatchError, ModuleError}; -use sp_std::any::TypeId; #[frame_support::pallet(dev_mode)] pub mod pallet { @@ -194,7 +194,7 @@ pub mod pallet { #[derive(frame_support::DefaultNoBound)] pub struct GenesisConfig, I: 'static = ()> { #[serde(skip)] - _config: sp_std::marker::PhantomData<(T, I)>, + _config: core::marker::PhantomData<(T, I)>, _myfield: u32, } diff --git a/substrate/frame/support/test/tests/runtime.rs b/substrate/frame/support/test/tests/runtime.rs index 1f4d9110a24fc4e8f18fec0f1d7e2b714f920fa4..06c2b5b7071c1357b3b6bfb1b699662fc10f0c20 100644 --- a/substrate/frame/support/test/tests/runtime.rs +++ b/substrate/frame/support/test/tests/runtime.rs @@ -169,7 +169,7 @@ mod nested { #[derive(frame_support::DefaultNoBound)] pub struct GenesisConfig { #[serde(skip)] - pub _config: sp_std::marker::PhantomData, + pub _config: core::marker::PhantomData, } #[pallet::genesis_build] @@ -251,7 +251,7 @@ pub mod module3 { #[derive(frame_support::DefaultNoBound)] pub struct GenesisConfig { #[serde(skip)] - pub _config: sp_std::marker::PhantomData, + pub _config: core::marker::PhantomData, } #[pallet::genesis_build] @@ -871,7 +871,7 @@ fn test_metadata() { PalletMetadata { name: "Module3", storage: Some(PalletStorageMetadata { - prefix: "Module3", + prefix: "Module3", entries: vec![ StorageEntryMetadata { name: "Storage", diff --git a/substrate/frame/support/test/tests/runtime_legacy_ordering.rs b/substrate/frame/support/test/tests/runtime_legacy_ordering.rs index 6330a138e2f2a66a5b763ecd57d1c742fa092465..4233db21e2031baf136bed1e6317bf244d3b21b8 100644 --- a/substrate/frame/support/test/tests/runtime_legacy_ordering.rs +++ b/substrate/frame/support/test/tests/runtime_legacy_ordering.rs @@ -169,7 +169,7 @@ mod nested { #[derive(frame_support::DefaultNoBound)] pub struct GenesisConfig { #[serde(skip)] - pub _config: sp_std::marker::PhantomData, + pub _config: core::marker::PhantomData, } #[pallet::genesis_build] @@ -251,7 +251,7 @@ pub mod module3 { #[derive(frame_support::DefaultNoBound)] pub struct GenesisConfig { #[serde(skip)] - pub _config: sp_std::marker::PhantomData, + pub _config: core::marker::PhantomData, } #[pallet::genesis_build] @@ -808,7 +808,7 @@ fn test_metadata() { PalletMetadata { name: "Module3", storage: Some(PalletStorageMetadata { - prefix: "Module3", + prefix: "Module3", entries: vec![ StorageEntryMetadata { name: "Storage", diff --git a/substrate/frame/support/test/tests/versioned_migration.rs b/substrate/frame/support/test/tests/versioned_migration.rs index c83dd6b71de9b3c72ee8c3f9b00cd81fecb0dfde..58c9e4ce93b58453f942e872fccd3a48a6c997f9 100644 --- a/substrate/frame/support/test/tests/versioned_migration.rs +++ b/substrate/frame/support/test/tests/versioned_migration.rs @@ -51,7 +51,7 @@ mod dummy_pallet { #[derive(frame_support::DefaultNoBound)] pub struct GenesisConfig { #[serde(skip)] - _config: sp_std::marker::PhantomData, + _config: core::marker::PhantomData, } #[pallet::genesis_build] @@ -90,7 +90,7 @@ pub(crate) fn new_test_ext() -> sp_io::TestExternalities { /// A dummy migration for testing the `VersionedMigration` trait. /// Sets SomeStorage to S. -struct SomeUnversionedMigration(sp_std::marker::PhantomData); +struct SomeUnversionedMigration(core::marker::PhantomData); parameter_types! { const UpgradeReads: u64 = 4; diff --git a/substrate/frame/system/benchmarking/Cargo.toml b/substrate/frame/system/benchmarking/Cargo.toml index 47a6721b93f585bf3b5c0f6a777327ade4f38be6..dec68d20b69954d3d3c4eb7a7af2b9d724169b50 100644 --- a/substrate/frame/system/benchmarking/Cargo.toml +++ b/substrate/frame/system/benchmarking/Cargo.toml @@ -23,7 +23,6 @@ frame-support = { workspace = true } frame-system = { workspace = true } sp-core = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] sp-io = { workspace = true, default-features = true } @@ -42,7 +41,6 @@ std = [ "sp-externalities/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", "sp-version/std", ] diff --git a/substrate/frame/system/benchmarking/src/inner.rs b/substrate/frame/system/benchmarking/src/inner.rs index c1631b0a2e334e985c9b0ab8a87f1a318548dab1..0fb592f3dbba7c2ce137c05d6b5e51c825ba61e8 100644 --- a/substrate/frame/system/benchmarking/src/inner.rs +++ b/substrate/frame/system/benchmarking/src/inner.rs @@ -17,13 +17,13 @@ //! Frame System benchmarks. +use alloc::{vec, vec::Vec}; use codec::Encode; use frame_benchmarking::v2::*; use frame_support::{dispatch::DispatchClass, storage, traits::Get}; use frame_system::{Call, Pallet as System, RawOrigin}; use sp_core::storage::well_known_keys; use sp_runtime::traits::Hash; -use sp_std::{prelude::*, vec}; pub struct Pallet(System); pub trait Config: frame_system::Config { diff --git a/substrate/frame/system/benchmarking/src/lib.rs b/substrate/frame/system/benchmarking/src/lib.rs index e55038aeb9551f1bbee2f38371b1e0c63371cce5..f66d20ac8aed928521f6021cded6cd9c93110f49 100644 --- a/substrate/frame/system/benchmarking/src/lib.rs +++ b/substrate/frame/system/benchmarking/src/lib.rs @@ -19,6 +19,8 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + #[cfg(feature = "runtime-benchmarks")] pub mod inner; diff --git a/substrate/frame/system/src/extensions/check_genesis.rs b/substrate/frame/system/src/extensions/check_genesis.rs index 76a711a823e7d7a4b1092d9220b846584b21603f..000ec56da64f3f96eaf521ed6510b17020ce81fe 100644 --- a/substrate/frame/system/src/extensions/check_genesis.rs +++ b/substrate/frame/system/src/extensions/check_genesis.rs @@ -31,16 +31,16 @@ use sp_runtime::{ /// the extension does not affect any other fields of `TransactionValidity` directly. #[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo)] #[scale_info(skip_type_params(T))] -pub struct CheckGenesis(sp_std::marker::PhantomData); +pub struct CheckGenesis(core::marker::PhantomData); -impl sp_std::fmt::Debug for CheckGenesis { +impl core::fmt::Debug for CheckGenesis { #[cfg(feature = "std")] - fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { write!(f, "CheckGenesis") } #[cfg(not(feature = "std"))] - fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, _: &mut core::fmt::Formatter) -> core::fmt::Result { Ok(()) } } @@ -48,7 +48,7 @@ impl sp_std::fmt::Debug for CheckGenesis { impl CheckGenesis { /// Creates new `SignedExtension` to check genesis hash. pub fn new() -> Self { - Self(sp_std::marker::PhantomData) + Self(core::marker::PhantomData) } } diff --git a/substrate/frame/system/src/extensions/check_mortality.rs b/substrate/frame/system/src/extensions/check_mortality.rs index 31fdbba5950e21ceecb8b29ae50934d52f194903..6666c4812fbc383e48b6e11b6b8c5c286d126c5d 100644 --- a/substrate/frame/system/src/extensions/check_mortality.rs +++ b/substrate/frame/system/src/extensions/check_mortality.rs @@ -36,23 +36,23 @@ use sp_runtime::{ /// The extension affects `longevity` of the transaction according to the [`Era`] definition. #[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo)] #[scale_info(skip_type_params(T))] -pub struct CheckMortality(pub Era, sp_std::marker::PhantomData); +pub struct CheckMortality(pub Era, core::marker::PhantomData); impl CheckMortality { /// utility constructor. Used only in client/factory code. pub fn from(era: Era) -> Self { - Self(era, sp_std::marker::PhantomData) + Self(era, core::marker::PhantomData) } } -impl sp_std::fmt::Debug for CheckMortality { +impl core::fmt::Debug for CheckMortality { #[cfg(feature = "std")] - fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { write!(f, "CheckMortality({:?})", self.0) } #[cfg(not(feature = "std"))] - fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, _: &mut core::fmt::Formatter) -> core::fmt::Result { Ok(()) } } diff --git a/substrate/frame/system/src/extensions/check_non_zero_sender.rs b/substrate/frame/system/src/extensions/check_non_zero_sender.rs index 92eed60fc66b53dec19a86c1fac20f1af8ff4d7b..06dc2bf177ac9500ab492cb585a8cbb7589397d6 100644 --- a/substrate/frame/system/src/extensions/check_non_zero_sender.rs +++ b/substrate/frame/system/src/extensions/check_non_zero_sender.rs @@ -17,6 +17,7 @@ use crate::Config; use codec::{Decode, Encode}; +use core::marker::PhantomData; use frame_support::{dispatch::DispatchInfo, DefaultNoBound}; use scale_info::TypeInfo; use sp_runtime::{ @@ -25,21 +26,20 @@ use sp_runtime::{ InvalidTransaction, TransactionValidity, TransactionValidityError, ValidTransaction, }, }; -use sp_std::{marker::PhantomData, prelude::*}; /// Check to ensure that the sender is not the zero address. #[derive(Encode, Decode, DefaultNoBound, Clone, Eq, PartialEq, TypeInfo)] #[scale_info(skip_type_params(T))] pub struct CheckNonZeroSender(PhantomData); -impl sp_std::fmt::Debug for CheckNonZeroSender { +impl core::fmt::Debug for CheckNonZeroSender { #[cfg(feature = "std")] - fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { write!(f, "CheckNonZeroSender") } #[cfg(not(feature = "std"))] - fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, _: &mut core::fmt::Formatter) -> core::fmt::Result { Ok(()) } } @@ -47,7 +47,7 @@ impl sp_std::fmt::Debug for CheckNonZeroSender { impl CheckNonZeroSender { /// Create new `SignedExtension` to check runtime version. pub fn new() -> Self { - Self(sp_std::marker::PhantomData) + Self(core::marker::PhantomData) } } @@ -61,7 +61,7 @@ where type Pre = (); const IDENTIFIER: &'static str = "CheckNonZeroSender"; - fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> { + fn additional_signed(&self) -> core::result::Result<(), TransactionValidityError> { Ok(()) } diff --git a/substrate/frame/system/src/extensions/check_nonce.rs b/substrate/frame/system/src/extensions/check_nonce.rs index 894ab72eb593b02324e5fabc37a4035efecaac5e..3535870d1b5959186c25e94615a59b41b9e5be87 100644 --- a/substrate/frame/system/src/extensions/check_nonce.rs +++ b/substrate/frame/system/src/extensions/check_nonce.rs @@ -16,6 +16,7 @@ // limitations under the License. use crate::Config; +use alloc::vec; use codec::{Decode, Encode}; use frame_support::dispatch::DispatchInfo; use scale_info::TypeInfo; @@ -26,7 +27,6 @@ use sp_runtime::{ ValidTransaction, }, }; -use sp_std::vec; /// Nonce check and increment to give replay protection for transactions. /// @@ -46,14 +46,14 @@ impl CheckNonce { } } -impl sp_std::fmt::Debug for CheckNonce { +impl core::fmt::Debug for CheckNonce { #[cfg(feature = "std")] - fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { write!(f, "CheckNonce({})", self.0) } #[cfg(not(feature = "std"))] - fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, _: &mut core::fmt::Formatter) -> core::fmt::Result { Ok(()) } } @@ -68,7 +68,7 @@ where type Pre = (); const IDENTIFIER: &'static str = "CheckNonce"; - fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> { + fn additional_signed(&self) -> core::result::Result<(), TransactionValidityError> { Ok(()) } diff --git a/substrate/frame/system/src/extensions/check_spec_version.rs b/substrate/frame/system/src/extensions/check_spec_version.rs index 24d5ef9cafb17b0dd8c1ac02fc127f7068cf6cca..ee7e6f2efd001a981c56f840bf089718b6d823f3 100644 --- a/substrate/frame/system/src/extensions/check_spec_version.rs +++ b/substrate/frame/system/src/extensions/check_spec_version.rs @@ -31,16 +31,16 @@ use sp_runtime::{ /// is not affected in any other way. #[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo)] #[scale_info(skip_type_params(T))] -pub struct CheckSpecVersion(sp_std::marker::PhantomData); +pub struct CheckSpecVersion(core::marker::PhantomData); -impl sp_std::fmt::Debug for CheckSpecVersion { +impl core::fmt::Debug for CheckSpecVersion { #[cfg(feature = "std")] - fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { write!(f, "CheckSpecVersion") } #[cfg(not(feature = "std"))] - fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, _: &mut core::fmt::Formatter) -> core::fmt::Result { Ok(()) } } @@ -48,7 +48,7 @@ impl sp_std::fmt::Debug for CheckSpecVersion { impl CheckSpecVersion { /// Create new `SignedExtension` to check runtime version. pub fn new() -> Self { - Self(sp_std::marker::PhantomData) + Self(core::marker::PhantomData) } } diff --git a/substrate/frame/system/src/extensions/check_tx_version.rs b/substrate/frame/system/src/extensions/check_tx_version.rs index 3f9d6a1903fe1d08d05266a46625aeacba3c273c..15983c2cd088b3b0deeeccf21a679d648da9be42 100644 --- a/substrate/frame/system/src/extensions/check_tx_version.rs +++ b/substrate/frame/system/src/extensions/check_tx_version.rs @@ -31,16 +31,16 @@ use sp_runtime::{ /// is not affected in any other way. #[derive(Encode, Decode, Clone, Eq, PartialEq, TypeInfo)] #[scale_info(skip_type_params(T))] -pub struct CheckTxVersion(sp_std::marker::PhantomData); +pub struct CheckTxVersion(core::marker::PhantomData); -impl sp_std::fmt::Debug for CheckTxVersion { +impl core::fmt::Debug for CheckTxVersion { #[cfg(feature = "std")] - fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { write!(f, "CheckTxVersion") } #[cfg(not(feature = "std"))] - fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, _: &mut core::fmt::Formatter) -> core::fmt::Result { Ok(()) } } @@ -48,7 +48,7 @@ impl sp_std::fmt::Debug for CheckTxVersion { impl CheckTxVersion { /// Create new `SignedExtension` to check transaction version. pub fn new() -> Self { - Self(sp_std::marker::PhantomData) + Self(core::marker::PhantomData) } } diff --git a/substrate/frame/system/src/extensions/check_weight.rs b/substrate/frame/system/src/extensions/check_weight.rs index d4705f200efddacd18149651acf8ed431ca722a8..22da2a5b9872545e53f33481a5595e57e91cc8e3 100644 --- a/substrate/frame/system/src/extensions/check_weight.rs +++ b/substrate/frame/system/src/extensions/check_weight.rs @@ -37,7 +37,7 @@ use sp_weights::Weight; /// transaction is valid. #[derive(Encode, Decode, Clone, Eq, PartialEq, Default, TypeInfo)] #[scale_info(skip_type_params(T))] -pub struct CheckWeight(sp_std::marker::PhantomData); +pub struct CheckWeight(core::marker::PhantomData); impl CheckWeight where @@ -211,7 +211,7 @@ where type Pre = (); const IDENTIFIER: &'static str = "CheckWeight"; - fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> { + fn additional_signed(&self) -> core::result::Result<(), TransactionValidityError> { Ok(()) } @@ -281,14 +281,14 @@ where } } -impl sp_std::fmt::Debug for CheckWeight { +impl core::fmt::Debug for CheckWeight { #[cfg(feature = "std")] - fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { write!(f, "CheckWeight") } #[cfg(not(feature = "std"))] - fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, _: &mut core::fmt::Formatter) -> core::fmt::Result { Ok(()) } } @@ -300,8 +300,8 @@ mod tests { mock::{new_test_ext, System, Test, CALL}, AllExtrinsicsLen, BlockWeight, DispatchClass, }; + use core::marker::PhantomData; use frame_support::{assert_err, assert_ok, dispatch::Pays, weights::Weight}; - use sp_std::marker::PhantomData; fn block_weights() -> crate::limits::BlockWeights { ::BlockWeights::get() diff --git a/substrate/frame/system/src/lib.rs b/substrate/frame/system/src/lib.rs index 84d00a1e917ec033d4fe534f932236db76569625..0c6ff2cb8ddbaf0c1f2634eca4cfa0d6853721b1 100644 --- a/substrate/frame/system/src/lib.rs +++ b/substrate/frame/system/src/lib.rs @@ -97,6 +97,10 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + +use alloc::{boxed::Box, vec, vec::Vec}; +use core::{fmt::Debug, marker::PhantomData}; use pallet_prelude::{BlockNumberFor, HeaderFor}; #[cfg(feature = "std")] use serde::Serialize; @@ -118,7 +122,6 @@ use sp_runtime::{ }; #[cfg(any(feature = "std", test))] use sp_std::map; -use sp_std::{fmt::Debug, marker::PhantomData, prelude::*}; use sp_version::RuntimeVersion; use codec::{Decode, Encode, EncodeLike, FullCodec, MaxEncodedLen}; @@ -269,7 +272,7 @@ pub mod pallet { /// /// NOTE: Avoids overriding `BlockHashCount` when using `mocking::{MockBlock, MockBlockU32, /// MockBlockU128}`. - pub struct TestBlockHashCount>(sp_std::marker::PhantomData); + pub struct TestBlockHashCount>(core::marker::PhantomData); impl, C: Get> Get for TestBlockHashCount { fn get() -> I { C::get().into() @@ -511,7 +514,7 @@ pub mod pallet { + Default + Copy + CheckEqual - + sp_std::hash::Hash + + core::hash::Hash + AsRef<[u8]> + AsMut<[u8]> + MaxEncodedLen; @@ -1011,7 +1014,7 @@ pub mod pallet { #[pallet::genesis_config] pub struct GenesisConfig { #[serde(skip)] - pub _config: sp_std::marker::PhantomData, + pub _config: core::marker::PhantomData, } #[pallet::genesis_build] @@ -1153,7 +1156,7 @@ impl From for LastRuntimeUpgradeInfo { } /// Ensure the origin is Root. -pub struct EnsureRoot(sp_std::marker::PhantomData); +pub struct EnsureRoot(core::marker::PhantomData); impl, O>> + From>, AccountId> EnsureOrigin for EnsureRoot { @@ -1179,7 +1182,7 @@ impl_ensure_origin_with_arg_ignoring_arg! { /// Ensure the origin is Root and return the provided `Success` value. pub struct EnsureRootWithSuccess( - sp_std::marker::PhantomData<(AccountId, Success)>, + core::marker::PhantomData<(AccountId, Success)>, ); impl< O: Into, O>> + From>, @@ -1209,7 +1212,7 @@ impl_ensure_origin_with_arg_ignoring_arg! { /// Ensure the origin is provided `Ensure` origin and return the provided `Success` value. pub struct EnsureWithSuccess( - sp_std::marker::PhantomData<(Ensure, AccountId, Success)>, + core::marker::PhantomData<(Ensure, AccountId, Success)>, ); impl< @@ -1232,7 +1235,7 @@ impl< } /// Ensure the origin is any `Signed` origin. -pub struct EnsureSigned(sp_std::marker::PhantomData); +pub struct EnsureSigned(core::marker::PhantomData); impl, O>> + From>, AccountId: Decode> EnsureOrigin for EnsureSigned { @@ -1259,7 +1262,7 @@ impl_ensure_origin_with_arg_ignoring_arg! { } /// Ensure the origin is `Signed` origin from the given `AccountId`. -pub struct EnsureSignedBy(sp_std::marker::PhantomData<(Who, AccountId)>); +pub struct EnsureSignedBy(core::marker::PhantomData<(Who, AccountId)>); impl< O: Into, O>> + From>, Who: SortedMembers, @@ -1291,7 +1294,7 @@ impl_ensure_origin_with_arg_ignoring_arg! { } /// Ensure the origin is `None`. i.e. unsigned transaction. -pub struct EnsureNone(sp_std::marker::PhantomData); +pub struct EnsureNone(core::marker::PhantomData); impl, O>> + From>, AccountId> EnsureOrigin for EnsureNone { @@ -1316,7 +1319,7 @@ impl_ensure_origin_with_arg_ignoring_arg! { } /// Always fail. -pub struct EnsureNever(sp_std::marker::PhantomData); +pub struct EnsureNever(core::marker::PhantomData); impl EnsureOrigin for EnsureNever { type Success = Success; fn try_origin(o: O) -> Result { @@ -1906,7 +1909,7 @@ impl Pallet { /// Should only be called if you know what you are doing and outside of the runtime block /// execution else it can have a large impact on the PoV size of a block. pub fn read_events_no_consensus( - ) -> impl sp_std::iter::Iterator>> { + ) -> impl Iterator>> { Events::::stream_iter() } diff --git a/substrate/frame/system/src/migrations/mod.rs b/substrate/frame/system/src/migrations/mod.rs index 945bbc53955257266f9023c790f9a7a87d2f8a55..7c69843d73f10d4e9b17d66807fa0c7e92232e36 100644 --- a/substrate/frame/system/src/migrations/mod.rs +++ b/substrate/frame/system/src/migrations/mod.rs @@ -24,7 +24,6 @@ use frame_support::{ pallet_prelude::ValueQuery, traits::PalletInfoAccess, weights::Weight, Blake2_128Concat, }; use sp_runtime::RuntimeDebug; -use sp_std::prelude::*; /// Type used to encode the number of references an account has. type RefCount = u32; diff --git a/substrate/frame/system/src/offchain.rs b/substrate/frame/system/src/offchain.rs index a64b326196403cb87e0970c061ac09e42136d4e1..1f72ea2d37452c88742b427ea621658a20b43a3a 100644 --- a/substrate/frame/system/src/offchain.rs +++ b/substrate/frame/system/src/offchain.rs @@ -56,13 +56,13 @@ #![warn(missing_docs)] +use alloc::{boxed::Box, collections::btree_set::BTreeSet, vec::Vec}; use codec::Encode; use sp_runtime::{ app_crypto::RuntimeAppPublic, traits::{Extrinsic as ExtrinsicT, IdentifyAccount, One}, RuntimeDebug, }; -use sp_std::{collections::btree_set::BTreeSet, prelude::*}; /// Marker struct used to flag using all supported keys to sign a payload. pub struct ForAll {} @@ -76,7 +76,7 @@ pub struct ForAny {} /// utility function can be used. However, this struct is used by `Signer` /// to submit a signed transactions providing the signature along with the call. pub struct SubmitTransaction, OverarchingCall> { - _phantom: sp_std::marker::PhantomData<(T, OverarchingCall)>, + _phantom: core::marker::PhantomData<(T, OverarchingCall)>, } impl SubmitTransaction @@ -115,7 +115,7 @@ where #[derive(RuntimeDebug)] pub struct Signer, X = ForAny> { accounts: Option>, - _phantom: sp_std::marker::PhantomData<(X, C)>, + _phantom: core::marker::PhantomData<(X, C)>, } impl, X> Default for Signer { diff --git a/substrate/frame/timestamp/Cargo.toml b/substrate/frame/timestamp/Cargo.toml index 2da6e2d5a95d222853e7eeca372c770de84f77ea..25aecea7b79eaaf9600cf08e784cc4119b0d8215 100644 --- a/substrate/frame/timestamp/Cargo.toml +++ b/substrate/frame/timestamp/Cargo.toml @@ -26,7 +26,6 @@ frame-system = { workspace = true } sp-inherents = { workspace = true } sp-io = { optional = true, workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } sp-storage = { workspace = true } sp-timestamp = { workspace = true } @@ -49,7 +48,6 @@ std = [ "sp-inherents/std", "sp-io?/std", "sp-runtime/std", - "sp-std/std", "sp-storage/std", "sp-timestamp/std", ] diff --git a/substrate/frame/timestamp/src/lib.rs b/substrate/frame/timestamp/src/lib.rs index 6a22ab1cd5ef8fde0d94791e82750f46629a2340..ca495c5e24efb7302add9b04c7d27c8b7dd14628 100644 --- a/substrate/frame/timestamp/src/lib.rs +++ b/substrate/frame/timestamp/src/lib.rs @@ -133,9 +133,9 @@ mod mock; mod tests; pub mod weights; +use core::{cmp, result}; use frame_support::traits::{OnTimestampSet, Time, UnixTime}; use sp_runtime::traits::{AtLeast32Bit, SaturatedConversion, Scale, Zero}; -use sp_std::{cmp, result}; use sp_timestamp::{InherentError, InherentType, INHERENT_IDENTIFIER}; pub use weights::WeightInfo; @@ -367,14 +367,12 @@ impl UnixTime for Pallet { // now is duration since unix epoch in millisecond as documented in // `sp_timestamp::InherentDataProvider`. let now = Now::::get(); - sp_std::if_std! { - if now == T::Moment::zero() { - log::error!( - target: "runtime::timestamp", - "`pallet_timestamp::UnixTime::now` is called at genesis, invalid value returned: 0", - ); - } - } + + log::error!( + target: "runtime::timestamp", + "`pallet_timestamp::UnixTime::now` is called at genesis, invalid value returned: 0", + ); + core::time::Duration::from_millis(now.saturated_into::()) } } diff --git a/substrate/frame/tips/Cargo.toml b/substrate/frame/tips/Cargo.toml index abebaa19aedaea145ad31be7d6af4abc46aad4dd..bec2ce0a47b8b610f557138965bcb4e52d1fb1df 100644 --- a/substrate/frame/tips/Cargo.toml +++ b/substrate/frame/tips/Cargo.toml @@ -27,7 +27,6 @@ pallet-treasury = { workspace = true } sp-core = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] pallet-balances = { workspace = true, default-features = true } @@ -48,7 +47,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", "sp-storage/std", ] runtime-benchmarks = [ diff --git a/substrate/frame/tips/src/lib.rs b/substrate/frame/tips/src/lib.rs index a75aed89d0b44866aee5453743f8865894660dc3..67bcdfa0685e5f606654dee3f68a527385cf35e6 100644 --- a/substrate/frame/tips/src/lib.rs +++ b/substrate/frame/tips/src/lib.rs @@ -60,12 +60,14 @@ mod tests; pub mod migrations; pub mod weights; +extern crate alloc; + use sp_runtime::{ traits::{AccountIdConversion, BadOrigin, Hash, StaticLookup, TrailingZeroInput, Zero}, Percent, RuntimeDebug, }; -use sp_std::prelude::*; +use alloc::{vec, vec::Vec}; use codec::{Decode, Encode}; use frame_support::{ ensure, diff --git a/substrate/frame/tips/src/migrations/unreserve_deposits.rs b/substrate/frame/tips/src/migrations/unreserve_deposits.rs index 16cb1a80e812bd43dbcf60c353210a650a4d59d0..afc424309bf4d54332572e7b3b6e9bbcded1eaa1 100644 --- a/substrate/frame/tips/src/migrations/unreserve_deposits.rs +++ b/substrate/frame/tips/src/migrations/unreserve_deposits.rs @@ -18,6 +18,7 @@ //! A migration that unreserves all deposit and unlocks all stake held in the context of this //! pallet. +use alloc::collections::btree_map::BTreeMap; use core::iter::Sum; use frame_support::{ pallet_prelude::OptionQuery, @@ -27,7 +28,6 @@ use frame_support::{ Parameter, Twox64Concat, }; use sp_runtime::{traits::Zero, Saturating}; -use sp_std::collections::btree_map::BTreeMap; #[cfg(feature = "try-runtime")] const LOG_TARGET: &str = "runtime::tips::migrations::unreserve_deposits"; @@ -85,7 +85,7 @@ type Tips, I: 'static> = StorageMap< /// The pallet should be made inoperable before or immediately after this migration is run. /// /// (See also the `RemovePallet` migration in `frame/support/src/migrations.rs`) -pub struct UnreserveDeposits, I: 'static>(sp_std::marker::PhantomData<(T, I)>); +pub struct UnreserveDeposits, I: 'static>(core::marker::PhantomData<(T, I)>); impl, I: 'static> UnreserveDeposits { /// Calculates and returns the total amount reserved by each account by this pallet from open @@ -133,7 +133,7 @@ where /// Fails with a `TryRuntimeError` if somehow the amount reserved by this pallet is greater than /// the actual total reserved amount for any accounts. #[cfg(feature = "try-runtime")] - fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { + fn pre_upgrade() -> Result, sp_runtime::TryRuntimeError> { use codec::Encode; use frame_support::ensure; @@ -189,7 +189,7 @@ where /// Verifies that the account reserved balances were reduced by the actual expected amounts. #[cfg(feature = "try-runtime")] fn post_upgrade( - account_reserved_before_bytes: sp_std::vec::Vec, + account_reserved_before_bytes: alloc::vec::Vec, ) -> Result<(), sp_runtime::TryRuntimeError> { use codec::Decode; diff --git a/substrate/frame/transaction-payment/Cargo.toml b/substrate/frame/transaction-payment/Cargo.toml index 3e890a8f7b69f53b80376b78bb014a8c57726301..c405ea1e9439060973523fbfe494ff38657df2a6 100644 --- a/substrate/frame/transaction-payment/Cargo.toml +++ b/substrate/frame/transaction-payment/Cargo.toml @@ -26,7 +26,6 @@ frame-system = { workspace = true } sp-core = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] serde_json = { workspace = true, default-features = true } @@ -44,7 +43,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] try-runtime = [ "frame-support/try-runtime", diff --git a/substrate/frame/transaction-payment/asset-conversion-tx-payment/Cargo.toml b/substrate/frame/transaction-payment/asset-conversion-tx-payment/Cargo.toml index 02ce212deb6a7b4982996945f1604ccd03ed4f29..b87d780b96721d3cd805326ba59a980a3274dbbf 100644 --- a/substrate/frame/transaction-payment/asset-conversion-tx-payment/Cargo.toml +++ b/substrate/frame/transaction-payment/asset-conversion-tx-payment/Cargo.toml @@ -18,7 +18,6 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] # Substrate dependencies sp-runtime = { workspace = true } -sp-std = { workspace = true } frame-support = { workspace = true } frame-system = { workspace = true } pallet-asset-conversion = { workspace = true } @@ -47,7 +46,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", "sp-storage/std", ] try-runtime = [ diff --git a/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/lib.rs b/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/lib.rs index ed0ed56e6e074b49db7abf6d43ddb9305d7fb616..538d88bfacfaa6d5138ff7fca33e9b45cf1ee56c 100644 --- a/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/lib.rs +++ b/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/lib.rs @@ -42,7 +42,7 @@ #![cfg_attr(not(feature = "std"), no_std)] -use sp_std::prelude::*; +extern crate alloc; use codec::{Decode, Encode}; use frame_support::{ @@ -214,13 +214,13 @@ where } } -impl sp_std::fmt::Debug for ChargeAssetTxPayment { +impl core::fmt::Debug for ChargeAssetTxPayment { #[cfg(feature = "std")] - fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { write!(f, "ChargeAssetTxPayment<{:?}, {:?}>", self.tip, self.asset_id.encode()) } #[cfg(not(feature = "std"))] - fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, _: &mut core::fmt::Formatter) -> core::fmt::Result { Ok(()) } } @@ -252,7 +252,7 @@ where Option>, ); - fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> { + fn additional_signed(&self) -> core::result::Result<(), TransactionValidityError> { Ok(()) } diff --git a/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/payment.rs b/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/payment.rs index f2f2c57bb376d9b81d04f3e39a77d27c0652be20..0ef3fb1111439e0020bc4797fb0cd85ed71521b7 100644 --- a/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/payment.rs +++ b/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/payment.rs @@ -17,6 +17,8 @@ use super::*; use crate::Config; +use alloc::vec; +use core::marker::PhantomData; use frame_support::{ ensure, traits::{fungible::Inspect, tokens::Balance}, @@ -28,7 +30,6 @@ use sp_runtime::{ transaction_validity::InvalidTransaction, Saturating, }; -use sp_std::marker::PhantomData; /// Handle withdrawing, refunding and depositing of transaction fees. pub trait OnChargeAssetTransaction { diff --git a/substrate/frame/transaction-payment/asset-tx-payment/Cargo.toml b/substrate/frame/transaction-payment/asset-tx-payment/Cargo.toml index 1b92ecf53c0266606b3653911e305c4f069c1b72..ec8fb38dda390c4d3535541228d3fe3e02785a49 100644 --- a/substrate/frame/transaction-payment/asset-tx-payment/Cargo.toml +++ b/substrate/frame/transaction-payment/asset-tx-payment/Cargo.toml @@ -20,7 +20,6 @@ targets = ["x86_64-unknown-linux-gnu"] sp-core = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } frame-support = { workspace = true } frame-system = { workspace = true } @@ -57,7 +56,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", "sp-storage/std", ] runtime-benchmarks = [ diff --git a/substrate/frame/transaction-payment/asset-tx-payment/src/lib.rs b/substrate/frame/transaction-payment/asset-tx-payment/src/lib.rs index 753fae747a37ec914abb439fc3829c4caca9a448..97f1116993fc166dd6036ae88a790eaf3cb8e34f 100644 --- a/substrate/frame/transaction-payment/asset-tx-payment/src/lib.rs +++ b/substrate/frame/transaction-payment/asset-tx-payment/src/lib.rs @@ -35,8 +35,6 @@ #![cfg_attr(not(feature = "std"), no_std)] -use sp_std::prelude::*; - use codec::{Decode, Encode}; use frame_support::{ dispatch::{DispatchInfo, DispatchResult, PostDispatchInfo}, @@ -198,13 +196,13 @@ where } } -impl sp_std::fmt::Debug for ChargeAssetTxPayment { +impl core::fmt::Debug for ChargeAssetTxPayment { #[cfg(feature = "std")] - fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { write!(f, "ChargeAssetTxPayment<{:?}, {:?}>", self.tip, self.asset_id.encode()) } #[cfg(not(feature = "std"))] - fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, _: &mut core::fmt::Formatter) -> core::fmt::Result { Ok(()) } } @@ -232,7 +230,7 @@ where Option>, ); - fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> { + fn additional_signed(&self) -> core::result::Result<(), TransactionValidityError> { Ok(()) } diff --git a/substrate/frame/transaction-payment/asset-tx-payment/src/payment.rs b/substrate/frame/transaction-payment/asset-tx-payment/src/payment.rs index 717114ab6bd03c786266d1b54fe25fa171c47d19..2486474bad45b7ad9a293491631acfbc3ef4e47f 100644 --- a/substrate/frame/transaction-payment/asset-tx-payment/src/payment.rs +++ b/substrate/frame/transaction-payment/asset-tx-payment/src/payment.rs @@ -18,6 +18,7 @@ use super::*; use crate::Config; use codec::FullCodec; +use core::{fmt::Debug, marker::PhantomData}; use frame_support::{ traits::{ fungibles::{Balanced, Credit, Inspect}, @@ -33,7 +34,6 @@ use sp_runtime::{ traits::{DispatchInfoOf, MaybeSerializeDeserialize, One, PostDispatchInfoOf}, transaction_validity::InvalidTransaction, }; -use sp_std::{fmt::Debug, marker::PhantomData}; /// Handle withdrawing, refunding and depositing of transaction fees. pub trait OnChargeAssetTransaction { diff --git a/substrate/frame/transaction-payment/skip-feeless-payment/Cargo.toml b/substrate/frame/transaction-payment/skip-feeless-payment/Cargo.toml index 7265979cedc0c3737df51a24718e9b19d6cf57e9..b5bc7719def607bd54cc9013f4f89889e03f5430 100644 --- a/substrate/frame/transaction-payment/skip-feeless-payment/Cargo.toml +++ b/substrate/frame/transaction-payment/skip-feeless-payment/Cargo.toml @@ -16,7 +16,6 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] # Substrate dependencies sp-runtime = { workspace = true } -sp-std = { workspace = true } frame-support = { workspace = true } frame-system = { workspace = true } @@ -33,7 +32,6 @@ std = [ "frame-system/std", "scale-info/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-support/runtime-benchmarks", diff --git a/substrate/frame/transaction-payment/skip-feeless-payment/src/lib.rs b/substrate/frame/transaction-payment/skip-feeless-payment/src/lib.rs index 682fb320356166bdd16b068b156e3315344b3a44..3ab38743bafdd8b4e8f86bb1f5f0ad902f83ffd4 100644 --- a/substrate/frame/transaction-payment/skip-feeless-payment/src/lib.rs +++ b/substrate/frame/transaction-payment/skip-feeless-payment/src/lib.rs @@ -77,7 +77,7 @@ pub mod pallet { /// A [`SignedExtension`] that skips the wrapped extension if the dispatchable is feeless. #[derive(Encode, Decode, Clone, Eq, PartialEq)] -pub struct SkipCheckIfFeeless(pub S, sp_std::marker::PhantomData); +pub struct SkipCheckIfFeeless(pub S, core::marker::PhantomData); // Make this extension "invisible" from the outside (ie metadata type information) impl TypeInfo for SkipCheckIfFeeless { @@ -87,20 +87,20 @@ impl TypeInfo for SkipCheckIfFeeless { } } -impl sp_std::fmt::Debug for SkipCheckIfFeeless { +impl core::fmt::Debug for SkipCheckIfFeeless { #[cfg(feature = "std")] - fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { write!(f, "SkipCheckIfFeeless<{:?}>", self.0.encode()) } #[cfg(not(feature = "std"))] - fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, _: &mut core::fmt::Formatter) -> core::fmt::Result { Ok(()) } } impl From for SkipCheckIfFeeless { fn from(s: S) -> Self { - Self(s, sp_std::marker::PhantomData) + Self(s, core::marker::PhantomData) } } diff --git a/substrate/frame/transaction-payment/skip-feeless-payment/src/mock.rs b/substrate/frame/transaction-payment/skip-feeless-payment/src/mock.rs index 4ddeae11fcab4cf071d17e00e6d77b4d0c4c27fe..d6d600f24e77cf840db1fae796fc8edad2133f91 100644 --- a/substrate/frame/transaction-payment/skip-feeless-payment/src/mock.rs +++ b/substrate/frame/transaction-payment/skip-feeless-payment/src/mock.rs @@ -45,7 +45,7 @@ impl SignedExtension for DummyExtension { type AdditionalSigned = (); type Pre = (); const IDENTIFIER: &'static str = "DummyExtension"; - fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> { + fn additional_signed(&self) -> core::result::Result<(), TransactionValidityError> { Ok(()) } diff --git a/substrate/frame/transaction-payment/src/lib.rs b/substrate/frame/transaction-payment/src/lib.rs index 0e440ee4e9ff5f503086a0e5c139a89fdf01a5be..69fad6e0e32483f9301e30bd4c833ec120cc7226 100644 --- a/substrate/frame/transaction-payment/src/lib.rs +++ b/substrate/frame/transaction-payment/src/lib.rs @@ -69,7 +69,6 @@ use sp_runtime::{ }, FixedPointNumber, FixedU128, Perbill, Perquintill, RuntimeDebug, }; -use sp_std::prelude::*; pub use types::{FeeDetails, InclusionFee, RuntimeDispatchInfo}; #[cfg(test)] @@ -137,7 +136,7 @@ type BalanceOf = <::OnChargeTransaction as OnChargeTransaction -pub struct TargetedFeeAdjustment(sp_std::marker::PhantomData<(T, S, V, M, X)>); +pub struct TargetedFeeAdjustment(core::marker::PhantomData<(T, S, V, M, X)>); /// Something that can convert the current multiplier to the next one. pub trait MultiplierUpdate: Convert { @@ -264,7 +263,7 @@ where } /// A struct to make the fee multiplier a constant -pub struct ConstFeeMultiplier>(sp_std::marker::PhantomData); +pub struct ConstFeeMultiplier>(core::marker::PhantomData); impl> MultiplierUpdate for ConstFeeMultiplier { fn min() -> Multiplier { @@ -406,7 +405,7 @@ pub mod pallet { pub struct GenesisConfig { pub multiplier: Multiplier, #[serde(skip)] - pub _config: sp_std::marker::PhantomData, + pub _config: core::marker::PhantomData, } impl Default for GenesisConfig { @@ -806,13 +805,13 @@ where } } -impl sp_std::fmt::Debug for ChargeTransactionPayment { +impl core::fmt::Debug for ChargeTransactionPayment { #[cfg(feature = "std")] - fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { write!(f, "ChargeTransactionPayment<{:?}>", self.0) } #[cfg(not(feature = "std"))] - fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, _: &mut core::fmt::Formatter) -> core::fmt::Result { Ok(()) } } @@ -834,7 +833,7 @@ where // imbalance resulting from withdrawing the fee <::OnChargeTransaction as OnChargeTransaction>::LiquidityInfo, ); - fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> { + fn additional_signed(&self) -> core::result::Result<(), TransactionValidityError> { Ok(()) } diff --git a/substrate/frame/transaction-payment/src/types.rs b/substrate/frame/transaction-payment/src/types.rs index 25cecc58a63ab092822d61bb32259a7a846b230a..67c7311d0cab5bf8e8e4f83ac874a49279e42d14 100644 --- a/substrate/frame/transaction-payment/src/types.rs +++ b/substrate/frame/transaction-payment/src/types.rs @@ -24,7 +24,6 @@ use serde::{Deserialize, Serialize}; use scale_info::TypeInfo; use sp_runtime::traits::{AtLeast32BitUnsigned, Zero}; -use sp_std::prelude::*; use frame_support::dispatch::DispatchClass; diff --git a/substrate/frame/transaction-storage/Cargo.toml b/substrate/frame/transaction-storage/Cargo.toml index 3bb97e0cd01562c439028f373339398b6ef4e2f1..e57ee1e729c4d05fb713053c98a693368e5dce3e 100644 --- a/substrate/frame/transaction-storage/Cargo.toml +++ b/substrate/frame/transaction-storage/Cargo.toml @@ -27,7 +27,6 @@ pallet-balances = { workspace = true } sp-inherents = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } sp-transaction-storage-proof = { workspace = true } log = { workspace = true } @@ -58,7 +57,6 @@ std = [ "sp-inherents/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", "sp-transaction-storage-proof/std", ] try-runtime = [ diff --git a/substrate/frame/transaction-storage/src/benchmarking.rs b/substrate/frame/transaction-storage/src/benchmarking.rs index 8d485d9f3cac2de9f5a738dbe5490f2fb5232bce..f360e9847a1e1f9ef57b12f3aa77f62c13d8d4ca 100644 --- a/substrate/frame/transaction-storage/src/benchmarking.rs +++ b/substrate/frame/transaction-storage/src/benchmarking.rs @@ -20,11 +20,11 @@ #![cfg(feature = "runtime-benchmarks")] use super::*; +use alloc::{vec, vec::Vec}; use frame_benchmarking::v1::{benchmarks, whitelisted_caller}; use frame_support::traits::{Get, OnFinalize, OnInitialize}; use frame_system::{pallet_prelude::BlockNumberFor, EventRecord, Pallet as System, RawOrigin}; use sp_runtime::traits::{Bounded, CheckedDiv, One, Zero}; -use sp_std::*; use sp_transaction_storage_proof::TransactionStorageProof; use crate::Pallet as TransactionStorage; diff --git a/substrate/frame/transaction-storage/src/lib.rs b/substrate/frame/transaction-storage/src/lib.rs index 6e58ee3e585abd5362bfd5f19d9a616c1b4d7ee7..68f24526300d8539bb1865520dbc6d7b06dc2cf0 100644 --- a/substrate/frame/transaction-storage/src/lib.rs +++ b/substrate/frame/transaction-storage/src/lib.rs @@ -28,7 +28,11 @@ mod mock; #[cfg(test)] mod tests; +extern crate alloc; + +use alloc::vec::Vec; use codec::{Decode, Encode, MaxEncodedLen}; +use core::result; use frame_support::{ dispatch::GetDispatchInfo, traits::{ @@ -38,7 +42,6 @@ use frame_support::{ }, }; use sp_runtime::traits::{BlakeTwo256, Dispatchable, Hash, One, Saturating, Zero}; -use sp_std::{prelude::*, result}; use sp_transaction_storage_proof::{ encode_index, random_chunk, InherentError, TransactionStorageProof, CHUNK_SIZE, INHERENT_IDENTIFIER, diff --git a/substrate/frame/treasury/Cargo.toml b/substrate/frame/treasury/Cargo.toml index 33e74b0a4aa282699e2a278ab6359b22df563c39..2727ab809320c6eac7f53d82563910b871380ef2 100644 --- a/substrate/frame/treasury/Cargo.toml +++ b/substrate/frame/treasury/Cargo.toml @@ -29,7 +29,6 @@ frame-support = { workspace = true } frame-system = { workspace = true } pallet-balances = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } sp-core = { optional = true, workspace = true } [dev-dependencies] @@ -51,7 +50,6 @@ std = [ "sp-core?/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "dep:sp-core", diff --git a/substrate/frame/treasury/src/lib.rs b/substrate/frame/treasury/src/lib.rs index b437e5ef137e3e72bf39c10223a94a67dc31b91c..3954489a2d156696efe0173aea74ec0583c16ae9 100644 --- a/substrate/frame/treasury/src/lib.rs +++ b/substrate/frame/treasury/src/lib.rs @@ -81,14 +81,16 @@ use core::marker::PhantomData; #[cfg(feature = "runtime-benchmarks")] pub use benchmarking::ArgumentsFactory; +extern crate alloc; + use codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; +use alloc::{boxed::Box, collections::btree_map::BTreeMap}; use sp_runtime::{ traits::{AccountIdConversion, CheckedAdd, Saturating, StaticLookup, Zero}, Permill, RuntimeDebug, }; -use sp_std::{collections::btree_map::BTreeMap, prelude::*}; use frame_support::{ dispatch::{DispatchResult, DispatchResultWithPostInfo}, @@ -326,7 +328,7 @@ pub mod pallet { #[derive(frame_support::DefaultNoBound)] pub struct GenesisConfig, I: 'static = ()> { #[serde(skip)] - _config: sp_std::marker::PhantomData<(T, I)>, + _config: core::marker::PhantomData<(T, I)>, } #[pallet::genesis_build] diff --git a/substrate/frame/try-runtime/Cargo.toml b/substrate/frame/try-runtime/Cargo.toml index 16e815975b5440000a0bc0808205e2323865adaa..228d96095ac926a92a428f68851b65cd647c9116 100644 --- a/substrate/frame/try-runtime/Cargo.toml +++ b/substrate/frame/try-runtime/Cargo.toml @@ -19,7 +19,6 @@ codec = { features = ["derive"], workspace = true } frame-support = { workspace = true } sp-api = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [features] default = ["std"] @@ -28,6 +27,5 @@ std = [ "frame-support/std", "sp-api/std", "sp-runtime/std", - "sp-std/std", ] try-runtime = ["frame-support/try-runtime", "sp-runtime/try-runtime"] diff --git a/substrate/frame/tx-pause/Cargo.toml b/substrate/frame/tx-pause/Cargo.toml index fbb71513c6ae7e59595a8b06a39c62d5db2ebecf..861a85881f2dd9d9d5adb3eafeba809677d8ba42 100644 --- a/substrate/frame/tx-pause/Cargo.toml +++ b/substrate/frame/tx-pause/Cargo.toml @@ -22,7 +22,6 @@ frame-support = { workspace = true } frame-system = { workspace = true } scale-info = { features = ["derive"], workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } pallet-balances = { optional = true, workspace = true } pallet-utility = { optional = true, workspace = true } pallet-proxy = { optional = true, workspace = true } @@ -48,7 +47,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/tx-pause/src/benchmarking.rs b/substrate/frame/tx-pause/src/benchmarking.rs index 126c0837949d56553baf5e1a073ab082df3c4dad..95ae250eff7b54d680aea1dce819f950b8bcefec 100644 --- a/substrate/frame/tx-pause/src/benchmarking.rs +++ b/substrate/frame/tx-pause/src/benchmarking.rs @@ -18,6 +18,7 @@ #![cfg(feature = "runtime-benchmarks")] use super::{Pallet as TxPause, *}; +use alloc::vec; use frame_benchmarking::v2::*; #[benchmarks] diff --git a/substrate/frame/tx-pause/src/lib.rs b/substrate/frame/tx-pause/src/lib.rs index 5904b5ed316285c38526bdab47b9cb53048faec7..68f7a0312554d59fc2570393548dfa5a9e6f4a3e 100644 --- a/substrate/frame/tx-pause/src/lib.rs +++ b/substrate/frame/tx-pause/src/lib.rs @@ -79,6 +79,9 @@ pub mod mock; mod tests; pub mod weights; +extern crate alloc; + +use alloc::vec::Vec; use frame_support::{ dispatch::GetDispatchInfo, pallet_prelude::*, @@ -87,7 +90,6 @@ use frame_support::{ }; use frame_system::pallet_prelude::*; use sp_runtime::{traits::Dispatchable, DispatchResult}; -use sp_std::prelude::*; pub use pallet::*; pub use weights::*; diff --git a/substrate/frame/uniques/Cargo.toml b/substrate/frame/uniques/Cargo.toml index d41d322bb63f1a9e72915549107f673a340c039d..2b1794aa60fe7ea2cc650c8828784c0ec260a22c 100644 --- a/substrate/frame/uniques/Cargo.toml +++ b/substrate/frame/uniques/Cargo.toml @@ -23,7 +23,6 @@ frame-benchmarking = { optional = true, workspace = true } frame-support = { workspace = true } frame-system = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] pallet-balances = { workspace = true, default-features = true } @@ -44,7 +43,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/uniques/src/benchmarking.rs b/substrate/frame/uniques/src/benchmarking.rs index 80d02f1362189d34491975918b5d14ce28bc3ab0..a8a83010c51ff895ba3631dba238b44d669144cf 100644 --- a/substrate/frame/uniques/src/benchmarking.rs +++ b/substrate/frame/uniques/src/benchmarking.rs @@ -20,6 +20,7 @@ #![cfg(feature = "runtime-benchmarks")] use super::*; +use alloc::{vec, vec::Vec}; use frame_benchmarking::v1::{ account, benchmarks_instance_pallet, whitelist_account, whitelisted_caller, BenchmarkError, }; @@ -29,7 +30,6 @@ use frame_support::{ }; use frame_system::RawOrigin as SystemOrigin; use sp_runtime::traits::Bounded; -use sp_std::prelude::*; use crate::Pallet as Uniques; diff --git a/substrate/frame/uniques/src/impl_nonfungibles.rs b/substrate/frame/uniques/src/impl_nonfungibles.rs index 0ae055a98d8c8bd551106cf4ef3c47503e41a83c..8e4af723f80333d736214bf79a88948b986eb78a 100644 --- a/substrate/frame/uniques/src/impl_nonfungibles.rs +++ b/substrate/frame/uniques/src/impl_nonfungibles.rs @@ -18,13 +18,13 @@ //! Implementations for `nonfungibles` traits. use super::*; +use alloc::vec::Vec; use frame_support::{ storage::KeyPrefixIterator, traits::{tokens::nonfungibles::*, Get}, BoundedSlice, }; use sp_runtime::{DispatchError, DispatchResult}; -use sp_std::prelude::*; impl, I: 'static> Inspect<::AccountId> for Pallet { type ItemId = T::ItemId; diff --git a/substrate/frame/uniques/src/lib.rs b/substrate/frame/uniques/src/lib.rs index 2291d19de2bfb6941c78614558254de19e75680a..dc27c335623406e21e811c0af8ed2e626908637c 100644 --- a/substrate/frame/uniques/src/lib.rs +++ b/substrate/frame/uniques/src/lib.rs @@ -42,6 +42,9 @@ mod types; pub mod migration; pub mod weights; +extern crate alloc; + +use alloc::vec::Vec; use codec::{Decode, Encode}; use frame_support::traits::{ tokens::Locker, BalanceStatus::Reserved, Currency, EnsureOriginWithArg, ReservableCurrency, @@ -51,7 +54,6 @@ use sp_runtime::{ traits::{Saturating, StaticLookup, Zero}, ArithmeticError, RuntimeDebug, }; -use sp_std::prelude::*; pub use pallet::*; pub use types::*; diff --git a/substrate/frame/uniques/src/tests.rs b/substrate/frame/uniques/src/tests.rs index 5dfe43c96888dfb634012a460a4b9314da2a2497..a8428c420b3e5fd7b9104f0e622baa2175bf0e20 100644 --- a/substrate/frame/uniques/src/tests.rs +++ b/substrate/frame/uniques/src/tests.rs @@ -21,7 +21,6 @@ use crate::{mock::*, Event, *}; use frame_support::{assert_noop, assert_ok, traits::Currency}; use pallet_balances::Error as BalancesError; use sp_runtime::traits::Dispatchable; -use sp_std::prelude::*; fn items() -> Vec<(u64, u32, u32)> { let mut r: Vec<_> = Account::::iter().map(|x| x.0).collect(); diff --git a/substrate/frame/utility/Cargo.toml b/substrate/frame/utility/Cargo.toml index 0ccdac6be6236ef68f528f5c24f8904a7dba1670..f08232de9cd6d10139e86d9ea7bff9c2bfc9d36a 100644 --- a/substrate/frame/utility/Cargo.toml +++ b/substrate/frame/utility/Cargo.toml @@ -24,7 +24,6 @@ frame-system = { workspace = true } sp-core = { workspace = true } sp-io = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] pallet-balances = { workspace = true, default-features = true } @@ -48,7 +47,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/utility/src/benchmarking.rs b/substrate/frame/utility/src/benchmarking.rs index 78911fd310e857222d5ff46b661838cda79597d9..467055ecd800daad6ee827343dbd2f6d1094bcae 100644 --- a/substrate/frame/utility/src/benchmarking.rs +++ b/substrate/frame/utility/src/benchmarking.rs @@ -20,6 +20,7 @@ #![cfg(feature = "runtime-benchmarks")] use super::*; +use alloc::{vec, vec::Vec}; use frame_benchmarking::v1::{account, benchmarks, whitelisted_caller}; use frame_system::RawOrigin; diff --git a/substrate/frame/utility/src/lib.rs b/substrate/frame/utility/src/lib.rs index 7f963e3637d6fcb606591c46e9511280ee776879..3ce5b4ff86496d48ffa60d953b86d56880ec65c5 100644 --- a/substrate/frame/utility/src/lib.rs +++ b/substrate/frame/utility/src/lib.rs @@ -56,6 +56,9 @@ mod benchmarking; mod tests; pub mod weights; +extern crate alloc; + +use alloc::{boxed::Box, vec::Vec}; use codec::{Decode, Encode}; use frame_support::{ dispatch::{extract_actual_weight, GetDispatchInfo, PostDispatchInfo}, @@ -64,7 +67,6 @@ use frame_support::{ use sp_core::TypeId; use sp_io::hashing::blake2_256; use sp_runtime::traits::{BadOrigin, Dispatchable, TrailingZeroInput}; -use sp_std::prelude::*; pub use weights::WeightInfo; pub use pallet::*; @@ -131,7 +133,7 @@ pub mod pallet { /// The limit on the number of batched calls. fn batched_calls_limit() -> u32 { let allocator_limit = sp_core::MAX_POSSIBLE_ALLOCATION; - let call_size = ((sp_std::mem::size_of::<::RuntimeCall>() as u32 + + let call_size = ((core::mem::size_of::<::RuntimeCall>() as u32 + CALL_ALIGN - 1) / CALL_ALIGN) * CALL_ALIGN; // The margin to take into account vec doubling capacity. @@ -146,7 +148,7 @@ pub mod pallet { fn integrity_test() { // If you hit this error, you need to try to `Box` big dispatchable parameters. assert!( - sp_std::mem::size_of::<::RuntimeCall>() as u32 <= CALL_ALIGN, + core::mem::size_of::<::RuntimeCall>() as u32 <= CALL_ALIGN, "Call enum size should be smaller than {} bytes.", CALL_ALIGN, ); diff --git a/substrate/frame/utility/src/tests.rs b/substrate/frame/utility/src/tests.rs index eb2047aac28af40e9d8872c38ed21b89666e1c48..0a58a92b4c9ea7564a221c7b9cfb02b3f83b1d90 100644 --- a/substrate/frame/utility/src/tests.rs +++ b/substrate/frame/utility/src/tests.rs @@ -25,14 +25,13 @@ use crate as utility; use frame_support::{ assert_err_ignore_postinfo, assert_noop, assert_ok, derive_impl, dispatch::{DispatchErrorWithPostInfo, Pays}, - error::BadOrigin, parameter_types, storage, traits::{ConstU64, Contains}, weights::Weight, }; use pallet_collective::{EnsureProportionAtLeast, Instance1}; use sp_runtime::{ - traits::{BlakeTwo256, Dispatchable, Hash}, + traits::{BadOrigin, BlakeTwo256, Dispatchable, Hash}, BuildStorage, DispatchError, TokenError, }; diff --git a/substrate/frame/vesting/Cargo.toml b/substrate/frame/vesting/Cargo.toml index 3aca5683465cd39e6873cb123135312b8c3ca74b..64c26174cfdfd0a4fb2e0094973f2ac66897933e 100644 --- a/substrate/frame/vesting/Cargo.toml +++ b/substrate/frame/vesting/Cargo.toml @@ -25,7 +25,6 @@ frame-benchmarking = { optional = true, workspace = true } frame-support = { workspace = true } frame-system = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] pallet-balances = { workspace = true, default-features = true } @@ -45,7 +44,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking/runtime-benchmarks", diff --git a/substrate/frame/vesting/src/lib.rs b/substrate/frame/vesting/src/lib.rs index 3868f1a8592e95c69aa2fd09b8a201b869016fba..bfc10efeed796bdf85d42c48bcb3c41ffa8ce8e0 100644 --- a/substrate/frame/vesting/src/lib.rs +++ b/substrate/frame/vesting/src/lib.rs @@ -56,7 +56,11 @@ mod vesting_info; pub mod migrations; pub mod weights; +extern crate alloc; + +use alloc::vec::Vec; use codec::{Decode, Encode, MaxEncodedLen}; +use core::{fmt::Debug, marker::PhantomData}; use frame_support::{ dispatch::DispatchResult, ensure, @@ -76,7 +80,6 @@ use sp_runtime::{ }, DispatchError, RuntimeDebug, }; -use sp_std::{fmt::Debug, marker::PhantomData, prelude::*}; pub use pallet::*; pub use vesting_info::*; diff --git a/substrate/frame/vesting/src/migrations.rs b/substrate/frame/vesting/src/migrations.rs index 6fe82312b637d550bfe164c62155bb9261e75801..33fa5d0df882c7f018d9c7bffbec4661e5b558c8 100644 --- a/substrate/frame/vesting/src/migrations.rs +++ b/substrate/frame/vesting/src/migrations.rs @@ -18,6 +18,7 @@ //! Storage migrations for the vesting pallet. use super::*; +use alloc::vec; // Migration from single schedule to multiple schedules. pub mod v1 { diff --git a/substrate/frame/whitelist/Cargo.toml b/substrate/frame/whitelist/Cargo.toml index 922f9124d913a1b81c9142f9822635753eec728c..c48a15f2163185dd6ac63cf64ab2839f94df3281 100644 --- a/substrate/frame/whitelist/Cargo.toml +++ b/substrate/frame/whitelist/Cargo.toml @@ -22,7 +22,6 @@ frame-support = { workspace = true } frame-system = { workspace = true } sp-api = { workspace = true } sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] pallet-balances = { workspace = true, default-features = true } @@ -44,7 +43,6 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime/std", - "sp-std/std", ] runtime-benchmarks = [ "frame-benchmarking", diff --git a/substrate/frame/whitelist/src/benchmarking.rs b/substrate/frame/whitelist/src/benchmarking.rs index 7fb5632fc00247648be3238775735d0b2fdc2241..cbe6ee4becd0acb5d51cc09b7794973d8f79f9af 100644 --- a/substrate/frame/whitelist/src/benchmarking.rs +++ b/substrate/frame/whitelist/src/benchmarking.rs @@ -73,7 +73,7 @@ mod benchmarks { ) -> Result<(), BenchmarkError> { let origin = T::DispatchWhitelistedOrigin::try_successful_origin() .map_err(|_| BenchmarkError::Weightless)?; - let remark = sp_std::vec![1u8; n as usize]; + let remark = alloc::vec![1u8; n as usize]; let call: ::RuntimeCall = frame_system::Call::remark { remark }.into(); let call_weight = call.get_dispatch_info().weight; let encoded_call = call.encode(); @@ -97,7 +97,7 @@ mod benchmarks { fn dispatch_whitelisted_call_with_preimage(n: Linear<1, 10_000>) -> Result<(), BenchmarkError> { let origin = T::DispatchWhitelistedOrigin::try_successful_origin() .map_err(|_| BenchmarkError::Weightless)?; - let remark = sp_std::vec![1u8; n as usize]; + let remark = alloc::vec![1u8; n as usize]; let call: ::RuntimeCall = frame_system::Call::remark { remark }.into(); let call_hash = T::Hashing::hash_of(&call); diff --git a/substrate/frame/whitelist/src/lib.rs b/substrate/frame/whitelist/src/lib.rs index 44551abd10715e0e4dd23d9667b2786f8ae850a1..de16c2c2da883e20a62ffd807ef7739df9b46439 100644 --- a/substrate/frame/whitelist/src/lib.rs +++ b/substrate/frame/whitelist/src/lib.rs @@ -40,6 +40,9 @@ mod tests; pub mod weights; pub use weights::WeightInfo; +extern crate alloc; + +use alloc::boxed::Box; use codec::{DecodeLimit, Encode, FullCodec}; use frame_support::{ dispatch::{GetDispatchInfo, PostDispatchInfo}, @@ -49,7 +52,6 @@ use frame_support::{ }; use scale_info::TypeInfo; use sp_runtime::traits::{Dispatchable, Hash}; -use sp_std::prelude::*; pub use pallet::*; diff --git a/substrate/kitchensink_runtime.wasm b/substrate/kitchensink_runtime.wasm deleted file mode 100644 index 7ebb14371243afa4956a107374b27a4e686f0360..0000000000000000000000000000000000000000 Binary files a/substrate/kitchensink_runtime.wasm and /dev/null differ diff --git a/substrate/primitives/api/Cargo.toml b/substrate/primitives/api/Cargo.toml index f8cbad8e31f02d38ee5a218d107968f634420a67..d6c64a0ada28bb668f648b092268edcf81b513df 100644 --- a/substrate/primitives/api/Cargo.toml +++ b/substrate/primitives/api/Cargo.toml @@ -19,7 +19,6 @@ targets = ["x86_64-unknown-linux-gnu"] codec = { workspace = true } sp-api-proc-macro = { workspace = true } sp-core = { workspace = true } -sp-std = { workspace = true } sp-runtime = { workspace = true } sp-runtime-interface = { workspace = true } sp-externalities = { optional = true, workspace = true } @@ -53,7 +52,6 @@ std = [ "sp-runtime-interface/std", "sp-runtime/std", "sp-state-machine/std", - "sp-std/std", "sp-test-primitives/std", "sp-trie/std", "sp-version/std", diff --git a/substrate/primitives/api/src/lib.rs b/substrate/primitives/api/src/lib.rs index cd8da8ba2374e142835967c8f304c62b1d0bf250..d254bf20601fe12a7c960ae2381c5d7a75c70d67 100644 --- a/substrate/primitives/api/src/lib.rs +++ b/substrate/primitives/api/src/lib.rs @@ -70,6 +70,8 @@ // Make doc tests happy extern crate self as sp_api; +extern crate alloc; + /// Private exports used by the macros. /// /// This is seen as internal API and can change at any point. @@ -90,7 +92,9 @@ pub mod __private { pub use std_imports::*; pub use crate::*; + pub use alloc::vec; pub use codec::{self, Decode, DecodeLimit, Encode}; + pub use core::{mem, slice}; pub use scale_info; pub use sp_core::offchain; #[cfg(not(feature = "std"))] @@ -103,7 +107,6 @@ pub mod __private { transaction_validity::TransactionValidity, ExtrinsicInclusionMode, RuntimeString, TransactionOutcome, }; - pub use sp_std::{mem, slice, vec}; pub use sp_version::{create_apis_vec, ApiId, ApisVec, RuntimeVersion}; #[cfg(all(any(target_arch = "riscv32", target_arch = "riscv64"), substrate_runtime))] @@ -833,7 +836,7 @@ decl_runtime_apis! { /// Returns the supported metadata versions. /// /// This can be used to call `metadata_at_version`. - fn metadata_versions() -> sp_std::vec::Vec; + fn metadata_versions() -> alloc::vec::Vec; } } diff --git a/substrate/primitives/application-crypto/Cargo.toml b/substrate/primitives/application-crypto/Cargo.toml index fbf9def20fce7468ced3036c107cbbaac9e2593b..c0508d377f8b4950d734a1ea09d339fd77be9b0c 100644 --- a/substrate/primitives/application-crypto/Cargo.toml +++ b/substrate/primitives/application-crypto/Cargo.toml @@ -22,7 +22,6 @@ sp-core = { workspace = true } codec = { features = ["derive"], workspace = true } scale-info = { features = ["derive"], workspace = true } serde = { optional = true, features = ["alloc", "derive"], workspace = true } -sp-std = { workspace = true } sp-io = { workspace = true } [features] @@ -34,7 +33,6 @@ std = [ "serde/std", "sp-core/std", "sp-io/std", - "sp-std/std", ] # Serde support without relying on std features. diff --git a/substrate/primitives/application-crypto/src/bandersnatch.rs b/substrate/primitives/application-crypto/src/bandersnatch.rs index fc7383815d7021a6abe93da2bbbeb723d91f4d2e..0e21e5d3bce31ba0cd62987377cbaa60fc1230a4 100644 --- a/substrate/primitives/application-crypto/src/bandersnatch.rs +++ b/substrate/primitives/application-crypto/src/bandersnatch.rs @@ -18,8 +18,8 @@ //! Bandersnatch VRF application crypto types. use crate::{KeyTypeId, RuntimePublic}; +use alloc::vec::Vec; pub use sp_core::bandersnatch::*; -use sp_std::vec::Vec; mod app { crate::app_crypto!(super, sp_core::testing::BANDERSNATCH); diff --git a/substrate/primitives/application-crypto/src/bls377.rs b/substrate/primitives/application-crypto/src/bls377.rs index 3bd01de139c9496d35b143ddeb07de1285154946..9d346ea618343dde42526a7d2c9389965463840c 100644 --- a/substrate/primitives/application-crypto/src/bls377.rs +++ b/substrate/primitives/application-crypto/src/bls377.rs @@ -18,8 +18,8 @@ //! BLS12-377 crypto applications. use crate::{KeyTypeId, RuntimePublic}; +use alloc::vec::Vec; pub use sp_core::bls::bls377::*; -use sp_std::vec::Vec; mod app { crate::app_crypto!(super, sp_core::testing::BLS377); diff --git a/substrate/primitives/application-crypto/src/ecdsa.rs b/substrate/primitives/application-crypto/src/ecdsa.rs index 439b51dc604509788bd16b25aea2dbf6201471bd..94d5288584ccb89d111f62f14fb140495d8b3714 100644 --- a/substrate/primitives/application-crypto/src/ecdsa.rs +++ b/substrate/primitives/application-crypto/src/ecdsa.rs @@ -19,7 +19,7 @@ use crate::{KeyTypeId, RuntimePublic}; -use sp_std::vec::Vec; +use alloc::vec::Vec; pub use sp_core::ecdsa::*; diff --git a/substrate/primitives/application-crypto/src/ecdsa_bls377.rs b/substrate/primitives/application-crypto/src/ecdsa_bls377.rs index 8dee73095fb2e2fcbeb968edef2aad667112767a..443d214d67729f47b081ba9a13e20cfa407dc5f0 100644 --- a/substrate/primitives/application-crypto/src/ecdsa_bls377.rs +++ b/substrate/primitives/application-crypto/src/ecdsa_bls377.rs @@ -18,7 +18,7 @@ //! ECDSA and BLS12-377 paired crypto applications. use crate::{KeyTypeId, RuntimePublic}; -use sp_std::vec::Vec; +use alloc::vec::Vec; pub use sp_core::paired_crypto::ecdsa_bls377::*; diff --git a/substrate/primitives/application-crypto/src/ed25519.rs b/substrate/primitives/application-crypto/src/ed25519.rs index addefe7daf6431415f1c06727b88edd1b3bd9158..6769de4e47c349f0b5736573144ae0f9f50bea5f 100644 --- a/substrate/primitives/application-crypto/src/ed25519.rs +++ b/substrate/primitives/application-crypto/src/ed25519.rs @@ -19,7 +19,7 @@ use crate::{KeyTypeId, RuntimePublic}; -use sp_std::vec::Vec; +use alloc::vec::Vec; pub use sp_core::ed25519::*; diff --git a/substrate/primitives/application-crypto/src/lib.rs b/substrate/primitives/application-crypto/src/lib.rs index 2355f1ba527d5227a804fc30ae2deccc44df2152..37949d7c41ded368fc33a5b33d8e11df6dd4f6f5 100644 --- a/substrate/primitives/application-crypto/src/lib.rs +++ b/substrate/primitives/application-crypto/src/lib.rs @@ -20,6 +20,8 @@ #![warn(missing_docs)] #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + pub use sp_core::crypto::{key_types, CryptoTypeId, DeriveJunction, KeyTypeId, Ss58Codec}; #[doc(hidden)] pub use sp_core::crypto::{DeriveError, Pair, SecretStringError}; @@ -30,15 +32,17 @@ pub use sp_core::{ RuntimeDebug, }; +#[doc(hidden)] +pub use alloc::vec::Vec; #[doc(hidden)] pub use codec; #[doc(hidden)] +pub use core::ops::Deref; +#[doc(hidden)] pub use scale_info; #[doc(hidden)] #[cfg(feature = "serde")] pub use serde; -#[doc(hidden)] -pub use sp_std::{ops::Deref, vec::Vec}; #[cfg(feature = "bandersnatch-experimental")] pub mod bandersnatch; @@ -357,7 +361,7 @@ macro_rules! app_crypto_public_common { #[doc(hidden)] pub mod module_format_string_prelude { #[cfg(all(not(feature = "std"), feature = "serde"))] - pub use sp_std::alloc::{format, string::String}; + pub use alloc::{format, string::String}; #[cfg(feature = "std")] pub use std::{format, string::String}; } diff --git a/substrate/primitives/application-crypto/src/sr25519.rs b/substrate/primitives/application-crypto/src/sr25519.rs index d411cc253c0d84fd0bd7f366a7dec86f4c9acc91..ba6f0e3ae6b37ad6627f5fc19718f268115ec09a 100644 --- a/substrate/primitives/application-crypto/src/sr25519.rs +++ b/substrate/primitives/application-crypto/src/sr25519.rs @@ -19,7 +19,7 @@ use crate::{KeyTypeId, RuntimePublic}; -use sp_std::vec::Vec; +use alloc::vec::Vec; pub use sp_core::sr25519::*; diff --git a/substrate/primitives/application-crypto/src/traits.rs b/substrate/primitives/application-crypto/src/traits.rs index 0b59abf272dc7761f08c8604db33762b07e31584..1789d9b96fd82e51e73e4e2d0ba8c0e173b6802d 100644 --- a/substrate/primitives/application-crypto/src/traits.rs +++ b/substrate/primitives/application-crypto/src/traits.rs @@ -18,8 +18,9 @@ use codec::Codec; use scale_info::TypeInfo; +use alloc::vec::Vec; +use core::fmt::Debug; use sp_core::crypto::{CryptoType, CryptoTypeId, IsWrappedBy, KeyTypeId, Pair, Public}; -use sp_std::{fmt::Debug, vec::Vec}; /// Application-specific cryptographic object. /// @@ -47,8 +48,8 @@ pub trait AppCrypto: 'static + Sized + CryptoType { } /// Type which implements Hash in std, not when no-std (std variant). -pub trait MaybeHash: sp_std::hash::Hash {} -impl MaybeHash for T {} +pub trait MaybeHash: core::hash::Hash {} +impl MaybeHash for T {} /// Application-specific key pair. pub trait AppPair: diff --git a/substrate/primitives/arithmetic/Cargo.toml b/substrate/primitives/arithmetic/Cargo.toml index a0d80fc9b504984121c990d9053d67383ad9c57b..4a9d5ba234bab98e0cd56fd7cbdcfdd4fec840e1 100644 --- a/substrate/primitives/arithmetic/Cargo.toml +++ b/substrate/primitives/arithmetic/Cargo.toml @@ -26,7 +26,6 @@ num-traits = { workspace = true } scale-info = { features = ["derive"], workspace = true } serde = { features = ["alloc", "derive"], optional = true, workspace = true } static_assertions = { workspace = true, default-features = true } -sp-std = { workspace = true } docify = { workspace = true } [dev-dependencies] @@ -43,7 +42,6 @@ std = [ "scale-info/std", "serde/std", "sp-crypto-hashing/std", - "sp-std/std", ] # Serde support without relying on std features. serde = ["dep:serde", "scale-info/serde"] diff --git a/substrate/primitives/blockchain/Cargo.toml b/substrate/primitives/blockchain/Cargo.toml index aedd720612c33d35722eca2f3815f562e15f23c0..bd0daaf63c055934ab99c4087eb7d27db8ae41c1 100644 --- a/substrate/primitives/blockchain/Cargo.toml +++ b/substrate/primitives/blockchain/Cargo.toml @@ -19,7 +19,6 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] codec = { features = ["derive"], workspace = true } futures = { workspace = true } -log = { workspace = true, default-features = true } parking_lot = { workspace = true, default-features = true } schnellru = { workspace = true } thiserror = { workspace = true } @@ -29,3 +28,4 @@ sp-consensus = { workspace = true, default-features = true } sp-database = { workspace = true, default-features = true } sp-runtime = { workspace = true, default-features = true } sp-state-machine = { workspace = true, default-features = true } +tracing = { workspace = true, default-features = true } diff --git a/substrate/primitives/blockchain/src/backend.rs b/substrate/primitives/blockchain/src/backend.rs index a928217d5885454b704c527354cabb5ba49af923..2accd4dad12c5bc579408ae432a5bf579ea8d57c 100644 --- a/substrate/primitives/blockchain/src/backend.rs +++ b/substrate/primitives/blockchain/src/backend.rs @@ -17,7 +17,6 @@ //! Substrate blockchain trait -use log::warn; use parking_lot::RwLock; use sp_runtime::{ generic::BlockId, @@ -25,6 +24,7 @@ use sp_runtime::{ Justifications, }; use std::collections::{btree_set::BTreeSet, HashMap, VecDeque}; +use tracing::{debug, warn}; use crate::{ error::{Error, Result}, @@ -228,6 +228,7 @@ pub trait Backend: // // FIXME #1558 only issue this warning when not on a dead fork warn!( + target: crate::LOG_TARGET, "Block {:?} exists in chain but not found when following all leaves backwards", base_hash, ); @@ -254,16 +255,35 @@ pub trait Backend: ) -> std::result::Result, Error> { let leaves = self.leaves()?; + debug!( + target: crate::LOG_TARGET, + ?leaves, + %finalized_block_hash, + ?finalized_block_number, + "Checking for displaced leaves after finalization." + ); + // If we have only one leaf there are no forks, and we can return early. if finalized_block_number == Zero::zero() || leaves.len() == 1 { return Ok(DisplacedLeavesAfterFinalization::default()) } - // Store hashes of finalized blocks for quick checking later, the last block if the + // Store hashes of finalized blocks for quick checking later, the last block is the // finalized one let mut finalized_chain = VecDeque::new(); - finalized_chain - .push_front(MinimalBlockMetadata::from(&self.header_metadata(finalized_block_hash)?)); + let current_finalized = match self.header_metadata(finalized_block_hash) { + Ok(metadata) => metadata, + Err(Error::UnknownBlock(_)) => { + debug!( + target: crate::LOG_TARGET, + hash = ?finalized_block_hash, + "Tried to fetch unknown block, block ancestry has gaps." + ); + return Ok(DisplacedLeavesAfterFinalization::default()); + }, + Err(e) => Err(e)?, + }; + finalized_chain.push_front(MinimalBlockMetadata::from(¤t_finalized)); // Local cache is a performance optimization in case of finalized block deep below the // tip of the chain with a lot of leaves above finalized block @@ -273,6 +293,7 @@ pub trait Backend: displaced_leaves: Vec::with_capacity(leaves.len()), displaced_blocks: Vec::with_capacity(leaves.len()), }; + let mut displaced_blocks_candidates = Vec::new(); for leaf_hash in leaves { @@ -306,11 +327,11 @@ pub trait Backend: continue; } - // Otherwise the whole leaf branch needs to be pruned, track it all the way to the - // point of branching from the finalized chain - result.displaced_leaves.push((leaf_number, leaf_hash)); - result.displaced_blocks.extend(displaced_blocks_candidates.drain(..)); - result.displaced_blocks.push(current_header_metadata.hash); + // We reuse `displaced_blocks_candidates` to store the current metadata. + // This block is not displaced if there is a gap in the ancestry. We + // check for this gap later. + displaced_blocks_candidates.push(current_header_metadata.hash); + // Collect the rest of the displaced blocks of leaf branch for distance_from_finalized in 1_u32.. { // Find block at `distance_from_finalized` from finalized block @@ -318,9 +339,22 @@ pub trait Backend: match finalized_chain.iter().rev().nth(distance_from_finalized as usize) { Some(header) => (header.number, header.hash), None => { - let metadata = MinimalBlockMetadata::from(&self.header_metadata( - finalized_chain.front().expect("Not empty; qed").parent, - )?); + let to_fetch = finalized_chain.front().expect("Not empty; qed"); + let metadata = match self.header_metadata(to_fetch.parent) { + Ok(metadata) => metadata, + Err(Error::UnknownBlock(_)) => { + debug!( + target: crate::LOG_TARGET, + distance_from_finalized, + hash = ?to_fetch.parent, + number = ?to_fetch.number, + "Tried to fetch unknown block, block ancestry has gaps." + ); + break; + }, + Err(e) => Err(e)?, + }; + let metadata = MinimalBlockMetadata::from(&metadata); let result = (metadata.number, metadata.hash); finalized_chain.push_front(metadata); result @@ -336,11 +370,13 @@ pub trait Backend: let parent_hash = current_header_metadata.parent; if finalized_chain_block_hash == parent_hash { // Reached finalized chain, nothing left to do + result.displaced_blocks.extend(displaced_blocks_candidates.drain(..)); + result.displaced_leaves.push((leaf_number, leaf_hash)); break; } // Store displaced block and look deeper for block on finalized chain - result.displaced_blocks.push(parent_hash); + displaced_blocks_candidates.push(parent_hash); current_header_metadata = MinimalBlockMetadata::from(&self.header_metadata(parent_hash)?); } diff --git a/substrate/primitives/blockchain/src/header_metadata.rs b/substrate/primitives/blockchain/src/header_metadata.rs index 30024765add3ced4b5295a023cb0980aae3d59fd..b2910a32e99546f9cb74803f124ba963ed21700f 100644 --- a/substrate/primitives/blockchain/src/header_metadata.rs +++ b/substrate/primitives/blockchain/src/header_metadata.rs @@ -18,7 +18,7 @@ //! Implements tree backend, cached header metadata and algorithms //! to compute routes efficiently over the tree of headers. -use parking_lot::RwLock; +use parking_lot::Mutex; use schnellru::{ByLength, LruMap}; use sp_core::U256; use sp_runtime::{ @@ -248,33 +248,33 @@ pub trait HeaderMetadata { /// Caches header metadata in an in-memory LRU cache. pub struct HeaderMetadataCache { - cache: RwLock>>, + cache: Mutex>>, } impl HeaderMetadataCache { /// Creates a new LRU header metadata cache with `capacity`. pub fn new(capacity: u32) -> Self { - HeaderMetadataCache { cache: RwLock::new(LruMap::new(ByLength::new(capacity))) } + HeaderMetadataCache { cache: Mutex::new(LruMap::new(ByLength::new(capacity))) } } } impl Default for HeaderMetadataCache { fn default() -> Self { - HeaderMetadataCache { cache: RwLock::new(LruMap::new(ByLength::new(LRU_CACHE_SIZE))) } + Self::new(LRU_CACHE_SIZE) } } impl HeaderMetadataCache { pub fn header_metadata(&self, hash: Block::Hash) -> Option> { - self.cache.write().get(&hash).cloned() + self.cache.lock().get(&hash).cloned() } pub fn insert_header_metadata(&self, hash: Block::Hash, metadata: CachedHeaderMetadata) { - self.cache.write().insert(hash, metadata); + self.cache.lock().insert(hash, metadata); } pub fn remove_header_metadata(&self, hash: Block::Hash) { - self.cache.write().remove(&hash); + self.cache.lock().remove(&hash); } } diff --git a/substrate/primitives/blockchain/src/lib.rs b/substrate/primitives/blockchain/src/lib.rs index eabbbcf50d9f208c19d76ef81c8736e314e61a71..305b7f6afec198f260a9dbc331fb573612fb74c0 100644 --- a/substrate/primitives/blockchain/src/lib.rs +++ b/substrate/primitives/blockchain/src/lib.rs @@ -24,3 +24,5 @@ mod header_metadata; pub use backend::*; pub use error::*; pub use header_metadata::*; + +const LOG_TARGET: &str = "db::blockchain"; diff --git a/substrate/primitives/core/src/address_uri.rs b/substrate/primitives/core/src/address_uri.rs index d44f3c0c87c40dd447ca0e3123b74f9464408666..bbe31b7553bd2b2304384934bdf9ee1928d63aa1 100644 --- a/substrate/primitives/core/src/address_uri.rs +++ b/substrate/primitives/core/src/address_uri.rs @@ -18,8 +18,8 @@ //! Little util for parsing an address URI. Replaces regular expressions. #[cfg(not(feature = "std"))] -use sp_std::{ - alloc::string::{String, ToString}, +use alloc::{ + string::{String, ToString}, vec::Vec, }; @@ -97,10 +97,10 @@ impl InvalidCharacterInfo { } } -impl sp_std::fmt::Display for InvalidCharacterInfo { - fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { +impl core::fmt::Display for InvalidCharacterInfo { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { let (s, pos) = escape_string(&self.0, self.1); - write!(f, "{s}\n{i}^", i = sp_std::iter::repeat(" ").take(pos).collect::()) + write!(f, "{s}\n{i}^", i = core::iter::repeat(" ").take(pos).collect::()) } } diff --git a/substrate/primitives/core/src/bandersnatch.rs b/substrate/primitives/core/src/bandersnatch.rs index 71ee2da5383489a42f1c3a961089b031e2764964..25bf4657030fbcddcc75a419941a247759e0f9d5 100644 --- a/substrate/primitives/core/src/bandersnatch.rs +++ b/substrate/primitives/core/src/bandersnatch.rs @@ -31,7 +31,7 @@ use bandersnatch_vrfs::{CanonicalSerialize, SecretKey}; use codec::{Decode, Encode, EncodeLike, MaxEncodedLen}; use scale_info::TypeInfo; -use sp_std::{vec, vec::Vec}; +use alloc::{vec, vec::Vec}; /// Identifier used to match public keys against bandersnatch-vrf keys. pub const CRYPTO_ID: CryptoTypeId = CryptoTypeId(*b"band"); diff --git a/substrate/primitives/core/src/bls.rs b/substrate/primitives/core/src/bls.rs index bb04babb3f180f3728c3a0e8159b725aeb7a2d47..a86f67844da2addb4c5596689268c469039a50a2 100644 --- a/substrate/primitives/core/src/bls.rs +++ b/substrate/primitives/core/src/bls.rs @@ -28,7 +28,7 @@ use crate::crypto::{ SignatureBytes, UncheckedFrom, }; -use sp_std::vec::Vec; +use alloc::vec::Vec; use w3f_bls::{ DoublePublicKey, DoublePublicKeyScheme, DoubleSignature, EngineBLS, Keypair, Message, diff --git a/substrate/primitives/core/src/crypto.rs b/substrate/primitives/core/src/crypto.rs index b13899fff5176eb76defa5ef32f840ad2c8c0ceb..fd7fe776720400ba3e4ad9fa1859ca5dc168a8bb 100644 --- a/substrate/primitives/core/src/crypto.rs +++ b/substrate/primitives/core/src/crypto.rs @@ -18,8 +18,14 @@ //! Cryptographic utilities. use crate::{ed25519, sr25519}; +#[cfg(all(not(feature = "std"), feature = "serde"))] +use alloc::{format, string::String, vec}; +use alloc::{str, vec::Vec}; use bip39::{Language, Mnemonic}; use codec::{Decode, Encode, MaxEncodedLen}; +use core::hash::Hash; +#[doc(hidden)] +pub use core::ops::Deref; #[cfg(feature = "std")] use itertools::Itertools; #[cfg(feature = "std")] @@ -27,14 +33,6 @@ use rand::{rngs::OsRng, RngCore}; use scale_info::TypeInfo; pub use secrecy::{ExposeSecret, SecretString}; use sp_runtime_interface::pass_by::PassByInner; -#[doc(hidden)] -pub use sp_std::ops::Deref; -#[cfg(all(not(feature = "std"), feature = "serde"))] -use sp_std::{ - alloc::{format, string::String}, - vec, -}; -use sp_std::{hash::Hash, str, vec::Vec}; pub use ss58_registry::{from_known_address_format, Ss58AddressFormat, Ss58AddressFormatRegistry}; /// Trait to zeroize a memory buffer. pub use zeroize::Zeroize; @@ -245,8 +243,8 @@ pub enum PublicError { } #[cfg(feature = "std")] -impl sp_std::fmt::Debug for PublicError { - fn fmt(&self, f: &mut sp_std::fmt::Formatter<'_>) -> sp_std::fmt::Result { +impl core::fmt::Debug for PublicError { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { // Just use the `Display` implementation write!(f, "{}", self) } @@ -587,8 +585,8 @@ impl std::fmt::Display for AccountId32 { } } -impl sp_std::fmt::Debug for AccountId32 { - fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { +impl core::fmt::Debug for AccountId32 { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { #[cfg(feature = "serde")] { let s = self.to_ss58check(); @@ -624,7 +622,7 @@ impl<'de> serde::Deserialize<'de> for AccountId32 { } #[cfg(feature = "std")] -impl sp_std::str::FromStr for AccountId32 { +impl std::str::FromStr for AccountId32 { type Err = &'static str; fn from_str(s: &str) -> Result { @@ -786,7 +784,7 @@ pub struct SecretUri { pub junctions: Vec, } -impl sp_std::str::FromStr for SecretUri { +impl alloc::str::FromStr for SecretUri { type Err = SecretStringError; fn from_str(s: &str) -> Result { @@ -925,7 +923,7 @@ pub trait Pair: CryptoType + Sized { s: &str, password_override: Option<&str>, ) -> Result<(Self, Option), SecretStringError> { - use sp_std::str::FromStr; + use alloc::str::FromStr; let SecretUri { junctions, phrase, password } = SecretUri::from_str(s)?; let password = password_override.or_else(|| password.as_ref().map(|p| p.expose_secret().as_str())); diff --git a/substrate/primitives/core/src/crypto_bytes.rs b/substrate/primitives/core/src/crypto_bytes.rs index ee5f3482f743a6a63b3465c75fcdb6d2d82ab6e7..e5130e6d50079f3b9c8e8797f89e1c04e636679b 100644 --- a/substrate/primitives/core/src/crypto_bytes.rs +++ b/substrate/primitives/core/src/crypto_bytes.rs @@ -34,7 +34,7 @@ use crate::crypto::Ss58Codec; use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; #[cfg(all(not(feature = "std"), feature = "serde"))] -use sp_std::alloc::{format, string::String}; +use alloc::{format, string::String}; pub use public_bytes::*; pub use signature_bytes::*; @@ -256,7 +256,7 @@ mod public_bytes { impl Public for PublicBytes where Self: CryptoType {} - impl sp_std::fmt::Debug for PublicBytes + impl core::fmt::Debug for PublicBytes where Self: CryptoType, { @@ -267,7 +267,7 @@ mod public_bytes { } #[cfg(not(feature = "std"))] - fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, _: &mut core::fmt::Formatter) -> core::fmt::Result { Ok(()) } } @@ -362,17 +362,17 @@ mod signature_bytes { } } - impl sp_std::fmt::Debug for SignatureBytes + impl core::fmt::Debug for SignatureBytes where Self: CryptoType, { #[cfg(feature = "std")] - fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { write!(f, "{}", crate::hexdisplay::HexDisplay::from(&&self.0[..])) } #[cfg(not(feature = "std"))] - fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, _: &mut core::fmt::Formatter) -> core::fmt::Result { Ok(()) } } diff --git a/substrate/primitives/core/src/ecdsa.rs b/substrate/primitives/core/src/ecdsa.rs index 9cba8cc3d352a0b60317f570827015f4c11d5313..d11811ff2af65be517b69b7fadb454b7fd65432e 100644 --- a/substrate/primitives/core/src/ecdsa.rs +++ b/substrate/primitives/core/src/ecdsa.rs @@ -22,6 +22,8 @@ use crate::crypto::{ SecretStringError, SignatureBytes, }; +#[cfg(not(feature = "std"))] +use alloc::vec::Vec; #[cfg(not(feature = "std"))] use k256::ecdsa::{SigningKey as SecretKey, VerifyingKey}; #[cfg(feature = "std")] @@ -29,8 +31,6 @@ use secp256k1::{ ecdsa::{RecoverableSignature, RecoveryId}, Message, PublicKey, SecretKey, SECP256K1, }; -#[cfg(not(feature = "std"))] -use sp_std::vec::Vec; /// An identifier used to match public keys against ecdsa keys pub const CRYPTO_ID: CryptoTypeId = CryptoTypeId(*b"ecds"); diff --git a/substrate/primitives/core/src/ed25519.rs b/substrate/primitives/core/src/ed25519.rs index 269b6bfcd8dcefc961aa10b1384d4cfe0bfdfd19..401f9a39d5673f78d7e2a22d023d62873d293ad7 100644 --- a/substrate/primitives/core/src/ed25519.rs +++ b/substrate/primitives/core/src/ed25519.rs @@ -24,7 +24,7 @@ use crate::crypto::{ use ed25519_zebra::{SigningKey, VerificationKey}; -use sp_std::vec::Vec; +use alloc::vec::Vec; /// An identifier used to match public keys against ed25519 keys pub const CRYPTO_ID: CryptoTypeId = CryptoTypeId(*b"ed25"); diff --git a/substrate/primitives/core/src/hexdisplay.rs b/substrate/primitives/core/src/hexdisplay.rs index 72bb24a186e54dbfb4deecd105065dc2b63d332d..1902b8cca958a3aa45403e7a3173cb96023faebf 100644 --- a/substrate/primitives/core/src/hexdisplay.rs +++ b/substrate/primitives/core/src/hexdisplay.rs @@ -27,8 +27,8 @@ impl<'a> HexDisplay<'a> { } } -impl<'a> sp_std::fmt::Display for HexDisplay<'a> { - fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> Result<(), sp_std::fmt::Error> { +impl<'a> core::fmt::Display for HexDisplay<'a> { + fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> { if self.0.len() < 1027 { for byte in self.0 { f.write_fmt(format_args!("{:02x}", byte))?; @@ -46,8 +46,8 @@ impl<'a> sp_std::fmt::Display for HexDisplay<'a> { } } -impl<'a> sp_std::fmt::Debug for HexDisplay<'a> { - fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> Result<(), sp_std::fmt::Error> { +impl<'a> core::fmt::Debug for HexDisplay<'a> { + fn fmt(&self, f: &mut core::fmt::Formatter) -> Result<(), core::fmt::Error> { for byte in self.0 { f.write_fmt(format_args!("{:02x}", byte))?; } @@ -73,7 +73,7 @@ impl AsBytesRef for [u8] { } } -impl AsBytesRef for sp_std::vec::Vec { +impl AsBytesRef for alloc::vec::Vec { fn as_bytes_ref(&self) -> &[u8] { self } diff --git a/substrate/primitives/core/src/lib.rs b/substrate/primitives/core/src/lib.rs index 78ec92e4be98db3ac12aaba165fdcdfa596375e3..46503921453def0995c33597186e310478896741 100644 --- a/substrate/primitives/core/src/lib.rs +++ b/substrate/primitives/core/src/lib.rs @@ -31,15 +31,18 @@ macro_rules! map { ); } +extern crate alloc; + +use alloc::vec::Vec; #[doc(hidden)] pub use codec::{Decode, Encode, MaxEncodedLen}; +use core::ops::Deref; use scale_info::TypeInfo; #[cfg(feature = "serde")] pub use serde; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; use sp_runtime_interface::pass_by::{PassByEnum, PassByInner}; -use sp_std::{ops::Deref, prelude::*}; pub use sp_debug_derive::RuntimeDebug; @@ -137,7 +140,7 @@ impl codec::WrapperTypeDecode for Bytes { } #[cfg(feature = "std")] -impl sp_std::str::FromStr for Bytes { +impl alloc::str::FromStr for Bytes { type Err = bytes::FromHexError; fn from_str(s: &str) -> Result { @@ -156,7 +159,7 @@ impl OpaqueMetadata { } } -impl sp_std::ops::Deref for OpaqueMetadata { +impl Deref for OpaqueMetadata { type Target = Vec; fn deref(&self) -> &Self::Target { @@ -313,7 +316,7 @@ pub fn to_substrate_wasm_fn_return_value(value: &impl Encode) -> u64 { // Leak the output vector to avoid it being freed. // This is fine in a WASM context since the heap // will be discarded after the call. - sp_std::mem::forget(encoded); + core::mem::forget(encoded); res } @@ -456,7 +459,7 @@ macro_rules! generate_feature_enabled_macro { /// // Will add the code depending on the feature being enabled or not. #[doc = concat!(stringify!($macro_name), "!( println!(\"Hello\") )")] /// ``` - // https://github.com/rust-lang/rust/pull/52234 + // https://github.com/rust-lang/rust/pull/52234 pub use [<_ $macro_name>] as $macro_name; } }; diff --git a/substrate/primitives/core/src/offchain/mod.rs b/substrate/primitives/core/src/offchain/mod.rs index cef495dfaacdcf3c0ba58610819b758d2d4fd6c6..9be86e85d58783553c0d05503bd5ab951d241e32 100644 --- a/substrate/primitives/core/src/offchain/mod.rs +++ b/substrate/primitives/core/src/offchain/mod.rs @@ -18,10 +18,10 @@ //! Offchain workers types use crate::{OpaquePeerId, RuntimeDebug}; +use alloc::{boxed::Box, vec::Vec}; use codec::{Decode, Encode}; use scale_info::TypeInfo; use sp_runtime_interface::pass_by::{PassByCodec, PassByEnum, PassByInner}; -use sp_std::prelude::{Box, Vec}; pub use crate::crypto::KeyTypeId; diff --git a/substrate/primitives/core/src/paired_crypto.rs b/substrate/primitives/core/src/paired_crypto.rs index 260e86b6ff9c4d759fd3794c6a91cc77aebd8dc0..57bc5b006197bb875f6e44dfc2dfea20738b3878 100644 --- a/substrate/primitives/core/src/paired_crypto.rs +++ b/substrate/primitives/core/src/paired_crypto.rs @@ -24,7 +24,7 @@ use crate::crypto::{ PublicBytes, SecretStringError, Signature as SignatureT, SignatureBytes, UncheckedFrom, }; -use sp_std::vec::Vec; +use alloc::vec::Vec; /// ECDSA and BLS12-377 paired crypto scheme #[cfg(feature = "bls-experimental")] diff --git a/substrate/primitives/core/src/sr25519.rs b/substrate/primitives/core/src/sr25519.rs index 54b9a98db3d2ca2b69af5ab77701e4e8c0b70a83..48780f2ccff939c36097d0b2d4289215c8a82026 100644 --- a/substrate/primitives/core/src/sr25519.rs +++ b/substrate/primitives/core/src/sr25519.rs @@ -25,25 +25,25 @@ use crate::crypto::Ss58Codec; use crate::crypto::{ CryptoBytes, DeriveError, DeriveJunction, Pair as TraitPair, SecretStringError, }; +use alloc::vec::Vec; #[cfg(feature = "full_crypto")] use schnorrkel::signing_context; use schnorrkel::{ derive::{ChainCode, Derivation, CHAIN_CODE_LENGTH}, ExpansionMode, Keypair, MiniSecretKey, PublicKey, SecretKey, }; -use sp_std::vec::Vec; use crate::crypto::{CryptoType, CryptoTypeId, Derive, Public as TraitPublic, SignatureBytes}; use codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; +#[cfg(all(not(feature = "std"), feature = "serde"))] +use alloc::{format, string::String}; use schnorrkel::keys::{MINI_SECRET_KEY_LENGTH, SECRET_KEY_LENGTH}; #[cfg(feature = "serde")] use serde::{de, Deserialize, Deserializer, Serialize, Serializer}; #[cfg(feature = "std")] use sp_runtime_interface::pass_by::PassByInner; -#[cfg(all(not(feature = "std"), feature = "serde"))] -use sp_std::alloc::{format, string::String}; // signing context const SIGNING_CTX: &[u8] = b"substrate"; @@ -100,15 +100,15 @@ impl std::fmt::Display for Public { } } -impl sp_std::fmt::Debug for Public { +impl core::fmt::Debug for Public { #[cfg(feature = "std")] - fn fmt(&self, f: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { let s = self.to_ss58check(); write!(f, "{} ({}...)", crate::hexdisplay::HexDisplay::from(self.inner()), &s[0..8]) } #[cfg(not(feature = "std"))] - fn fmt(&self, _: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, _: &mut core::fmt::Formatter) -> core::fmt::Result { Ok(()) } } diff --git a/substrate/primitives/io/Cargo.toml b/substrate/primitives/io/Cargo.toml index 6b58ea70b8e5ef3a31fc1b9b468e43b544d21343..923efc3b87646a4322134c5b6ab576bfb10c83af 100644 --- a/substrate/primitives/io/Cargo.toml +++ b/substrate/primitives/io/Cargo.toml @@ -25,7 +25,6 @@ codec = { features = [ sp-core = { workspace = true } sp-crypto-hashing = { workspace = true } sp-keystore = { optional = true, workspace = true } -sp-std = { workspace = true } libsecp256k1 = { optional = true, workspace = true, default-features = true } sp-state-machine = { optional = true, workspace = true } sp-runtime-interface = { workspace = true } @@ -67,7 +66,6 @@ std = [ "sp-keystore/std", "sp-runtime-interface/std", "sp-state-machine/std", - "sp-std/std", "sp-tracing/std", "sp-trie/std", "tracing-core/std", diff --git a/substrate/primitives/io/src/lib.rs b/substrate/primitives/io/src/lib.rs index 67e822ba7e248ed2b07614b85dca4e1c72e8c3e3..b39a06ed2115ab9ec51736d291534af445f08aa4 100644 --- a/substrate/primitives/io/src/lib.rs +++ b/substrate/primitives/io/src/lib.rs @@ -77,7 +77,9 @@ #![cfg_attr(not(feature = "std"), no_std)] #![cfg_attr(enable_alloc_error_handler, feature(alloc_error_handler))] -use sp_std::vec::Vec; +extern crate alloc; + +use alloc::vec::Vec; #[cfg(feature = "std")] use tracing; @@ -1771,7 +1773,7 @@ pub fn unreachable() -> ! { #[panic_handler] #[no_mangle] pub fn panic(info: &core::panic::PanicInfo) -> ! { - let message = sp_std::alloc::format!("{}", info); + let message = alloc::format!("{}", info); #[cfg(feature = "improved_panic_error_reporting")] { panic_handler::abort_on_panic(&message); diff --git a/substrate/primitives/runtime-interface/proc-macro/src/pass_by/enum_.rs b/substrate/primitives/runtime-interface/proc-macro/src/pass_by/enum_.rs index 0d05dd9aa51e20b076f293946077a5b40c7418a2..d0eb382cdc566b79643c42ea680e3d66978f037e 100644 --- a/substrate/primitives/runtime-interface/proc-macro/src/pass_by/enum_.rs +++ b/substrate/primitives/runtime-interface/proc-macro/src/pass_by/enum_.rs @@ -54,7 +54,7 @@ pub fn derive_impl(input: DeriveInput) -> Result { impl TryFrom for #ident { type Error = (); - fn try_from(inner: u8) -> #crate_::sp_std::result::Result { + fn try_from(inner: u8) -> core::result::Result { match inner { #( #try_from_variants, )* _ => Err(()), diff --git a/substrate/primitives/runtime-interface/src/impls.rs b/substrate/primitives/runtime-interface/src/impls.rs index 3530b62662a53c53afa14667a77fb7c1c609c582..daf5725e7f51147a6286bfe0398e4f5799c26a5a 100644 --- a/substrate/primitives/runtime-interface/src/impls.rs +++ b/substrate/primitives/runtime-interface/src/impls.rs @@ -35,10 +35,12 @@ use sp_wasm_interface::{FunctionContext, Result}; use codec::{Decode, Encode}; -use sp_std::{any::TypeId, mem, vec::Vec}; +use core::{any::TypeId, mem}; + +use alloc::vec::Vec; #[cfg(feature = "std")] -use sp_std::borrow::Cow; +use alloc::borrow::Cow; // Make sure that our assumptions for storing a pointer + its size in `u64` is valid. #[cfg(all(not(feature = "std"), not(feature = "disable_target_static_assertions")))] @@ -337,7 +339,7 @@ impl IntoPreallocatedFFIValue for [u8; N] { } } -impl PassBy for sp_std::result::Result { +impl PassBy for core::result::Result { type PassBy = Codec; } diff --git a/substrate/primitives/runtime-interface/src/lib.rs b/substrate/primitives/runtime-interface/src/lib.rs index f6ef27789b36f08a6a5e7a58035304cab345737e..d6dcb69958af493185a3fd819e76701b57d79d54 100644 --- a/substrate/primitives/runtime-interface/src/lib.rs +++ b/substrate/primitives/runtime-interface/src/lib.rs @@ -111,6 +111,8 @@ extern crate self as sp_runtime_interface; +extern crate alloc; + #[doc(hidden)] #[cfg(feature = "std")] pub use sp_wasm_interface; diff --git a/substrate/primitives/runtime-interface/src/pass_by.rs b/substrate/primitives/runtime-interface/src/pass_by.rs index 103e9c16220542d5a9be5d85301bd45f7906e5e9..dce0b8e4bddb733df47dd83fa96423c85f3e2a53 100644 --- a/substrate/primitives/runtime-interface/src/pass_by.rs +++ b/substrate/primitives/runtime-interface/src/pass_by.rs @@ -33,10 +33,10 @@ use crate::wasm::*; #[cfg(feature = "std")] use sp_wasm_interface::{FunctionContext, Pointer, Result}; -use sp_std::marker::PhantomData; +use core::marker::PhantomData; #[cfg(not(feature = "std"))] -use sp_std::vec::Vec; +use alloc::vec::Vec; /// Derive macro for implementing [`PassBy`] with the [`Codec`] strategy. /// diff --git a/substrate/primitives/runtime-interface/test-wasm/Cargo.toml b/substrate/primitives/runtime-interface/test-wasm/Cargo.toml index 759ab99ceacc1ac393d9ae51c6aca3d65dd14f9f..77e77c707d9e66796a6042465dcc28c8af608773 100644 --- a/substrate/primitives/runtime-interface/test-wasm/Cargo.toml +++ b/substrate/primitives/runtime-interface/test-wasm/Cargo.toml @@ -20,7 +20,6 @@ bytes = { workspace = true } sp-core = { workspace = true } sp-io = { workspace = true } sp-runtime-interface = { workspace = true } -sp-std = { workspace = true } [build-dependencies] substrate-wasm-builder = { optional = true, workspace = true, default-features = true } @@ -32,6 +31,5 @@ std = [ "sp-core/std", "sp-io/std", "sp-runtime-interface/std", - "sp-std/std", "substrate-wasm-builder", ] diff --git a/substrate/primitives/runtime-interface/test-wasm/src/lib.rs b/substrate/primitives/runtime-interface/test-wasm/src/lib.rs index 2b3fc728f6ff46cc1332e413d8dee965f6ec7e3d..545f1ff4a115e1b3a381e5b3c85d74f19f41fbd0 100644 --- a/substrate/primitives/runtime-interface/test-wasm/src/lib.rs +++ b/substrate/primitives/runtime-interface/test-wasm/src/lib.rs @@ -19,11 +19,14 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + use sp_runtime_interface::runtime_interface; #[cfg(not(feature = "std"))] -use sp_std::{mem, prelude::*}; +use core::mem; +use alloc::{vec, vec::Vec}; use sp_core::{sr25519::Public, wasm_export_functions}; // Include the WASM binary @@ -229,7 +232,7 @@ wasm_export_functions! { fn test_invalid_utf8_data_should_return_an_error() { let data = vec![0, 159, 146, 150]; // I'm an evil hacker, trying to hack! - let data_str = unsafe { sp_std::str::from_utf8_unchecked(&data) }; + let data_str = unsafe { alloc::str::from_utf8_unchecked(&data) }; test_api::invalid_utf8_data(data_str); } diff --git a/substrate/primitives/runtime/src/generic/block.rs b/substrate/primitives/runtime/src/generic/block.rs index 05146e880cb16571d7eb56c61d8f6c318436d74a..8ed79c7c8dcf728094bc47cb7a58fc3eee93f585 100644 --- a/substrate/primitives/runtime/src/generic/block.rs +++ b/substrate/primitives/runtime/src/generic/block.rs @@ -31,8 +31,8 @@ use crate::{ }, Justifications, }; +use alloc::vec::Vec; use sp_core::RuntimeDebug; -use sp_std::prelude::*; /// Something to identify a block. #[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)] diff --git a/substrate/primitives/runtime/src/generic/digest.rs b/substrate/primitives/runtime/src/generic/digest.rs index d7db0f91a482110f6e9da53e0417657aaf579058..c639576a28670845fc265a0c78d1c9cd50544144 100644 --- a/substrate/primitives/runtime/src/generic/digest.rs +++ b/substrate/primitives/runtime/src/generic/digest.rs @@ -17,12 +17,11 @@ //! Generic implementation of a digest. +#[cfg(all(not(feature = "std"), feature = "serde"))] +use alloc::format; +use alloc::vec::Vec; #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; -#[cfg(all(not(feature = "std"), feature = "serde"))] -use sp_std::alloc::format; - -use sp_std::prelude::*; use crate::{ codec::{Decode, Encode, Error, Input}, diff --git a/substrate/primitives/runtime/src/generic/unchecked_extrinsic.rs b/substrate/primitives/runtime/src/generic/unchecked_extrinsic.rs index df1f5645f04827873fdee3e984f851d40b836c25..499b7c5f5836d21d67f8eb58c0ee41644a119180 100644 --- a/substrate/primitives/runtime/src/generic/unchecked_extrinsic.rs +++ b/substrate/primitives/runtime/src/generic/unchecked_extrinsic.rs @@ -26,12 +26,13 @@ use crate::{ transaction_validity::{InvalidTransaction, TransactionValidityError}, OpaqueExtrinsic, }; +#[cfg(all(not(feature = "std"), feature = "serde"))] +use alloc::format; +use alloc::{vec, vec::Vec}; use codec::{Compact, Decode, Encode, EncodeLike, Error, Input}; +use core::fmt; use scale_info::{build::Fields, meta_type, Path, StaticTypeInfo, Type, TypeInfo, TypeParameter}; use sp_io::hashing::blake2_256; -#[cfg(all(not(feature = "std"), feature = "serde"))] -use sp_std::alloc::format; -use sp_std::{fmt, prelude::*}; /// Current version of the [`UncheckedExtrinsic`] encoded format. /// @@ -316,7 +317,7 @@ where Extra: SignedExtension, { fn encode(&self) -> Vec { - let mut tmp = Vec::with_capacity(sp_std::mem::size_of::()); + let mut tmp = Vec::with_capacity(core::mem::size_of::()); // 1 byte version id. match self.signature.as_ref() { @@ -437,7 +438,7 @@ mod tests { type AdditionalSigned = (); type Pre = (); - fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> { + fn additional_signed(&self) -> core::result::Result<(), TransactionValidityError> { Ok(()) } diff --git a/substrate/primitives/runtime/src/lib.rs b/substrate/primitives/runtime/src/lib.rs index 046909b9a38d732a80f5178d228090fe10939c8d..d313d23395a0fa1b655dccaf94e30cacc1ac5c2a 100644 --- a/substrate/primitives/runtime/src/lib.rs +++ b/substrate/primitives/runtime/src/lib.rs @@ -45,6 +45,11 @@ #![warn(missing_docs)] #![cfg_attr(not(feature = "std"), no_std)] +#[doc(hidden)] +extern crate alloc; + +#[doc(hidden)] +pub use alloc::vec::Vec; #[doc(hidden)] pub use codec; #[doc(hidden)] @@ -73,12 +78,12 @@ use sp_core::{ hash::{H256, H512}, sr25519, }; -use sp_std::prelude::*; +#[cfg(all(not(feature = "std"), feature = "serde"))] +use alloc::format; +use alloc::vec; use codec::{Decode, Encode, MaxEncodedLen}; use scale_info::TypeInfo; -#[cfg(all(not(feature = "std"), feature = "serde"))] -use sp_std::alloc::format; pub mod curve; pub mod generic; @@ -191,7 +196,7 @@ impl Justifications { impl IntoIterator for Justifications { type Item = Justification; - type IntoIter = sp_std::vec::IntoIter; + type IntoIter = alloc::vec::IntoIter; fn into_iter(self) -> Self::IntoIter { self.0.into_iter() @@ -508,11 +513,11 @@ impl From for DispatchOutcome { /// This is the legacy return type of `Dispatchable`. It is still exposed for compatibility reasons. /// The new return type is `DispatchResultWithInfo`. FRAME runtimes should use /// `frame_support::dispatch::DispatchResult`. -pub type DispatchResult = sp_std::result::Result<(), DispatchError>; +pub type DispatchResult = core::result::Result<(), DispatchError>; /// Return type of a `Dispatchable` which contains the `DispatchResult` and additional information /// about the `Dispatchable` that is only known post dispatch. -pub type DispatchResultWithInfo = sp_std::result::Result>; +pub type DispatchResultWithInfo = core::result::Result>; /// Reason why a pallet call failed. #[derive(Eq, Clone, Copy, Encode, Decode, Debug, TypeInfo, MaxEncodedLen)] @@ -911,14 +916,14 @@ impl OpaqueExtrinsic { } } -impl sp_std::fmt::Debug for OpaqueExtrinsic { +impl core::fmt::Debug for OpaqueExtrinsic { #[cfg(feature = "std")] - fn fmt(&self, fmt: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, fmt: &mut core::fmt::Formatter) -> core::fmt::Result { write!(fmt, "{}", sp_core::hexdisplay::HexDisplay::from(&self.0)) } #[cfg(not(feature = "std"))] - fn fmt(&self, _fmt: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn fmt(&self, _fmt: &mut core::fmt::Formatter) -> core::fmt::Result { Ok(()) } } diff --git a/substrate/primitives/runtime/src/multiaddress.rs b/substrate/primitives/runtime/src/multiaddress.rs index c435606312e43ab0772ac71dd06f62489b416248..4382405a8ebc67bf8975cb35b99d18b7b213dd2b 100644 --- a/substrate/primitives/runtime/src/multiaddress.rs +++ b/substrate/primitives/runtime/src/multiaddress.rs @@ -17,8 +17,8 @@ //! MultiAddress type is a wrapper for multiple downstream account formats. +use alloc::vec::Vec; use codec::{Decode, Encode}; -use sp_std::vec::Vec; /// A multi-format address wrapper for on-chain accounts. #[derive(Encode, Decode, PartialEq, Eq, Clone, crate::RuntimeDebug, scale_info::TypeInfo)] diff --git a/substrate/primitives/runtime/src/offchain/http.rs b/substrate/primitives/runtime/src/offchain/http.rs index bacc0073825bb1412f63f07f0c92ddcbc81e080f..79899164540259ac2093012f9f40de161d9c7d6f 100644 --- a/substrate/primitives/runtime/src/offchain/http.rs +++ b/substrate/primitives/runtime/src/offchain/http.rs @@ -48,15 +48,13 @@ //! assert_eq!(body.error(), &None); //! ``` +use alloc::{str, vec, vec::Vec}; use sp_core::{ offchain::{ HttpError, HttpRequestId as RequestId, HttpRequestStatus as RequestStatus, Timestamp, }, RuntimeDebug, }; -#[cfg(not(feature = "std"))] -use sp_std::prelude::vec; -use sp_std::{prelude::Vec, str}; /// Request method (HTTP verb) #[derive(Clone, PartialEq, Eq, RuntimeDebug)] diff --git a/substrate/primitives/runtime/src/runtime_logger.rs b/substrate/primitives/runtime/src/runtime_logger.rs index 6f1e738eb0e7ab1e9841d56519e3d3cb7c20c40c..79984b13567250fe7c513c84f28e1276d1cc7ec8 100644 --- a/substrate/primitives/runtime/src/runtime_logger.rs +++ b/substrate/primitives/runtime/src/runtime_logger.rs @@ -53,7 +53,7 @@ impl log::Log for RuntimeLogger { } fn log(&self, record: &log::Record) { - use sp_std::fmt::Write; + use core::fmt::Write; let mut w = sp_std::Writer::default(); let _ = ::core::write!(&mut w, "{}", record.args()); diff --git a/substrate/primitives/runtime/src/runtime_string.rs b/substrate/primitives/runtime/src/runtime_string.rs index 607ae59db632f7d5044d48cae4dab4b78d24ad41..71aacf07a762e2fe0886bedae28b408079781ed4 100644 --- a/substrate/primitives/runtime/src/runtime_string.rs +++ b/substrate/primitives/runtime/src/runtime_string.rs @@ -15,9 +15,9 @@ // See the License for the specific language governing permissions and // limitations under the License. +use alloc::vec::Vec; use codec::{Decode, Encode}; use sp_core::RuntimeDebug; -use sp_std::vec::Vec; /// A string that wraps a `&'static str` in the runtime and `String`/`Vec` on decode. #[derive(Eq, RuntimeDebug, Clone)] @@ -50,7 +50,7 @@ macro_rules! format_runtime_string { } #[cfg(not(feature = "std"))] { - sp_runtime::RuntimeString::Owned(sp_std::alloc::format!($($args)*).as_bytes().to_vec()) + sp_runtime::RuntimeString::Owned(alloc::format!($($args)*).as_bytes().to_vec()) } }}; } diff --git a/substrate/primitives/runtime/src/traits.rs b/substrate/primitives/runtime/src/traits.rs index d023aa045dbe09e492bac2c8a8150d620348c37e..25ef15eaf56effe93f56e51b093626ce68679918 100644 --- a/substrate/primitives/runtime/src/traits.rs +++ b/substrate/primitives/runtime/src/traits.rs @@ -26,7 +26,10 @@ use crate::{ }, DispatchResult, }; +use alloc::vec::Vec; use codec::{Codec, Decode, Encode, EncodeLike, FullCodec, MaxEncodedLen}; +#[doc(hidden)] +pub use core::{fmt::Debug, marker::PhantomData}; use impl_trait_for_tuples::impl_for_tuples; #[cfg(feature = "serde")] use serde::{de::DeserializeOwned, Deserialize, Serialize}; @@ -44,9 +47,6 @@ pub use sp_core::{ parameter_types, ConstBool, ConstI128, ConstI16, ConstI32, ConstI64, ConstI8, ConstU128, ConstU16, ConstU32, ConstU64, ConstU8, Get, GetDefault, TryCollect, TypedGet, }; -#[doc(hidden)] -pub use sp_std::marker::PhantomData; -use sp_std::{self, fmt::Debug, prelude::*}; #[cfg(feature = "std")] use std::fmt::Display; #[cfg(feature = "std")] @@ -322,7 +322,7 @@ impl TryMorph for Identity { } /// Implementation of `Morph` which converts between types using `Into`. -pub struct MorphInto(sp_std::marker::PhantomData); +pub struct MorphInto(core::marker::PhantomData); impl> Morph for MorphInto { type Outcome = T; fn morph(a: A) -> T { @@ -331,7 +331,7 @@ impl> Morph for MorphInto { } /// Implementation of `TryMorph` which attempts to convert between types using `TryInto`. -pub struct TryMorphInto(sp_std::marker::PhantomData); +pub struct TryMorphInto(core::marker::PhantomData); impl> TryMorph for TryMorphInto { type Outcome = T; fn try_morph(a: A) -> Result { @@ -692,7 +692,7 @@ impl MaybeEquivalence for Tuple { /// Adapter which turns a [Get] implementation into a [Convert] implementation which always returns /// in the same value no matter the input. -pub struct ConvertToValue(sp_std::marker::PhantomData); +pub struct ConvertToValue(core::marker::PhantomData); impl> Convert for ConvertToValue { fn convert(_: X) -> Y { T::get() @@ -934,17 +934,17 @@ impl Clear for T { pub trait SimpleBitOps: Sized + Clear - + sp_std::ops::BitOr - + sp_std::ops::BitXor - + sp_std::ops::BitAnd + + core::ops::BitOr + + core::ops::BitXor + + core::ops::BitAnd { } impl< T: Sized + Clear - + sp_std::ops::BitOr - + sp_std::ops::BitXor - + sp_std::ops::BitAnd, + + core::ops::BitOr + + core::ops::BitXor + + core::ops::BitAnd, > SimpleBitOps for T { } @@ -988,7 +988,7 @@ pub trait HashOutput: + MaybeDisplay + MaybeFromStr + Debug - + sp_std::hash::Hash + + core::hash::Hash + AsRef<[u8]> + AsMut<[u8]> + Copy @@ -1008,7 +1008,7 @@ impl HashOutput for T where + MaybeDisplay + MaybeFromStr + Debug - + sp_std::hash::Hash + + core::hash::Hash + AsRef<[u8]> + AsMut<[u8]> + Copy @@ -1131,7 +1131,7 @@ sp_core::impl_maybe_marker!( trait MaybeFromStr: FromStr; /// A type that implements Hash when in std environment. - trait MaybeHash: sp_std::hash::Hash; + trait MaybeHash: core::hash::Hash; ); sp_core::impl_maybe_marker_std_or_serde!( @@ -1158,7 +1158,7 @@ pub trait BlockNumber: + MaybeSerializeDeserialize + MaybeFromStr + Debug - + sp_std::hash::Hash + + core::hash::Hash + Copy + MaybeDisplay + AtLeast32BitUnsigned @@ -1176,7 +1176,7 @@ impl< + MaybeSerializeDeserialize + MaybeFromStr + Debug - + sp_std::hash::Hash + + core::hash::Hash + Copy + MaybeDisplay + AtLeast32BitUnsigned @@ -1599,7 +1599,7 @@ pub trait SignedExtension: /// This method provides a default implementation that returns a vec containing a single /// [`SignedExtensionMetadata`]. fn metadata() -> Vec { - sp_std::vec![SignedExtensionMetadata { + alloc::vec![SignedExtensionMetadata { identifier: Self::IDENTIFIER, ty: scale_info::meta_type::(), additional_signed: scale_info::meta_type::() @@ -1702,7 +1702,7 @@ impl SignedExtension for () { type Call = (); type Pre = (); const IDENTIFIER: &'static str = "UnitSignedExtension"; - fn additional_signed(&self) -> sp_std::result::Result<(), TransactionValidityError> { + fn additional_signed(&self) -> core::result::Result<(), TransactionValidityError> { Ok(()) } fn pre_dispatch( @@ -2035,7 +2035,7 @@ macro_rules! impl_opaque_keys_inner { /// The generated key pairs are stored in the keystore. /// /// Returns the concatenated SCALE encoded public keys. - pub fn generate(seed: Option<$crate::sp_std::vec::Vec>) -> $crate::sp_std::vec::Vec { + pub fn generate(seed: Option<$crate::Vec>) -> $crate::Vec { let keys = Self{ $( $field: < @@ -2051,7 +2051,7 @@ macro_rules! impl_opaque_keys_inner { /// Converts `Self` into a `Vec` of `(raw public key, KeyTypeId)`. pub fn into_raw_public_keys( self, - ) -> $crate::sp_std::vec::Vec<($crate::sp_std::vec::Vec, $crate::KeyTypeId)> { + ) -> $crate::Vec<($crate::Vec, $crate::KeyTypeId)> { let mut keys = Vec::new(); $( keys.push(( @@ -2073,7 +2073,7 @@ macro_rules! impl_opaque_keys_inner { /// Returns `None` when the decoding failed, otherwise `Some(_)`. pub fn decode_into_raw_public_keys( encoded: &[u8], - ) -> Option<$crate::sp_std::vec::Vec<($crate::sp_std::vec::Vec, $crate::KeyTypeId)>> { + ) -> Option<$crate::Vec<($crate::Vec, $crate::KeyTypeId)>> { ::decode(&mut &encoded[..]) .ok() .map(|s| s.into_raw_public_keys()) diff --git a/substrate/primitives/runtime/src/transaction_validity.rs b/substrate/primitives/runtime/src/transaction_validity.rs index 836948493823cb4d137ce90721788e9a78a8ac99..ffff94e17461e88a842b1926e1fc92a4c86336b0 100644 --- a/substrate/primitives/runtime/src/transaction_validity.rs +++ b/substrate/primitives/runtime/src/transaction_validity.rs @@ -21,8 +21,8 @@ use crate::{ codec::{Decode, Encode}, RuntimeDebug, }; +use alloc::{vec, vec::Vec}; use scale_info::TypeInfo; -use sp_std::prelude::*; /// Priority for a transaction. Additive. Higher is better. pub type TransactionPriority = u64; diff --git a/substrate/primitives/staking/src/lib.rs b/substrate/primitives/staking/src/lib.rs index c1cf7f2778ff6ea4041c88f90bb48522d1f1c7e9..03c1af50240bbe229eaa28dfaf6f7b77458aff79 100644 --- a/substrate/primitives/staking/src/lib.rs +++ b/substrate/primitives/staking/src/lib.rs @@ -254,8 +254,8 @@ pub trait StakingInterface { /// schedules have reached their unlocking era should allow more calls to this function. fn unbond(stash: &Self::AccountId, value: Self::Balance) -> DispatchResult; - /// Update the reward destination for the ledger associated with the stash. - fn update_payee(stash: &Self::AccountId, reward_acc: &Self::AccountId) -> DispatchResult; + /// Set the reward destination for the ledger associated with the stash. + fn set_payee(stash: &Self::AccountId, reward_acc: &Self::AccountId) -> DispatchResult; /// Unlock any funds schedule to unlock before or at the current era. /// diff --git a/substrate/primitives/version/src/lib.rs b/substrate/primitives/version/src/lib.rs index 789c507742f779983b478ccd8bc9ff87a87d7165..55dea364eef4d7089859583005ca3ed7192b2c41 100644 --- a/substrate/primitives/version/src/lib.rs +++ b/substrate/primitives/version/src/lib.rs @@ -33,6 +33,8 @@ #![cfg_attr(not(feature = "std"), no_std)] +extern crate alloc; + #[cfg(feature = "serde")] use serde::{Deserialize, Serialize}; #[cfg(feature = "std")] @@ -40,6 +42,8 @@ use std::collections::HashSet; #[cfg(feature = "std")] use std::fmt; +#[doc(hidden)] +pub use alloc::borrow::Cow; use codec::{Decode, Encode, Input}; use scale_info::TypeInfo; use sp_runtime::RuntimeString; @@ -139,13 +143,13 @@ pub use sp_version_proc_macro::runtime_version; pub type ApiId = [u8; 8]; /// A vector of pairs of `ApiId` and a `u32` for version. -pub type ApisVec = sp_std::borrow::Cow<'static, [(ApiId, u32)]>; +pub type ApisVec = alloc::borrow::Cow<'static, [(ApiId, u32)]>; /// Create a vector of Api declarations. #[macro_export] macro_rules! create_apis_vec { ( $y:expr ) => { - $crate::sp_std::borrow::Cow::Borrowed(&$y) + $crate::Cow::Borrowed(&$y) }; } @@ -409,9 +413,9 @@ impl GetNativeVersion for std::sync::Arc { #[cfg(feature = "serde")] mod apis_serialize { use super::*; + use alloc::vec::Vec; use impl_serde::serialize as bytes; use serde::{de, ser::SerializeTuple, Serializer}; - use sp_std::vec::Vec; #[derive(Serialize)] struct ApiId<'a>(#[serde(serialize_with = "serialize_bytesref")] &'a super::ApiId, &'a u32); @@ -446,7 +450,7 @@ mod apis_serialize { impl<'de> de::Visitor<'de> for Visitor { type Value = ApisVec; - fn expecting(&self, formatter: &mut sp_std::fmt::Formatter) -> sp_std::fmt::Result { + fn expecting(&self, formatter: &mut core::fmt::Formatter) -> core::fmt::Result { formatter.write_str("a sequence of api id and version tuples") } diff --git a/substrate/test-utils/runtime/src/lib.rs b/substrate/test-utils/runtime/src/lib.rs index a13441302e4df119584c056b7e2e62552d7328d6..d1a3eaa2daa921b8092cf58a2118122ea1228260 100644 --- a/substrate/test-utils/runtime/src/lib.rs +++ b/substrate/test-utils/runtime/src/lib.rs @@ -27,7 +27,6 @@ pub mod extrinsic; pub mod genesismap; pub mod substrate_test_pallet; -use alloc::boxed::Box; #[cfg(not(feature = "std"))] use alloc::{vec, vec::Vec}; use codec::{Decode, Encode}; diff --git a/substrate/utils/wasm-builder/src/prerequisites.rs b/substrate/utils/wasm-builder/src/prerequisites.rs index 22caf8950637960310c62eb98c5358de55c1662d..4de6b87f618db66caf1095e47b93056f513b7663 100644 --- a/substrate/utils/wasm-builder/src/prerequisites.rs +++ b/substrate/utils/wasm-builder/src/prerequisites.rs @@ -102,7 +102,10 @@ impl<'a> DummyCrate<'a> { "#, ); - write_file_if_changed(project_dir.join("src/main.rs"), "fn main() {}"); + write_file_if_changed( + project_dir.join("src/main.rs"), + "#![allow(missing_docs)] fn main() {}", + ); DummyCrate { cargo_command, temp, manifest_path, target } } diff --git a/substrate/utils/wasm-builder/src/wasm_project.rs b/substrate/utils/wasm-builder/src/wasm_project.rs index ff6c8e38a332121d6e4c7fcdfa6fe4128867ac5a..20fa9fc1aa33e115d218b7cb8bd9d144c0a5d056 100644 --- a/substrate/utils/wasm-builder/src/wasm_project.rs +++ b/substrate/utils/wasm-builder/src/wasm_project.rs @@ -245,6 +245,12 @@ fn maybe_compact_and_compress_wasm( compact_blob_path.as_ref().and_then(|p| try_compress_blob(&p.0, blob_name)); (compact_blob_path, compact_compressed_blob_path) } else { + // We at least want to lower the `sign-ext` code to `mvp`. + wasm_opt::OptimizationOptions::new_opt_level_0() + .add_pass(wasm_opt::Pass::SignextLowering) + .run(bloaty_blob_binary.bloaty_path(), bloaty_blob_binary.bloaty_path()) + .expect("Failed to lower sign-ext in WASM binary."); + (None, None) }; @@ -783,9 +789,7 @@ impl BuildConfiguration { (None, false) => { let profile = Profile::Release; build_helper::warning!( - "Unknown cargo profile `{}`. Defaulted to `{:?}` for the runtime build.", - name, - profile, + "Unknown cargo profile `{name}`. Defaulted to `{profile:?}` for the runtime build.", ); profile }, @@ -793,8 +797,7 @@ impl BuildConfiguration { (None, true) => { // We use println! + exit instead of a panic in order to have a cleaner output. println!( - "Unexpected profile name: `{}`. One of the following is expected: {:?}", - name, + "Unexpected profile name: `{name}`. One of the following is expected: {:?}", Profile::iter().map(|p| p.directory()).collect::>(), ); process::exit(1); @@ -963,13 +966,16 @@ fn compact_wasm( .mvp_features_only() .debug_info(true) .add_pass(wasm_opt::Pass::StripDwarf) + .add_pass(wasm_opt::Pass::SignextLowering) .run(bloaty_binary.bloaty_path(), &wasm_compact_path) .expect("Failed to compact generated WASM binary."); + println!( "{} {}", colorize_info_message("Compacted wasm in"), colorize_info_message(format!("{:?}", start.elapsed()).as_str()) ); + Some(WasmBinary(wasm_compact_path)) } diff --git a/templates/minimal/runtime/src/lib.rs b/templates/minimal/runtime/src/lib.rs index 8c7867f4cc8cd1ec8b8435ec3c038e45da1a5700..08ad537ecdd1487586f919bcce63fa259946e738 100644 --- a/templates/minimal/runtime/src/lib.rs +++ b/templates/minimal/runtime/src/lib.rs @@ -23,6 +23,9 @@ #[cfg(feature = "std")] include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); +extern crate alloc; + +use alloc::{vec, vec::Vec}; use frame::{ deps::frame_support::{ genesis_builder_helper::{build_state, get_preset}, diff --git a/templates/parachain/pallets/template/Cargo.toml b/templates/parachain/pallets/template/Cargo.toml index 3b651ce427f9db87bd7c5a48c6a27714eb7df4c4..dde863101372e9b30a6aff3062618509b1743520 100644 --- a/templates/parachain/pallets/template/Cargo.toml +++ b/templates/parachain/pallets/template/Cargo.toml @@ -27,7 +27,6 @@ frame-system = { workspace = true } # primitive deps sp-runtime = { workspace = true } -sp-std = { workspace = true } [dev-dependencies] sp-core = { workspace = true, default-features = true } @@ -50,7 +49,6 @@ std = [ "frame-system/std", "sp-runtime/std", - "sp-std/std", ] try-runtime = [ "frame-support/try-runtime", diff --git a/templates/parachain/runtime/Cargo.toml b/templates/parachain/runtime/Cargo.toml index de0ecad9b06ee4543aaf1e7072c3d0362e81977f..939fa245d2a0c1b6e03ecd0541a2b9aa63af75bd 100644 --- a/templates/parachain/runtime/Cargo.toml +++ b/templates/parachain/runtime/Cargo.toml @@ -62,7 +62,6 @@ sp-inherents = { workspace = true } sp-offchain = { workspace = true } sp-runtime = { workspace = true } sp-session = { workspace = true } -sp-std = { workspace = true } sp-transaction-pool = { workspace = true } sp-version = { workspace = true } @@ -136,7 +135,6 @@ std = [ "sp-offchain/std", "sp-runtime/std", "sp-session/std", - "sp-std/std", "sp-transaction-pool/std", "sp-version/std", "substrate-wasm-builder", diff --git a/templates/parachain/runtime/src/apis.rs b/templates/parachain/runtime/src/apis.rs index bc3c3808fb78bcde9114e7aac4e6794136be1e12..f5d5d3e63027be2d7cdb20fb24bb4c6dcf3c25c9 100644 --- a/templates/parachain/runtime/src/apis.rs +++ b/templates/parachain/runtime/src/apis.rs @@ -24,6 +24,7 @@ // For more information, please refer to // External crates imports +use alloc::vec::Vec; use frame_support::{ genesis_builder_helper::{build_state, get_preset}, weights::Weight, @@ -37,7 +38,6 @@ use sp_runtime::{ transaction_validity::{TransactionSource, TransactionValidity}, ApplyExtrinsicResult, }; -use sp_std::prelude::Vec; use sp_version::RuntimeVersion; // Local module imports @@ -106,7 +106,7 @@ impl_runtime_apis! { Runtime::metadata_at_version(version) } - fn metadata_versions() -> sp_std::vec::Vec { + fn metadata_versions() -> Vec { Runtime::metadata_versions() } } @@ -264,7 +264,7 @@ impl_runtime_apis! { use frame_system_benchmarking::Pallet as SystemBench; impl frame_system_benchmarking::Config for Runtime { - fn setup_set_code_requirements(code: &sp_std::vec::Vec) -> Result<(), BenchmarkError> { + fn setup_set_code_requirements(code: &Vec) -> Result<(), BenchmarkError> { ParachainSystem::initialize_for_set_code_benchmark(code.len() as u32); Ok(()) } diff --git a/templates/parachain/runtime/src/lib.rs b/templates/parachain/runtime/src/lib.rs index 3a9fee38f245da179f2bf6c093740b64b4754ffb..f53871bb185025682eddaab519c8cefbab5011f4 100644 --- a/templates/parachain/runtime/src/lib.rs +++ b/templates/parachain/runtime/src/lib.rs @@ -12,6 +12,8 @@ mod benchmarks; mod configs; mod weights; +extern crate alloc; +use alloc::vec::Vec; use smallvec::smallvec; use sp_runtime::{ create_runtime_str, generic, impl_opaque_keys, @@ -19,7 +21,6 @@ use sp_runtime::{ MultiSignature, }; -use sp_std::prelude::*; #[cfg(feature = "std")] use sp_version::NativeVersion; use sp_version::RuntimeVersion; diff --git a/templates/solochain/runtime/Cargo.toml b/templates/solochain/runtime/Cargo.toml index 3bacac7863270a5fc83855b370f682328a3e3656..d883022105220ded56d57270a834512d9681545b 100644 --- a/templates/solochain/runtime/Cargo.toml +++ b/templates/solochain/runtime/Cargo.toml @@ -53,7 +53,6 @@ sp-runtime = { features = [ "serde", ], workspace = true } sp-session = { workspace = true } -sp-std = { workspace = true } sp-storage = { workspace = true } sp-transaction-pool = { workspace = true } sp-version = { features = [ @@ -102,7 +101,6 @@ std = [ "sp-offchain/std", "sp-runtime/std", "sp-session/std", - "sp-std/std", "sp-storage/std", "sp-transaction-pool/std", "sp-version/std", diff --git a/templates/solochain/runtime/src/lib.rs b/templates/solochain/runtime/src/lib.rs index 3487f052c1de84e6391a31f1af776f1cb0b8705e..69e54207e2f02ff5067b8ea0672c9fb45977a0b0 100644 --- a/templates/solochain/runtime/src/lib.rs +++ b/templates/solochain/runtime/src/lib.rs @@ -3,15 +3,11 @@ #[cfg(feature = "std")] include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); +extern crate alloc; +use alloc::{vec, vec::Vec}; use pallet_grandpa::AuthorityId as GrandpaId; use sp_consensus_aura::sr25519::AuthorityId as AuraId; use sp_core::crypto::KeyTypeId; -// use sp_runtime::{ -// create_runtime_str, generic, impl_opaque_keys, -// traits::{BlakeTwo256, Block as BlockT, IdentifyAccount, NumberFor, One, Verify}, -// transaction_validity::{TransactionSource, TransactionValidity}, -// MultiSignature, -// }; use sp_std::prelude::*; #[cfg(feature = "std")] use sp_version::NativeVersion; @@ -384,7 +380,7 @@ impl_runtime_apis! { Runtime::metadata_at_version(version) } - fn metadata_versions() -> sp_std::vec::Vec { + fn metadata_versions() -> Vec { Runtime::metadata_versions() } } diff --git a/umbrella/Cargo.toml b/umbrella/Cargo.toml index 94ba09421d409e5a2daee0c702499be3df2d4dcd..79e7c0c38edaa609ef594a9b5159ac92d4f5408c 100644 --- a/umbrella/Cargo.toml +++ b/umbrella/Cargo.toml @@ -269,6 +269,7 @@ runtime-benchmarks = [ "pallet-babe?/runtime-benchmarks", "pallet-bags-list?/runtime-benchmarks", "pallet-balances?/runtime-benchmarks", + "pallet-beefy-mmr?/runtime-benchmarks", "pallet-bounties?/runtime-benchmarks", "pallet-bridge-grandpa?/runtime-benchmarks", "pallet-bridge-messages?/runtime-benchmarks",