diff --git a/.config/taplo.toml b/.config/taplo.toml index 2c6ccfb2b34440686764c39ed6db1c73ed940f06..7cbc1b075125ad237f16d5d7dd33b0de7089ac38 100644 --- a/.config/taplo.toml +++ b/.config/taplo.toml @@ -33,3 +33,10 @@ keys = ["build"] [rule.formatting] reorder_arrays = false + +[[rule]] +include = ["Cargo.toml"] +keys = ["workspace.dependencies"] + +[rule.formatting] +reorder_keys = true diff --git a/.forklift/config-gitlab.toml b/.forklift/config-gitlab.toml new file mode 100644 index 0000000000000000000000000000000000000000..ab3b2729a46d4e54dc77df1175d4ebe79eda46d0 --- /dev/null +++ b/.forklift/config-gitlab.toml @@ -0,0 +1,33 @@ +[compression] +type = "zstd" + +[compression.zstd] +compressionLevel = 3 + +[general] +jobNameVariable = "CI_JOB_NAME" +jobsBlackList = [] +logLevel = "warn" +threadsCount = 6 + +[cache] +extraEnv = ["RUNTIME_METADATA_HASH"] + +[metrics] +enabled = true +pushEndpoint = "placeholder" + +[metrics.extraLabels] +environment = "production" +job_name = "$CI_JOB_NAME" +project_name = "$CI_PROJECT_PATH" + +[storage] +type = "s3" + +[storage.s3] +accessKeyId = "placeholder" +bucketName = "placeholder" +concurrency = 10 +endpointUrl = "placeholder" +secretAccessKey = "placeholder" diff --git a/.forklift/config.toml b/.forklift/config.toml index ab3b2729a46d4e54dc77df1175d4ebe79eda46d0..6f8eed8882ea36f39d1f0a519180f92eb905f7be 100644 --- a/.forklift/config.toml +++ b/.forklift/config.toml @@ -23,11 +23,7 @@ job_name = "$CI_JOB_NAME" project_name = "$CI_PROJECT_PATH" [storage] -type = "s3" +type = "gcs" -[storage.s3] -accessKeyId = "placeholder" -bucketName = "placeholder" -concurrency = 10 -endpointUrl = "placeholder" -secretAccessKey = "placeholder" +[storage.gcs] +bucketName = "parity-ci-forklift" diff --git a/.github/actions/set-up-gh/action.yml b/.github/actions/set-up-gh/action.yml new file mode 100644 index 0000000000000000000000000000000000000000..fc16ce0b26334283b83266e381c1811738be87c9 --- /dev/null +++ b/.github/actions/set-up-gh/action.yml @@ -0,0 +1,36 @@ +name: 'install gh' +description: 'Install the gh cli in a debian based distro and switches to the PR branch.' +inputs: + pr-number: + description: "Number of the PR" + required: true + GH_TOKEN: + description: "GitHub token" + required: true +outputs: + branch: + description: 'Branch name for the PR' + value: ${{ steps.branch.outputs.branch }} +runs: + using: "composite" + steps: + - name: Instal gh cli + shell: bash + # Here it would get the script from previous step + run: | + (type -p wget >/dev/null || (apt update && apt-get install wget -y)) + mkdir -p -m 755 /etc/apt/keyrings + wget -qO- https://cli.github.com/packages/githubcli-archive-keyring.gpg | tee /etc/apt/keyrings/githubcli-archive-keyring.gpg > /dev/null + chmod go+r /etc/apt/keyrings/githubcli-archive-keyring.gpg + echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | tee /etc/apt/sources.list.d/github-cli.list > /dev/null + apt update + apt install gh -y + git config --global --add safe.directory '*' + - run: gh pr checkout ${{ inputs.pr-number }} + shell: bash + env: + GITHUB_TOKEN: ${{ inputs.GH_TOKEN }} + - name: Export branch name + shell: bash + run: echo "branch=$(git rev-parse --abbrev-ref HEAD)" >> "$GITHUB_OUTPUT" + id: branch diff --git a/.github/command-screnshot.png b/.github/command-screnshot.png new file mode 100644 index 0000000000000000000000000000000000000000..1451fabca8b975534778e8321facd261e3b803fb Binary files /dev/null and b/.github/command-screnshot.png differ diff --git a/.github/commands-readme.md b/.github/commands-readme.md new file mode 100644 index 0000000000000000000000000000000000000000..bf0e9e5ed20bb3085e6bbe3e59079372121167b1 --- /dev/null +++ b/.github/commands-readme.md @@ -0,0 +1,199 @@ +# Running commands + +Command bot has been migrated, it is no longer a comment parser and now it is a GitHub action that works as a [`workflow_dispatch`](https://docs.github.com/en/actions/using-workflows/events-that-trigger-workflows#workflow_dispatch) event. + +## How to run an action + +To run an action, you need to go to the [_actions tab_](https://github.com/paritytech/polkadot-sdk/actions) and pick the one you desire to run. + +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 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) + +You need to select the action, and click on the dropdown that says: `Run workflow`. It is located in the upper right. + +If this dropdown is not visible, you may not have permission to run the action. Contact IT for help. + +![command screenshot](command-screnshot.png) + +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) + +### 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 + +### Bench + +Runs `benchmark pallet` or `benchmark overhead` against your PR and commits back updated weights. + +Posible combinations based on the `benchmark` dropdown. + +- `substrate-pallet`: Pallet Benchmark for Substrate for specific pallet + - Requires `Subcommand` to be `pallet` + - Requires `Runtime` to be `dev` + - Requires field `Pallet` to have an input that applies to `^([a-z_]+)([:]{2}[a-z_]+)?$` + - Requires `Target Directory` to be `substrate` +- `polkadot-pallet`: Pallet Benchmark for Polkadot for specific pallet + - Requires `Subcommand` to be one of the following: + - `pallet` + - `xcm` + - Requires `Runtime` to be one of the following: + - `rococo` + - `westend` + - Requires field `Pallet` to have an input that applies to `^([a-z_]+)([:]{2}[a-z_]+)?$` + - Requires `Target Directory` to be `polkadot` +- `cumulus-assets`: Pallet Benchmark for Cumulus assets + - Requires `Subcommand` to be one of the following: + - `pallet` + - `xcm` + - Requires `Runtime` to be one of the following: + - `asset-hub-westend` + - `asset-hub-rococo` + - Requires field `Pallet` to have an input that applies to `^([a-z_]+)([:]{2}[a-z_]+)?$` + - Requires `Runtime Dir` to be `assets` + - Requires `Target Directory` to be `cumulus` +- `cumulus-collectives`: Pallet Benchmark for Cumulus collectives + - Requires `Subcommand` to be one of the following: + - `pallet` + - `xcm` + - Requires `Runtime` to be `collectives-westend` + - Requires field `Pallet` to have an input that applies to `^([a-z_]+)([:]{2}[a-z_]+)?$` + - Requires `Runtime Dir` to be `collectives` + - Requires `Target Directory` to be `cumulus` +- `cumulus-coretime`: Pallet Benchmark for Cumulus coretime + - Requires `Subcommand` to be one of the following: + - `pallet` + - `xcm` + - Requires `Runtime` to be one of the following: + - `coretime-rococo` + - `coretime-westend` + - Requires field `Pallet` to have an input that applies to `^([a-z_]+)([:]{2}[a-z_]+)?$` + - Requires `Runtime Dir` to be `coretime` + - Requires `Target Directory` to be `cumulus` +- `cumulus-bridge-hubs`: Pallet Benchmark for Cumulus bridge-hubs + - Requires `Subcommand` to be one of the following: + - `pallet` + - `xcm` + - Requires `Runtime` to be one of the following: + - `bridge-hub-rococo` + - `bridge-hub-westend` + - Requires field `Pallet` to have an input that applies to `^([a-z_]+)([:]{2}[a-z_]+)?$` + - Requires `Runtime Dir` to be `bridge-hub` + - Requires `Target Directory` to be `cumulus` +- `cumulus-contracts`: Pallet Benchmark for Cumulus contracts + - Requires `Subcommand` to be one of the following: + - `pallet` + - `xcm` + - Requires `Runtime` to be one `contracts-rococo` + - Requires field `Pallet` to have an input that applies to `^([a-z_]+)([:]{2}[a-z_]+)?$` + - Requires `Runtime Dir` to be `contracts` + - Requires `Target Directory` to be `cumulus` +- `cumulus-glutton`: Pallet Benchmark for Cumulus glutton + - Requires `Subcommand` to be `pallet` + - Requires `Runtime` to be one of the following: + - `glutton-westend` + - `glutton-westend-dev-1300` + - Requires field `Pallet` to have an input that applies to `^([a-z_]+)([:]{2}[a-z_]+)?$` + - Requires `Runtime Dir` to be `glutton` + - Requires `Target Directory` to be `cumulus` +- `cumulus-starters`: Pallet Benchmark for Cumulus starters + - Requires `Subcommand` to be one of the following: + - `pallet` + - `xcm` + - Requires `Runtime` to be one of the following: + - `seedling` + - `shell` + - Requires field `Pallet` to have an input that applies to `^([a-z_]+)([:]{2}[a-z_]+)?$` + - Requires `Runtime Dir` to be `starters` + - Requires `Target Directory` to be `cumulus` +- `cumulus-people`: Pallet Benchmark for Cumulus people + - Requires `Subcommand` to be one of the following: + - `pallet` + - `xcm` + - Requires `Runtime` to be one of the following: + - `people-westend` + - `people-rococo` + - Requires field `Pallet` to have an input that applies to `^([a-z_]+)([:]{2}[a-z_]+)?$` + - Requires `Runtime Dir` to be `people` + - Requires `Target Directory` to be `cumulus` +- `cumulus-testing`: Pallet Benchmark for Cumulus testing + - Requires `Subcommand` to be one of the following: + - `pallet` + - `xcm` + - Requires `Runtime` to be one of the following: + - `penpal` + - `rococo-parachain` + - Requires field `Pallet` to have an input that applies to `^([a-z_]+)([:]{2}[a-z_]+)?$` + - Requires `Runtime Dir` to be `testing` + - Requires `Target Directory` to be `cumulus` + +### Bench-all + +This is a wrapper to run `bench` for all pallets. + +Posible combinations based on the `benchmark` dropdown. + +- `pallet`: Benchmark for Substrate/Polkadot/Cumulus/Trappist for specific pallet + - Requires field `Pallet` to have an input that applies to `^([a-z_]+)([:]{2}[a-z_]+)?$` +- `substrate`: Pallet + Overhead + Machine Benchmark for Substrate for all pallets + - Requires `Target Directory` to be `substrate` +- `polkadot`: Pallet + Overhead Benchmark for Polkadot + - Requires `Runtime` to be one of the following: + - `rococo` + - `westend` + - Requires `Target Directory` to be `polkadot` +- `cumulus`: Pallet Benchmark for Cumulus + - Requires `Runtime` to be one of the following: + - `rococo` + - `westend` + - `asset-hub-kusama` + - `asset-hub-polkadot` + - `asset-hub-rococo` + - `asset-hub-westend` + - `bridge-hub-kusama` + - `bridge-hub-polkadot` + - `bridge-hub-rococo` + - `bridge-hub-westend` + - `collectives-polkadot` + - `collectives-westend` + - `coretime-rococo` + - `coretime-westend` + - `contracts-rococo` + - `glutton-kusama` + - `glutton-westend` + - `people-rococo` + - `people-westend` + - Requires `Target Directory` to be `cumulus` + +### Bench-overhead + +Run benchmarks overhead and commit back results to PR. + +Posible combinations based on the `benchmark` dropdown. + +- `default`: Runs `benchmark overhead` and commits back to PR the updated `extrinsic_weights.rs` files + - Requires `Runtime` to be one of the following: + - `rococo` + - `westend` + - Requires `Target directory` to be `polkadot` +- `substrate`: Runs `benchmark overhead` and commits back to PR the updated `extrinsic_weights.rs` files + - Requires `Target directory` to be `substrate` +- `cumulus`: Runs `benchmark overhead` and commits back to PR the updated `extrinsic_weights.rs` files + - Requires `Runtime` to be one of the following: + - `asset-hub-rococo` + - `asset-hub-westend` + - Requires `Target directory` to be `cumulus` + +## 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. + +This will use a file from a specified branch. diff --git a/.github/review-bot.yml b/.github/review-bot.yml index ed719cefec8bc97c921e11a1751889433f0991ea..adbc480c6ba1a69e8cdd112af4be378849d26315 100644 --- a/.github/review-bot.yml +++ b/.github/review-bot.yml @@ -9,6 +9,7 @@ rules: - ^\.gitlab/.* - ^\.config/nextest.toml - ^\.cargo/.* + - ^\.forklift/.* exclude: - ^\.gitlab/pipeline/zombienet.* type: "or" @@ -33,6 +34,7 @@ rules: - ^docker/.* - ^\.github/.* - ^\.gitlab/.* + - ^\.forklift/.* - ^\.config/nextest.toml - ^\.cargo/.* minApprovals: 2 diff --git a/.github/scripts/check-workspace.py b/.github/scripts/check-workspace.py index 1f8f103e4e157a8c1c804a618652741193ca5a00..d5197100ad253ed18b9a4df255faa88598883f91 100644 --- a/.github/scripts/check-workspace.py +++ b/.github/scripts/check-workspace.py @@ -135,8 +135,12 @@ def check_links(all_crates): if dep_name in all_crates: links.append((name, dep_name)) - if not 'path' in deps[dep]: - broken.append((name, dep_name, "crate must be linked via `path`")) + if name == 'polkadot-sdk': + if not 'path' in deps[dep]: + broken.append((name, dep_name, "crate must use path")) + return + elif not 'workspace' in deps[dep] or not deps[dep]['workspace']: + broken.append((name, dep_name, "crate must use workspace inheritance")) return def check_crate(deps): @@ -154,8 +158,6 @@ def check_links(all_crates): check_crate(manifest) - - links.sort() broken.sort() diff --git a/.github/scripts/deny-git-deps.py b/.github/scripts/deny-git-deps.py index 4b831c9347f75bdc3c74c80d3af652c37e7ae459..622fc64c488123a153b438af8516f3fa65133776 100644 --- a/.github/scripts/deny-git-deps.py +++ b/.github/scripts/deny-git-deps.py @@ -19,6 +19,7 @@ KNOWN_BAD_GIT_DEPS = { root = sys.argv[1] if len(sys.argv) > 1 else os.getcwd() workspace = Workspace.from_path(root) +errors = [] def check_dep(dep, used_by): if dep.location != DependencyLocation.GIT: @@ -27,14 +28,23 @@ def check_dep(dep, used_by): if used_by in KNOWN_BAD_GIT_DEPS.get(dep.name, []): print(f'๐Ÿคจ Ignoring git dependency {dep.name} in {used_by}') else: - print(f'๐Ÿšซ Found git dependency {dep.name} in {used_by}') - sys.exit(1) + errors.append(f'๐Ÿšซ Found git dependency {dep.name} in {used_by}') # Check the workspace dependencies that can be inherited: for dep in workspace.dependencies: check_dep(dep, "workspace") + if workspace.crates.find_by_name(dep.name): + if dep.location != DependencyLocation.PATH: + errors.append(f'๐Ÿšซ Workspace must use path to link local dependency {dep.name}') + # And the dependencies of each crate: for crate in workspace.crates: for dep in crate.dependencies: check_dep(dep, crate.name) + +if errors: + print('โŒ Found errors:') + for error in errors: + print(error) + sys.exit(1) diff --git a/.github/workflows/check-runtime-migration.yml b/.github/workflows/check-runtime-migration.yml index 671673c02c09e0e0b5babceca6819c3ae7f05af7..33da5a8ecd591535eb0d4fe8b63cd8801699e988 100644 --- a/.github/workflows/check-runtime-migration.yml +++ b/.github/workflows/check-runtime-migration.yml @@ -11,13 +11,6 @@ concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true -env: - FORKLIFT_storage_s3_bucketName: ${{ secrets.FORKLIFT_storage_s3_bucketName }} - FORKLIFT_storage_s3_accessKeyId: ${{ secrets.FORKLIFT_storage_s3_accessKeyId }} - FORKLIFT_storage_s3_secretAccessKey: ${{ secrets.FORKLIFT_storage_s3_secretAccessKey }} - FORKLIFT_storage_s3_endpointUrl: ${{ secrets.FORKLIFT_storage_s3_endpointUrl }} - FORKLIFT_metrics_pushEndpoint: ${{ secrets.FORKLIFT_metrics_pushEndpoint }} - jobs: set-image: # GitHub Actions allows using 'env' in a container context. diff --git a/.github/workflows/check-semver.yml b/.github/workflows/check-semver.yml index 04c63f4192b29ca1773d1018698b2abe6a666e1c..12f2149cdf249ba9dedc7f23866650a0ab0a0ad7 100644 --- a/.github/workflows/check-semver.yml +++ b/.github/workflows/check-semver.yml @@ -19,14 +19,14 @@ jobs: with: cache-on-failure: true + - name: install parity-publish + run: cargo install parity-publish@0.6.0 + - name: Rust compilation prerequisites run: | - rustup default nightly-2024-03-01 - rustup target add wasm32-unknown-unknown --toolchain nightly-2024-03-01 - rustup component add rust-src --toolchain nightly-2024-03-01 - - - name: install parity-publish - run: cargo install parity-publish@0.5.1 + rustup default $(parity-publish semver --minimum-nightly-rust-version) + rustup target add wasm32-unknown-unknown --toolchain $(parity-publish semver --minimum-nightly-rust-version) + rustup component add rust-src --toolchain $(parity-publish semver --minimum-nightly-rust-version) - name: extra git setup run: | @@ -39,7 +39,7 @@ jobs: export CARGO_TARGET_DIR=target export RUSTFLAGS='-A warnings -A missing_docs' export SKIP_WASM_BUILD=1 - if ! parity-publish --color always prdoc --since old --validate prdoc/pr_$PR.prdoc --toolchain nightly-2024-03-01 -v; then + if ! parity-publish --color always prdoc --since old --validate prdoc/pr_$PR.prdoc -v; then cat < /dev/null - name: run zepter - run: zepter run check + run: | + zepter --version + time zepter run check test-rust-features: runs-on: ubuntu-latest timeout-minutes: 10 diff --git a/.github/workflows/command-bench-all.yml b/.github/workflows/command-bench-all.yml new file mode 100644 index 0000000000000000000000000000000000000000..b3fa0868c48797775c0ef8eff67e3acbd7f6facd --- /dev/null +++ b/.github/workflows/command-bench-all.yml @@ -0,0 +1,97 @@ +name: Command Bench All + +on: + workflow_dispatch: + inputs: + pr: + description: Number of the Pull Request + required: true + benchmark: + description: Pallet benchmark + type: choice + required: true + options: + - pallet + - substrate + - polkadot + - cumulus + pallet: + description: Pallet + required: false + type: string + default: pallet_name + target_dir: + description: Target directory + type: choice + options: + - substrate + - polkadot + - cumulus + runtime: + description: Runtime + type: choice + options: + - rococo + - westend + - asset-hub-kusama + - asset-hub-polkadot + - asset-hub-rococo + - asset-hub-westend + - bridge-hub-kusama + - bridge-hub-polkadot + - bridge-hub-rococo + - bridge-hub-westend + - collectives-polkadot + - collectives-westend + - coretime-rococo + - coretime-westend + - contracts-rococo + - glutton-kusama + - glutton-westend + - people-rococo + - people-westend + + +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-bench-all: + needs: [set-image] + runs-on: arc-runners-polkadot-sdk-benchmark + container: + image: ${{ needs.set-image.outputs.IMAGE }} + 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 bench all + run: | + "./scripts/bench-all.sh" "${{ inputs.benchmark }}" --runtime "${{ inputs.runtime }}" --pallet "${{ inputs.pallet }}" --target_dir "${{ inputs.target_dir }}" + - 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-bench-overhead.yml b/.github/workflows/command-bench-overhead.yml new file mode 100644 index 0000000000000000000000000000000000000000..735b401021061c3dde3dd065a12d9f6f538b8c93 --- /dev/null +++ b/.github/workflows/command-bench-overhead.yml @@ -0,0 +1,75 @@ +name: Command Bench Overhead + +on: + workflow_dispatch: + inputs: + pr: + description: Number of the Pull Request + required: true + benchmark: + description: Pallet benchmark + type: choice + required: true + options: + - default + - substrate + - cumulus + runtime: + description: Runtime + type: choice + options: + - rococo + - westend + - asset-hub-rococo + - asset-hub-westend + target_dir: + description: Target directory + type: choice + options: + - polkadot + - substrate + - cumulus + +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-bench-overhead: + needs: [set-image] + runs-on: arc-runners-polkadot-sdk-benchmark + container: + image: ${{ needs.set-image.outputs.IMAGE }} + 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 bench overhead + run: | + "./scripts/bench.sh" "${{ inputs.benchmark }}" --subcommand "overhead" --runtime "${{ inputs.runtime }}" --target_dir "${{ inputs.target_dir }}" + - 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-bench.yml b/.github/workflows/command-bench.yml new file mode 100644 index 0000000000000000000000000000000000000000..0ff166be48c193aa00e858b3bf7138b856487e24 --- /dev/null +++ b/.github/workflows/command-bench.yml @@ -0,0 +1,122 @@ +name: Command Bench + +on: + workflow_dispatch: + inputs: + pr: + description: Number of the Pull Request + required: true + benchmark: + description: Pallet benchmark + type: choice + required: true + options: + - substrate-pallet + - polkadot-pallet + - cumulus-assets + - cumulus-collectives + - cumulus-coretime + - cumulus-bridge-hubs + - cumulus-contracts + - cumulus-glutton + - cumulus-starters + - cumulus-people + - cumulus-testing + subcommand: + description: Subcommand + type: choice + required: true + options: + - pallet + - xcm + runtime: + description: Runtime + type: choice + options: + - dev + - rococo + - westend + - asset-hub-westend + - asset-hub-rococo + - collectives-westend + - coretime-rococo + - coretime-westend + - bridge-hub-rococo + - bridge-hub-westend + - contracts-rococo + - glutton-westend + - glutton-westend-dev-1300 + - seedling + - shell + - people-westend + - people-rococo + - penpal + - rococo-parachain + pallet: + description: Pallet + type: string + default: pallet_name + target_dir: + description: Target directory + type: choice + options: + - substrate + - polkadot + - cumulus + runtime_dir: + description: Runtime directory + type: choice + options: + - people + - collectives + - coretime + - bridge-hubs + - contracts + - glutton + - starters + - testing + + +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-bench: + needs: [set-image] + runs-on: arc-runners-polkadot-sdk-benchmark + container: + image: ${{ needs.set-image.outputs.IMAGE }} + 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 bench + run: | + "./scripts/bench.sh" "${{ inputs.benchmark }}" --runtime "${{ inputs.runtime }}" --pallet "${{ inputs.pallet }}" --target_dir "${{ inputs.target_dir }}" --subcommand "${{ inputs.subcommand }}" --runtime_dir "${{ inputs.runtime_dir }}" + - 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-fmt.yml b/.github/workflows/command-fmt.yml new file mode 100644 index 0000000000000000000000000000000000000000..d415007d938390ded98a95f5f5c8ecc61fb0dc84 --- /dev/null +++ b/.github/workflows/command-fmt.yml @@ -0,0 +1,54 @@ +name: Command FMT + +on: + workflow_dispatch: + inputs: + pr: + description: Number of the Pull Request + required: true + +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-fmt: + needs: [set-image] + runs-on: ubuntu-latest + container: + image: ${{ needs.set-image.outputs.IMAGE }} + 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 FMT + run: | + # format toml. + # since paritytech/ci-unified:bullseye-1.73.0-2023-11-01-v20231204 includes taplo-cli + taplo format --config .config/taplo.toml + - 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-inform.yml b/.github/workflows/command-inform.yml new file mode 100644 index 0000000000000000000000000000000000000000..1c7323c998dfee3ba822f4bcb655c57a958fd80f --- /dev/null +++ b/.github/workflows/command-inform.yml @@ -0,0 +1,15 @@ +name: Inform of new command action + +on: + issue_comment: + types: [created] + +jobs: + comment: + runs-on: ubuntu-latest + 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 }} diff --git a/.github/workflows/command-update-ui.yml b/.github/workflows/command-update-ui.yml new file mode 100644 index 0000000000000000000000000000000000000000..9b9c45c5c0b9d78f0287b8d00314e0c58fff0c69 --- /dev/null +++ b/.github/workflows/command-update-ui.yml @@ -0,0 +1,55 @@ +name: Command Update UI + +on: + workflow_dispatch: + inputs: + pr: + description: Number of the Pull Request + required: true + rust-version: + description: Version of rust. Example 1.70 + required: false + +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-update-ui: + needs: [set-image] + runs-on: arc-runners-polkadot-sdk-beefy + container: + image: ${{ needs.set-image.outputs.IMAGE }} + 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 update-ui + run: | + "./scripts/update-ui-tests.sh" "${{ inputs.rust-version }}" + - 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/publish-check-crates.yml b/.github/workflows/publish-check-crates.yml index 9b5b89e34475699ccbcaeca34cd290882ee45a9a..33cf9316920048c65c70376557586d905fd7c9a6 100644 --- a/.github/workflows/publish-check-crates.yml +++ b/.github/workflows/publish-check-crates.yml @@ -20,7 +20,7 @@ jobs: cache-on-failure: true - name: install parity-publish - run: cargo install parity-publish@0.5.1 + run: cargo install parity-publish@0.6.0 - name: parity-publish check run: parity-publish --color always check --allow-unpublished diff --git a/.github/workflows/publish-claim-crates.yml b/.github/workflows/publish-claim-crates.yml index 9643361d9d318f84d64a212358a825a8e0b5aa20..08c50638267ba3be596b5b563433fccf28c2652b 100644 --- a/.github/workflows/publish-claim-crates.yml +++ b/.github/workflows/publish-claim-crates.yml @@ -18,7 +18,7 @@ jobs: cache-on-failure: true - name: install parity-publish - run: cargo install parity-publish@0.5.1 + run: cargo install parity-publish@0.6.0 - name: parity-publish claim env: diff --git a/.github/workflows/release-30_publish_release_draft.yml b/.github/workflows/release-30_publish_release_draft.yml index f39eb4c1716ebea4fb3207ea1a2ecc8227037448..20492f2d3a9104fd08af663d19aed9a301918e6c 100644 --- a/.github/workflows/release-30_publish_release_draft.yml +++ b/.github/workflows/release-30_publish_release_draft.yml @@ -31,7 +31,8 @@ jobs: runs-on: ubuntu-latest strategy: matrix: - binary: [ frame-omni-bencher, chain-spec-builder ] + # Tuples of [package, binary-name] + binary: [ [frame-omni-bencher, frame-omni-bencher], [staging-chain-spec-builder, chain-spec-builder] ] steps: - name: Checkout sources uses: actions/checkout@3df4ab11eba7bda6032a0b82a6bb43b11571feac # v4.0.0 @@ -41,21 +42,16 @@ jobs: sudo apt update sudo apt install -y protobuf-compiler - - name: Build ${{ matrix.binary }} binary + - name: Build ${{ matrix.binary[1] }} binary run: | - if [[ ${{ matrix.binary }} =~ chain-spec-builder ]]; then - cargo build --locked --profile=production -p staging-${{ matrix.binary }} --bin ${{ matrix.binary }} - target/production/${{ matrix.binary }} -h - else - cargo build --locked --profile=production -p ${{ matrix.binary }} - target/production/${{ matrix.binary }} --version - fi + cargo build --locked --profile=production -p ${{ matrix.binary[0] }} --bin ${{ matrix.binary[1] }} + target/production/${{ matrix.binary[1] }} --version - - name: Upload ${{ matrix.binary }} binary + - name: Upload ${{ matrix.binary[1] }} binary uses: actions/upload-artifact@5d5d22a31266ced268874388b861e4b58bb5c2f3 # v4.3.1 with: - name: ${{ matrix.binary }} - path: target/production/${{ matrix.binary }} + name: ${{ matrix.binary[1] }} + path: target/production/${{ matrix.binary[1] }} publish-release-draft: diff --git a/.github/workflows/release-clobber-stable.yml b/.github/workflows/release-clobber-stable.yml new file mode 100644 index 0000000000000000000000000000000000000000..643c14daa15b1aa7501e27f272524e0ee010e781 --- /dev/null +++ b/.github/workflows/release-clobber-stable.yml @@ -0,0 +1,70 @@ +name: Clobber Stable + +# This action implements the +# [Clobbering](https://github.com/paritytech/polkadot-sdk/blob/master/docs/RELEASE.md#clobbering) +# process from the release process. It pushes a new commit to the `stable` branch with all the +# current content of the `audited` tag. It does not use a merge commit, but rather 'clobbers' the +# branch with a single commit that contains all the changes. It has a naming scheme of `Clobber with +# audited ($COMMIT)`. +# Currently, the script is only triggered manually, but can be easily changed to a schedule. + +on: + workflow_dispatch: + +permissions: + contents: write + +jobs: + clobber-stable: + runs-on: ubuntu-latest + timeout-minutes: 5 + env: + STABLE: stable + UNSTABLE: master + AUDITED: audited + steps: + - name: Checkout + uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1 + + - name: Prechecks + run: | + # Properly fetch + git fetch --prune --unshallow origin tag $AUDITED + git fetch origin $STABLE + + # Sanity checks + git checkout -q tags/$AUDITED || (echo "Could not find the '$AUDITED' tag." && exit 1) + COMMIT=$(git rev-parse tags/$AUDITED) + #$(git branch --contains $COMMIT | grep -q $UNSTABLE) || (echo "The '$AUDITED' tag is not on the '$UNSTABLE' branch." && exit 1) + + git config --global user.email "admin@parity.io" + git config --global user.name "Parity Release Team" + + - name: Prepare commit + run: | + git checkout --quiet origin/$STABLE + + # Delete all tracked files in the working directory + git ls-files -z | xargs -0 rm -f + + # Find and delete any empty directories + find . -type d -empty -delete + + git add . 1>/dev/null 2>/dev/null + git commit -qm "Delete all files" + + # Grab the files from the commit + git checkout --quiet tags/$AUDITED -- . + + # Stage, commit, and push the working directory which now matches 'audited' 1:1 + git status + COMMIT=$(git rev-parse --short=10 tags/$AUDITED) + git add . 1>/dev/null 2>/dev/null + git commit --allow-empty --amend -qm "Clobber with $AUDITED ($COMMIT)" + + - name: Push stable branch + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + git log -3 + git push --verbose origin HEAD:$STABLE diff --git a/.github/workflows/release-srtool.yml b/.github/workflows/release-srtool.yml index 95b1846b98e0c47cc6de2c92cadc16adc0cab487..69a4bdbdda9ae87a188a23bceb9185d813424a98 100644 --- a/.github/workflows/release-srtool.yml +++ b/.github/workflows/release-srtool.yml @@ -6,8 +6,6 @@ env: on: push: - tags: - - "*" branches: - release-v[0-9]+.[0-9]+.[0-9]+* - release-cumulus-v[0-9]+* diff --git a/.github/workflows/tests-linux-stable.yml b/.github/workflows/tests-linux-stable.yml index 5fdfabc437fe721339af817f12aea1a58a6c0346..6f2ac87c3efbea16efc9a5564fa770cd0f9ffbdf 100644 --- a/.github/workflows/tests-linux-stable.yml +++ b/.github/workflows/tests-linux-stable.yml @@ -12,15 +12,7 @@ concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true -env: - FORKLIFT_storage_s3_bucketName: ${{ secrets.FORKLIFT_storage_s3_bucketName }} - FORKLIFT_storage_s3_accessKeyId: ${{ secrets.FORKLIFT_storage_s3_accessKeyId }} - FORKLIFT_storage_s3_secretAccessKey: ${{ secrets.FORKLIFT_storage_s3_secretAccessKey }} - FORKLIFT_storage_s3_endpointUrl: ${{ secrets.FORKLIFT_storage_s3_endpointUrl }} - FORKLIFT_metrics_pushEndpoint: ${{ secrets.FORKLIFT_metrics_pushEndpoint }} - jobs: - changes: permissions: pull-requests: read @@ -31,7 +23,7 @@ jobs: # However, env variables don't work for forks: https://github.com/orgs/community/discussions/44322 # This workaround sets the container image for each job using 'set-image' job output. needs: changes - if: ${{ needs.changes.outputs.rust }} + if: ${{ needs.changes.outputs.rust }} runs-on: ubuntu-latest outputs: IMAGE: ${{ steps.set_image.outputs.IMAGE }} @@ -40,10 +32,10 @@ jobs: uses: actions/checkout@v4 - id: set_image run: cat .github/env >> $GITHUB_OUTPUT - + test-linux-stable-int: needs: [set-image, changes] - if: ${{ needs.changes.outputs.rust }} + if: ${{ needs.changes.outputs.rust }} runs-on: arc-runners-polkadot-sdk-beefy timeout-minutes: 30 container: @@ -60,11 +52,11 @@ jobs: uses: actions/checkout@v4 - name: script run: WASM_BUILD_NO_COLOR=1 time forklift cargo test -p staging-node-cli --release --locked -- --ignored - + # https://github.com/paritytech/ci_cd/issues/864 test-linux-stable-runtime-benchmarks: needs: [set-image, changes] - if: ${{ needs.changes.outputs.rust }} + if: ${{ needs.changes.outputs.rust }} runs-on: arc-runners-polkadot-sdk-beefy timeout-minutes: 30 container: diff --git a/.github/workflows/tests.yml b/.github/workflows/tests.yml index 293acadc4e6a892fea9aa7fa3686cd821606992a..0c1447cba33a372cbbf4cb057b9f63dd49565468 100644 --- a/.github/workflows/tests.yml +++ b/.github/workflows/tests.yml @@ -11,15 +11,7 @@ concurrency: group: ${{ github.workflow }}-${{ github.event.pull_request.number || github.ref }} cancel-in-progress: true -env: - FORKLIFT_storage_s3_bucketName: ${{ secrets.FORKLIFT_storage_s3_bucketName }} - FORKLIFT_storage_s3_accessKeyId: ${{ secrets.FORKLIFT_storage_s3_accessKeyId }} - FORKLIFT_storage_s3_secretAccessKey: ${{ secrets.FORKLIFT_storage_s3_secretAccessKey }} - FORKLIFT_storage_s3_endpointUrl: ${{ secrets.FORKLIFT_storage_s3_endpointUrl }} - FORKLIFT_metrics_pushEndpoint: ${{ secrets.FORKLIFT_metrics_pushEndpoint }} - jobs: - changes: permissions: pull-requests: read @@ -40,7 +32,7 @@ jobs: quick-benchmarks: needs: [set-image, changes] - if: ${{ needs.changes.outputs.rust }} + if: ${{ needs.changes.outputs.rust }} runs-on: arc-runners-polkadot-sdk-beefy timeout-minutes: 30 container: @@ -55,11 +47,11 @@ jobs: uses: actions/checkout@v4 - name: script run: time forklift cargo run --locked --release -p staging-node-cli --bin substrate-node --features runtime-benchmarks -- benchmark pallet --chain dev --pallet "*" --extrinsic "*" --steps 2 --repeat 1 --quiet - + # cf https://github.com/paritytech/polkadot-sdk/issues/1652 test-syscalls: needs: [set-image, changes] - if: ${{ needs.changes.outputs.rust }} + if: ${{ needs.changes.outputs.rust }} runs-on: arc-runners-polkadot-sdk-beefy timeout-minutes: 30 container: @@ -81,10 +73,10 @@ jobs: # - if [[ "$CI_JOB_STATUS" == "failed" ]]; then # printf "The x86_64 syscalls used by the worker binaries have changed. Please review if this is expected and update polkadot/scripts/list-syscalls/*-worker-syscalls as needed.\n"; # fi - + cargo-check-all-benches: needs: [set-image, changes] - if: ${{ needs.changes.outputs.rust }} + if: ${{ needs.changes.outputs.rust }} runs-on: arc-runners-polkadot-sdk-beefy timeout-minutes: 30 container: diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 73a8c52c448f72d12e510d65b2f7ff38469856f0..7f2babc6bd47237032b941a6bf9de4a91b031932 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -120,7 +120,8 @@ default: .forklift-cache: before_script: - mkdir ~/.forklift - - cp .forklift/config.toml ~/.forklift/config.toml + - cp .forklift/config-gitlab.toml ~/.forklift/config.toml + - cat .forklift/config-gitlab.toml > .forklift/config.toml - > if [ "$FORKLIFT_BYPASS" != "true" ]; then echo "FORKLIFT_BYPASS not set"; diff --git a/.gitlab/pipeline/zombienet/polkadot.yml b/.gitlab/pipeline/zombienet/polkadot.yml index b158cbe0b5aa3a50d490129dab87c9e7d6769b35..90251082077ce07f739a5b122deaf6023dcfeaa6 100644 --- a/.gitlab/pipeline/zombienet/polkadot.yml +++ b/.gitlab/pipeline/zombienet/polkadot.yml @@ -162,6 +162,9 @@ zombienet-polkadot-elastic-scaling-0001-basic-3cores-6s-blocks: - .zombienet-polkadot-common variables: FORCED_INFRA_INSTANCE: "spot-iops" + before_script: + - !reference [.zombienet-polkadot-common, before_script] + - cp --remove-destination ${LOCAL_DIR}/assign-core.js ${LOCAL_DIR}/elastic_scaling script: - /home/nonroot/zombie-net/scripts/ci/run-test-local-env-manager.sh --local-dir="${LOCAL_DIR}/elastic_scaling" @@ -170,6 +173,9 @@ zombienet-polkadot-elastic-scaling-0001-basic-3cores-6s-blocks: zombienet-polkadot-elastic-scaling-0002-elastic-scaling-doesnt-break-parachains: extends: - .zombienet-polkadot-common + before_script: + - !reference [.zombienet-polkadot-common, before_script] + - cp --remove-destination ${LOCAL_DIR}/assign-core.js ${LOCAL_DIR}/elastic_scaling script: - /home/nonroot/zombie-net/scripts/ci/run-test-local-env-manager.sh --local-dir="${LOCAL_DIR}/elastic_scaling" @@ -199,6 +205,17 @@ zombienet-polkadot-functional-0014-chunk-fetching-network-compatibility: --local-dir="${LOCAL_DIR}/functional" --test="0014-chunk-fetching-network-compatibility.zndsl" +zombienet-polkadot-functional-0015-coretime-shared-core: + extends: + - .zombienet-polkadot-common + before_script: + - !reference [.zombienet-polkadot-common, before_script] + - cp --remove-destination ${LOCAL_DIR}/assign-core.js ${LOCAL_DIR}/functional + script: + - /home/nonroot/zombie-net/scripts/ci/run-test-local-env-manager.sh + --local-dir="${LOCAL_DIR}/functional" + --test="0015-coretime-shared-core.zndsl" + zombienet-polkadot-smoke-0001-parachains-smoke-test: extends: - .zombienet-polkadot-common diff --git a/Cargo.lock b/Cargo.lock index a96bb680b750b287f6b424311cb1a63d0d598b11..171b443d8159d0a7cbb3e310e810645cc4737ea9 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -294,6 +294,9 @@ name = "arbitrary" version = "1.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d5a26814d8dcb93b0e5a0ff3c6d80a8843bafb21b39e8e18a6f05471870e110" +dependencies = [ + "derive_arbitrary", +] [[package]] name = "ark-bls12-377" @@ -820,6 +823,7 @@ dependencies = [ "pallet-asset-conversion-ops", "pallet-asset-conversion-tx-payment", "pallet-assets", + "pallet-assets-freezer", "pallet-aura", "pallet-authorship", "pallet-balances", @@ -867,7 +871,7 @@ dependencies = [ "staging-xcm-executor", "substrate-wasm-builder", "testnet-parachains-constants", - "xcm-fee-payment-runtime-api", + "xcm-runtime-apis", ] [[package]] @@ -917,7 +921,7 @@ dependencies = [ "staging-xcm-executor", "westend-runtime", "westend-system-emulated-network", - "xcm-fee-payment-runtime-api", + "xcm-runtime-apis", ] [[package]] @@ -953,6 +957,7 @@ dependencies = [ "pallet-asset-conversion-ops", "pallet-asset-conversion-tx-payment", "pallet-assets", + "pallet-assets-freezer", "pallet-aura", "pallet-authorship", "pallet-balances", @@ -999,7 +1004,7 @@ dependencies = [ "substrate-wasm-builder", "testnet-parachains-constants", "westend-runtime-constants", - "xcm-fee-payment-runtime-api", + "xcm-runtime-apis", ] [[package]] @@ -1071,7 +1076,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "81953c529336010edd6d8e358f886d9581267795c61b19475b71314bffa46d35" dependencies = [ "concurrent-queue", - "event-listener", + "event-listener 2.5.3", "futures-core", ] @@ -1081,11 +1086,11 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6fa3dc5f2a8564f07759c008b9109dc0d39de92a88d5588b8a5036d286383afb" dependencies = [ - "async-lock", + "async-lock 2.8.0", "async-task", "concurrent-queue", "fastrand 1.9.0", - "futures-lite", + "futures-lite 1.13.0", "slab", ] @@ -1095,10 +1100,10 @@ version = "1.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "279cf904654eeebfa37ac9bb1598880884924aab82e290aa65c9e77a0e142e06" dependencies = [ - "async-lock", + "async-lock 2.8.0", "autocfg", "blocking", - "futures-lite", + "futures-lite 1.13.0", ] [[package]] @@ -1109,10 +1114,10 @@ checksum = "f1b6f5d7df27bd294849f8eec66ecfc63d11814df7a4f5d74168a2394467b776" dependencies = [ "async-channel", "async-executor", - "async-io", - "async-lock", + "async-io 1.13.0", + "async-lock 2.8.0", "blocking", - "futures-lite", + "futures-lite 1.13.0", "once_cell", ] @@ -1122,27 +1127,57 @@ version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fc5b45d93ef0529756f812ca52e44c221b35341892d3dcc34132ac02f3dd2af" dependencies = [ - "async-lock", + "async-lock 2.8.0", "autocfg", "cfg-if", "concurrent-queue", - "futures-lite", + "futures-lite 1.13.0", "log", "parking", - "polling", + "polling 2.8.0", "rustix 0.37.23", "slab", "socket2 0.4.9", "waker-fn", ] +[[package]] +name = "async-io" +version = "2.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d6baa8f0178795da0e71bc42c9e5d13261aac7ee549853162e66a241ba17964" +dependencies = [ + "async-lock 3.4.0", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite 2.3.0", + "parking", + "polling 3.4.0", + "rustix 0.38.21", + "slab", + "tracing", + "windows-sys 0.52.0", +] + [[package]] name = "async-lock" version = "2.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "287272293e9d8c41773cec55e365490fe034813a2f172f502d6ddcf75b2f582b" dependencies = [ - "event-listener", + "event-listener 2.5.3", +] + +[[package]] +name = "async-lock" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff6e472cdea888a4bd64f342f09b3f50e1886d32afe8df3d663c01140b811b18" +dependencies = [ + "event-listener 5.2.0", + "event-listener-strategy", + "pin-project-lite 0.2.12", ] [[package]] @@ -1151,10 +1186,10 @@ version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4051e67316bc7eff608fe723df5d32ed639946adcd69e07df41fd42a7b411f1f" dependencies = [ - "async-io", + "async-io 1.13.0", "autocfg", "blocking", - "futures-lite", + "futures-lite 1.13.0", ] [[package]] @@ -1163,13 +1198,13 @@ version = "1.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a9d28b1d97e08915212e2e45310d47854eafa69600756fc735fb788f75199c9" dependencies = [ - "async-io", - "async-lock", + "async-io 1.13.0", + "async-lock 2.8.0", "autocfg", "blocking", "cfg-if", - "event-listener", - "futures-lite", + "event-listener 2.5.3", + "futures-lite 1.13.0", "rustix 0.37.23", "signal-hook", "windows-sys 0.48.0", @@ -1184,13 +1219,13 @@ dependencies = [ "async-attributes", "async-channel", "async-global-executor", - "async-io", - "async-lock", + "async-io 1.13.0", + "async-lock 2.8.0", "crossbeam-utils", "futures-channel", "futures-core", "futures-io", - "futures-lite", + "futures-lite 1.13.0", "gloo-timers", "kv-log-macro", "log", @@ -1266,6 +1301,17 @@ version = "1.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1181e1e0d1fce796a03db1ae795d67167da795f9cf4a39c37589e85ef57f26d3" +[[package]] +name = "attohttpc" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d9a9bf8b79a749ee0b911b91b671cc2b6c670bdbc7e3dfd537576ddc94bb2a2" +dependencies = [ + "http 0.2.9", + "log", + "url", +] + [[package]] name = "atty" version = "0.2.14" @@ -1368,6 +1414,12 @@ version = "0.21.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "604178f6c5c21f02dc555784810edfb88d34ac2c73b2eae109655649ee73ce3d" +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + [[package]] name = "base64ct" version = "1.6.0" @@ -1490,9 +1542,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" [[package]] name = "bitflags" -version = "2.4.0" +version = "2.6.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4682ae6287fcf752ecaabbfcc7b6f9b72aa33933dc23a554d853aea8eea8635" +checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de" [[package]] name = "bitvec" @@ -1598,11 +1650,11 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77231a1c8f801696fc0123ec6150ce92cffb8e164a02afb9c8ddee0e9b65ad65" dependencies = [ "async-channel", - "async-lock", + "async-lock 2.8.0", "async-task", "atomic-waker", "fastrand 1.9.0", - "futures-lite", + "futures-lite 1.13.0", "log", ] @@ -2098,8 +2150,7 @@ dependencies = [ "static_assertions", "substrate-wasm-builder", "testnet-parachains-constants", - "tuplex", - "xcm-fee-payment-runtime-api", + "xcm-runtime-apis", ] [[package]] @@ -2258,9 +2309,8 @@ dependencies = [ "static_assertions", "substrate-wasm-builder", "testnet-parachains-constants", - "tuplex", "westend-runtime-constants", - "xcm-fee-payment-runtime-api", + "xcm-runtime-apis", ] [[package]] @@ -2447,6 +2497,12 @@ dependencies = [ "libc", ] +[[package]] +name = "cesu8" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + [[package]] name = "cexpr" version = "0.6.0" @@ -2896,7 +2952,7 @@ dependencies = [ "substrate-wasm-builder", "testnet-parachains-constants", "westend-runtime-constants", - "xcm-fee-payment-runtime-api", + "xcm-runtime-apis", ] [[package]] @@ -3152,7 +3208,7 @@ dependencies = [ "staging-xcm-executor", "substrate-wasm-builder", "testnet-parachains-constants", - "xcm-fee-payment-runtime-api", + "xcm-runtime-apis", ] [[package]] @@ -3163,9 +3219,9 @@ checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" [[package]] name = "core-foundation" -version = "0.9.3" +version = "0.9.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "194a7a9e6de53fa55116934067c844d9d749312f75c6f6d0980e8c252f8c2146" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" dependencies = [ "core-foundation-sys", "libc", @@ -3173,9 +3229,9 @@ dependencies = [ [[package]] name = "core-foundation-sys" -version = "0.8.4" +version = "0.8.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e496a50fda8aacccc86d7529e2c1e0892dbd0f898a6b5645b5561b89c3210efa" +checksum = "06ea2b9bc92be3c2baa9334a323ebca2d6f074ff852cd1d7b11064035cd3868f" [[package]] name = "core2" @@ -3249,7 +3305,7 @@ dependencies = [ "staging-xcm-executor", "substrate-wasm-builder", "testnet-parachains-constants", - "xcm-fee-payment-runtime-api", + "xcm-runtime-apis", ] [[package]] @@ -3314,7 +3370,7 @@ dependencies = [ "substrate-wasm-builder", "testnet-parachains-constants", "westend-runtime-constants", - "xcm-fee-payment-runtime-api", + "xcm-runtime-apis", ] [[package]] @@ -3675,6 +3731,7 @@ dependencies = [ "cumulus-relay-chain-interface", "futures", "parity-scale-codec", + "parking_lot 0.12.1", "polkadot-node-primitives", "polkadot-node-subsystem", "polkadot-overseer", @@ -3730,6 +3787,7 @@ dependencies = [ "sp-timestamp", "sp-tracing 16.0.0", "sp-trie", + "sp-version", "substrate-prometheus-endpoint", "tracing", ] @@ -3784,12 +3842,15 @@ dependencies = [ "parity-scale-codec", "parking_lot 0.12.1", "polkadot-node-primitives", + "polkadot-node-subsystem", "polkadot-parachain-primitives", "polkadot-primitives", "polkadot-test-client", "portpicker", + "rstest", "sc-cli", "sc-client-api", + "sp-api", "sp-blockchain", "sp-consensus", "sp-core", @@ -3797,6 +3858,7 @@ dependencies = [ "sp-keystore", "sp-runtime", "sp-state-machine", + "sp-version", "substrate-test-utils", "tokio", "tracing", @@ -3830,9 +3892,11 @@ dependencies = [ name = "cumulus-client-pov-recovery" version = "0.7.0" dependencies = [ + "assert_matches", "async-trait", "cumulus-primitives-core", "cumulus-relay-chain-interface", + "cumulus-test-client", "cumulus-test-service", "futures", "futures-timer", @@ -3843,12 +3907,18 @@ dependencies = [ "polkadot-primitives", "portpicker", "rand 0.8.5", + "rstest", "sc-cli", "sc-client-api", "sc-consensus", + "sc-utils", + "sp-api", + "sp-blockchain", "sp-consensus", "sp-maybe-compressed-blob", "sp-runtime", + "sp-tracing 16.0.0", + "sp-version", "substrate-test-utils", "tokio", "tracing", @@ -4219,6 +4289,7 @@ dependencies = [ "sp-api", "sp-blockchain", "sp-state-machine", + "sp-version", "thiserror", ] @@ -4521,16 +4592,15 @@ dependencies = [ [[package]] name = "curve25519-dalek" -version = "4.1.2" +version = "4.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a677b8922c94e01bdbb12126b0bc852f00447528dee1782229af9c720c3f348" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" dependencies = [ "cfg-if", "cpufeatures", "curve25519-dalek-derive", "digest 0.10.7", "fiat-crypto", - "platforms", "rustc_version 0.4.0", "subtle 2.5.0", "zeroize", @@ -4678,9 +4748,12 @@ dependencies = [ [[package]] name = "deranged" -version = "0.3.8" +version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f2696e8a945f658fd14dc3b87242e6b80cd0f36ff04ea560fa39082368847946" +checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" +dependencies = [ + "powerfmt", +] [[package]] name = "derivative" @@ -4715,6 +4788,17 @@ dependencies = [ "syn 2.0.61", ] +[[package]] +name = "derive_arbitrary" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67e77553c4162a157adbf834ebae5b415acbecbeafc7a74b0e886657506a7611" +dependencies = [ + "proc-macro2 1.0.82", + "quote 1.0.35", + "syn 2.0.61", +] + [[package]] name = "derive_more" version = "0.99.17" @@ -4992,7 +5076,7 @@ version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a3daa8e81a3963a60642bcc1f90a670680bd4a77535faa384e9d1c79d620871" dependencies = [ - "curve25519-dalek 4.1.2", + "curve25519-dalek 4.1.3", "ed25519 2.2.2", "rand_core 0.6.4", "serde", @@ -5007,7 +5091,7 @@ version = "4.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7d9ce6874da5d4415896cd45ffbc4d1cfc0c4f9c079427bd870742c30f2f65a9" dependencies = [ - "curve25519-dalek 4.1.2", + "curve25519-dalek 4.1.3", "ed25519 2.2.2", "hashbrown 0.14.3", "hex", @@ -5164,19 +5248,6 @@ dependencies = [ "regex", ] -[[package]] -name = "env_logger" -version = "0.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a12e6657c4c97ebab115a42dcee77225f7f482cdd841cf7088c657a42e9e00e7" -dependencies = [ - "atty", - "humantime", - "log", - "regex", - "termcolor", -] - [[package]] name = "env_logger" version = "0.10.1" @@ -5317,6 +5388,27 @@ version = "2.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0206175f82b8d6bf6652ff7d71a1e27fd2e4efde587fd368662814d6ec1d9ce0" +[[package]] +name = "event-listener" +version = "5.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b5fb89194fa3cad959b833185b3063ba881dbfc7030680b314250779fb4cc91" +dependencies = [ + "concurrent-queue", + "parking", + "pin-project-lite 0.2.12", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f214dc438f977e6d4e3500aaa277f5ad94ca83fbbd9b1a15713ce2344ccc5a1" +dependencies = [ + "event-listener 5.2.0", + "pin-project-lite 0.2.12", +] + [[package]] name = "exit-future" version = "0.2.0" @@ -5557,7 +5649,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c6c98ee8095e9d1dcbf2fcc6d95acccb90d1c81db1e44725c6a984b1dbdfb010" dependencies = [ "crc32fast", - "libz-sys", "miniz_oxide", ] @@ -5922,7 +6013,7 @@ dependencies = [ "frame-support-procedural-tools", "itertools 0.11.0", "macro_magic", - "proc-macro-warning", + "proc-macro-warning 1.0.0", "proc-macro2 1.0.82", "quote 1.0.35", "regex", @@ -6124,6 +6215,16 @@ dependencies = [ "futures-util", ] +[[package]] +name = "futures-bounded" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b07bbbe7d7e78809544c6f718d875627addc73a7c3582447abc052cd3dc67e0" +dependencies = [ + "futures-timer", + "futures-util", +] + [[package]] name = "futures-channel" version = "0.3.30" @@ -6173,6 +6274,16 @@ dependencies = [ "waker-fn", ] +[[package]] +name = "futures-lite" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52527eb5074e35e9339c6b4e8d12600c7128b68fb25dcb9fa9dec18f7c25f3a5" +dependencies = [ + "futures-core", + "pin-project-lite 0.2.12", +] + [[package]] name = "futures-macro" version = "0.3.30" @@ -6186,13 +6297,12 @@ dependencies = [ [[package]] name = "futures-rustls" -version = "0.22.2" +version = "0.24.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d2411eed028cdf8c8034eaf21f9915f956b6c3abec4d4c7949ee67f0721127bd" +checksum = "35bd3cf68c183738046838e300353e4716c674dc5e56890de4826801a6622a28" dependencies = [ "futures-io", - "rustls 0.20.8", - "webpki", + "rustls 0.21.7", ] [[package]] @@ -6450,7 +6560,26 @@ dependencies = [ "futures-core", "futures-sink", "futures-util", - "http", + "http 0.2.9", + "indexmap 2.2.3", + "slab", + "tokio", + "tokio-util", + "tracing", +] + +[[package]] +name = "h2" +version = "0.4.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa82e28a107a8cc405f0839610bdc9b15f1e25ec7d696aa5cf173edbcb1486ab" +dependencies = [ + "atomic-waker", + "bytes", + "fnv", + "futures-core", + "futures-sink", + "http 1.1.0", "indexmap 2.2.3", "slab", "tokio", @@ -6658,6 +6787,17 @@ dependencies = [ "itoa", ] +[[package]] +name = "http" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21b9ddb458710bc376481b842f5da65cdf31522de232c1ca8146abce2a358258" +dependencies = [ + "bytes", + "fnv", + "itoa", +] + [[package]] name = "http-body" version = "0.4.5" @@ -6665,15 +6805,32 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d5f38f16d184e36f2408a55281cd658ecbd3ca05cce6d6510a176eca393e26d1" dependencies = [ "bytes", - "http", + "http 0.2.9", "pin-project-lite 0.2.12", ] [[package]] -name = "http-range-header" -version = "0.3.1" +name = "http-body" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1cac85db508abc24a2e48553ba12a996e87244a0395ce011e62b37158745d643" +dependencies = [ + "bytes", + "http 1.1.0", +] + +[[package]] +name = "http-body-util" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "add0ab9360ddbd88cfeb3bd9574a1d85cfdfa14db10b3e21d3700dbc4328758f" +checksum = "793429d76616a256bcb62c2a2ec2bed781c8307e797e2598c50010f2bee2544f" +dependencies = [ + "bytes", + "futures-util", + "http 1.1.0", + "http-body 1.0.0", + "pin-project-lite 0.2.12", +] [[package]] name = "httparse" @@ -6703,9 +6860,9 @@ dependencies = [ "futures-channel", "futures-core", "futures-util", - "h2", - "http", - "http-body", + "h2 0.3.26", + "http 0.2.9", + "http-body 0.4.5", "httparse", "httpdate", "itoa", @@ -6717,6 +6874,27 @@ dependencies = [ "want", ] +[[package]] +name = "hyper" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe575dd17d0862a9a33781c8c4696a55c320909004a67a00fb286ba8b1bc496d" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "h2 0.4.5", + "http 1.1.0", + "http-body 1.0.0", + "httparse", + "httpdate", + "itoa", + "pin-project-lite 0.2.12", + "smallvec", + "tokio", + "want", +] + [[package]] name = "hyper-rustls" version = "0.24.1" @@ -6724,15 +6902,53 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8d78e1e73ec14cf7375674f74d7dde185c8206fd9dea6fb6295e8a98098aaa97" dependencies = [ "futures-util", - "http", - "hyper", + "http 0.2.9", + "hyper 0.14.27", "log", - "rustls 0.21.6", + "rustls 0.21.7", "rustls-native-certs 0.6.3", "tokio", "tokio-rustls 0.24.1", ] +[[package]] +name = "hyper-rustls" +version = "0.27.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ee4be2c948921a1a5320b629c4193916ed787a7f7f293fd3f7f5a6c9de74155" +dependencies = [ + "futures-util", + "http 1.1.0", + "hyper 1.3.1", + "hyper-util", + "log", + "rustls 0.23.10", + "rustls-pki-types", + "tokio", + "tokio-rustls 0.26.0", + "tower-service", +] + +[[package]] +name = "hyper-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7b875924a60b96e5d7b9ae7b066540b1dd1cbd90d1828f54c92e02a283351c56" +dependencies = [ + "bytes", + "futures-channel", + "futures-util", + "http 1.1.0", + "http-body 1.0.0", + "hyper 1.3.1", + "pin-project-lite 0.2.12", + "socket2 0.5.6", + "tokio", + "tower", + "tower-service", + "tracing", +] + [[package]] name = "iana-time-zone" version = "0.1.57" @@ -6779,21 +6995,21 @@ dependencies = [ [[package]] name = "if-addrs" -version = "0.7.0" +version = "0.10.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cbc0fa01ffc752e9dbc72818cdb072cd028b86be5e09dd04c5a643704fe101a9" +checksum = "cabb0019d51a643781ff15c9c8a3e5dedc365c47211270f4e8f82812fedd8f0a" dependencies = [ "libc", - "winapi", + "windows-sys 0.48.0", ] [[package]] name = "if-watch" -version = "3.0.1" +version = "3.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a9465340214b296cd17a0009acdb890d6160010b8adf8f78a00d0d7ab270f79f" +checksum = "d6b0422c86d7ce0e97169cc42e04ae643caf278874a7a3c87b8150a220dc7e1e" dependencies = [ - "async-io", + "async-io 2.3.3", "core-foundation", "fnv", "futures", @@ -6803,7 +7019,26 @@ dependencies = [ "rtnetlink", "system-configuration", "tokio", - "windows 0.34.0", + "windows 0.51.1", +] + +[[package]] +name = "igd-next" +version = "0.14.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "064d90fec10d541084e7b39ead8875a5a80d9114a2b18791565253bae25f49e4" +dependencies = [ + "async-trait", + "attohttpc", + "bytes", + "futures", + "http 0.2.9", + "hyper 0.14.27", + "log", + "rand 0.8.5", + "tokio", + "url", + "xmltree", ] [[package]] @@ -7020,13 +7255,13 @@ dependencies = [ "curl", "curl-sys", "encoding_rs", - "event-listener", - "futures-lite", - "http", + "event-listener 2.5.3", + "futures-lite 1.13.0", + "http 0.2.9", "log", "mime", "once_cell", - "polling", + "polling 2.8.0", "slab", "sluice", "tracing", @@ -7059,6 +7294,26 @@ version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "af150ab688ff2122fcef229be89cb50dd66af9e01a4ff320cc137eecc9bacc38" +[[package]] +name = "jni" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6df18c2e3db7e453d3c6ac5b3e9d5182664d28788126d39b91f2d1e22b017ec" +dependencies = [ + "cesu8", + "combine", + "jni-sys", + "log", + "thiserror", + "walkdir", +] + +[[package]] +name = "jni-sys" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eaf4bc02d17cbdd7ff4c7438cafcdf7fb9a4613313ad11b4f8fefe7d3fa0130" + [[package]] name = "jobserver" version = "0.1.26" @@ -7096,9 +7351,9 @@ dependencies = [ [[package]] name = "jsonrpsee" -version = "0.22.5" +version = "0.23.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfdb12a2381ea5b2e68c3469ec604a007b367778cdb14d09612c8069ebd616ad" +checksum = "62b089779ad7f80768693755a031cc14a7766aba707cbe886674e3f79e9b7e47" dependencies = [ "jsonrpsee-core", "jsonrpsee-http-client", @@ -7112,20 +7367,22 @@ dependencies = [ [[package]] name = "jsonrpsee-client-transport" -version = "0.22.5" +version = "0.23.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4978087a58c3ab02efc5b07c5e5e2803024536106fd5506f558db172c889b3aa" +checksum = "08163edd8bcc466c33d79e10f695cdc98c00d1e6ddfb95cec41b6b0279dd5432" dependencies = [ + "base64 0.22.1", "futures-util", - "http", + "http 1.1.0", "jsonrpsee-core", "pin-project", - "rustls-native-certs 0.7.0", + "rustls 0.23.10", "rustls-pki-types", - "soketto", + "rustls-platform-verifier", + "soketto 0.8.0", "thiserror", "tokio", - "tokio-rustls 0.25.0", + "tokio-rustls 0.26.0", "tokio-util", "tracing", "url", @@ -7133,16 +7390,19 @@ dependencies = [ [[package]] name = "jsonrpsee-core" -version = "0.22.5" +version = "0.23.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b4b257e1ec385e07b0255dde0b933f948b5c8b8c28d42afda9587c3a967b896d" +checksum = "79712302e737d23ca0daa178e752c9334846b08321d439fd89af9a384f8c830b" dependencies = [ "anyhow", "async-trait", "beef", + "bytes", "futures-timer", "futures-util", - "hyper", + "http 1.1.0", + "http-body 1.0.0", + "http-body-util", "jsonrpsee-types", "parking_lot 0.12.1", "pin-project", @@ -7158,15 +7418,20 @@ dependencies = [ [[package]] name = "jsonrpsee-http-client" -version = "0.22.5" +version = "0.23.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ccf93fc4a0bfe05d851d37d7c32b7f370fe94336b52a2f0efc5f1981895c2e5" +checksum = "2d90064e04fb9d7282b1c71044ea94d0bbc6eff5621c66f1a0bce9e9de7cf3ac" dependencies = [ "async-trait", - "hyper", - "hyper-rustls", + "base64 0.22.1", + "http-body 1.0.0", + "hyper 1.3.1", + "hyper-rustls 0.27.2", + "hyper-util", "jsonrpsee-core", "jsonrpsee-types", + "rustls 0.23.10", + "rustls-platform-verifier", "serde", "serde_json", "thiserror", @@ -7178,11 +7443,11 @@ dependencies = [ [[package]] name = "jsonrpsee-proc-macros" -version = "0.22.5" +version = "0.23.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7d0bb047e79a143b32ea03974a6bf59b62c2a4c5f5d42a381c907a8bbb3f75c0" +checksum = "7895f186d5921065d96e16bd795e5ca89ac8356ec423fafc6e3d7cf8ec11aee4" dependencies = [ - "heck 0.4.1", + "heck 0.5.0", "proc-macro-crate 3.1.0", "proc-macro2 1.0.82", "quote 1.0.35", @@ -7191,20 +7456,24 @@ dependencies = [ [[package]] name = "jsonrpsee-server" -version = "0.22.5" +version = "0.23.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "12d8b6a9674422a8572e0b0abb12feeb3f2aeda86528c80d0350c2bd0923ab41" +checksum = "654afab2e92e5d88ebd8a39d6074483f3f2bfdf91c5ac57fe285e7127cdd4f51" dependencies = [ + "anyhow", "futures-util", - "http", - "hyper", + "http 1.1.0", + "http-body 1.0.0", + "http-body-util", + "hyper 1.3.1", + "hyper-util", "jsonrpsee-core", "jsonrpsee-types", "pin-project", "route-recognizer", "serde", "serde_json", - "soketto", + "soketto 0.8.0", "thiserror", "tokio", "tokio-stream", @@ -7215,12 +7484,12 @@ dependencies = [ [[package]] name = "jsonrpsee-types" -version = "0.22.5" +version = "0.23.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "150d6168405890a7a3231a3c74843f58b8959471f6df76078db2619ddee1d07d" +checksum = "d9c465fbe385238e861fdc4d1c85e04ada6c1fd246161d26385c1b311724d2af" dependencies = [ - "anyhow", "beef", + "http 1.1.0", "serde", "serde_json", "thiserror", @@ -7228,11 +7497,11 @@ dependencies = [ [[package]] name = "jsonrpsee-ws-client" -version = "0.22.5" +version = "0.23.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "58b9db2dfd5bb1194b0ce921504df9ceae210a345bc2f6c5a61432089bbab070" +checksum = "1c28759775f5cb2f1ea9667672d3fe2b0e701d1f4b7b67954e60afe7fd058b5e" dependencies = [ - "http", + "http 1.1.0", "jsonrpsee-client-transport", "jsonrpsee-core", "jsonrpsee-types", @@ -7441,11 +7710,12 @@ dependencies = [ [[package]] name = "libp2p" -version = "0.51.4" +version = "0.52.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f35eae38201a993ece6bdc823292d6abd1bffed1c4d0f4a3517d2bd8e1d917fe" +checksum = "e94495eb319a85b70a68b85e2389a95bb3555c71c49025b78c691a854a7e6464" dependencies = [ "bytes", + "either", "futures", "futures-timer", "getrandom 0.2.10", @@ -7465,18 +7735,21 @@ dependencies = [ "libp2p-request-response", "libp2p-swarm", "libp2p-tcp", + "libp2p-upnp", "libp2p-wasm-ext", "libp2p-websocket", "libp2p-yamux", - "multiaddr", + "multiaddr 0.18.1", "pin-project", + "rw-stream-sink", + "thiserror", ] [[package]] name = "libp2p-allow-block-list" -version = "0.1.1" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "510daa05efbc25184458db837f6f9a5143888f1caa742426d92e1833ddd38a50" +checksum = "55b46558c5c0bf99d3e2a1a38fd54ff5476ca66dd1737b12466a1824dd219311" dependencies = [ "libp2p-core", "libp2p-identity", @@ -7486,9 +7759,9 @@ dependencies = [ [[package]] name = "libp2p-connection-limits" -version = "0.1.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4caa33f1d26ed664c4fe2cca81a08c8e07d4c1c04f2f4ac7655c2dd85467fda0" +checksum = "2f5107ad45cb20b2f6c3628c7b6014b996fcb13a88053f4569c872c6e30abf58" dependencies = [ "libp2p-core", "libp2p-identity", @@ -7498,9 +7771,9 @@ dependencies = [ [[package]] name = "libp2p-core" -version = "0.39.2" +version = "0.40.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3c1df63c0b582aa434fb09b2d86897fa2b419ffeccf934b36f87fcedc8e835c2" +checksum = "dd44289ab25e4c9230d9246c475a22241e301b23e8f4061d3bdef304a1a99713" dependencies = [ "either", "fnv", @@ -7509,8 +7782,8 @@ dependencies = [ "instant", "libp2p-identity", "log", - "multiaddr", - "multihash 0.17.0", + "multiaddr 0.18.1", + "multihash 0.19.1", "multistream-select", "once_cell", "parking_lot 0.12.1", @@ -7526,33 +7799,36 @@ dependencies = [ [[package]] name = "libp2p-dns" -version = "0.39.0" +version = "0.40.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "146ff7034daae62077c415c2376b8057368042df6ab95f5432ad5e88568b1554" +checksum = "e6a18db73084b4da2871438f6239fef35190b05023de7656e877c18a00541a3b" dependencies = [ + "async-trait", "futures", "libp2p-core", + "libp2p-identity", "log", "parking_lot 0.12.1", "smallvec", - "trust-dns-resolver 0.22.0", + "trust-dns-resolver", ] [[package]] name = "libp2p-identify" -version = "0.42.2" +version = "0.43.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5455f472243e63b9c497ff320ded0314254a9eb751799a39c283c6f20b793f3c" +checksum = "45a96638a0a176bec0a4bcaebc1afa8cf909b114477209d7456ade52c61cd9cd" dependencies = [ "asynchronous-codec", "either", "futures", + "futures-bounded", "futures-timer", "libp2p-core", "libp2p-identity", "libp2p-swarm", "log", - "lru 0.10.1", + "lru 0.12.3", "quick-protobuf", "quick-protobuf-codec", "smallvec", @@ -7562,27 +7838,27 @@ dependencies = [ [[package]] name = "libp2p-identity" -version = "0.1.3" +version = "0.2.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "276bb57e7af15d8f100d3c11cbdd32c6752b7eef4ba7a18ecf464972c07abcce" +checksum = "999ec70441b2fb35355076726a6bc466c932e9bdc66f6a11c6c0aa17c7ab9be0" dependencies = [ - "bs58 0.4.0", + "bs58 0.5.0", "ed25519-dalek 2.1.1", - "log", - "multiaddr", - "multihash 0.17.0", + "hkdf", + "multihash 0.19.1", "quick-protobuf", "rand 0.8.5", "sha2 0.10.8", "thiserror", + "tracing", "zeroize", ] [[package]] name = "libp2p-kad" -version = "0.43.3" +version = "0.44.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39d5ef876a2b2323d63c258e63c2f8e36f205fe5a11f0b3095d59635650790ff" +checksum = "16ea178dabba6dde6ffc260a8e0452ccdc8f79becf544946692fff9d412fc29d" dependencies = [ "arrayvec 0.7.4", "asynchronous-codec", @@ -7597,6 +7873,7 @@ dependencies = [ "libp2p-swarm", "log", "quick-protobuf", + "quick-protobuf-codec", "rand 0.8.5", "sha2 0.10.8", "smallvec", @@ -7608,9 +7885,9 @@ dependencies = [ [[package]] name = "libp2p-mdns" -version = "0.43.1" +version = "0.44.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "19983e1f949f979a928f2c603de1cf180cc0dc23e4ac93a62651ccb18341460b" +checksum = "42a2567c305232f5ef54185e9604579a894fd0674819402bb0ac0246da82f52a" dependencies = [ "data-encoding", "futures", @@ -7621,7 +7898,7 @@ dependencies = [ "log", "rand 0.8.5", "smallvec", - "socket2 0.4.9", + "socket2 0.5.6", "tokio", "trust-dns-proto 0.22.0", "void", @@ -7629,30 +7906,35 @@ dependencies = [ [[package]] name = "libp2p-metrics" -version = "0.12.0" +version = "0.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a42ec91e227d7d0dafa4ce88b333cdf5f277253873ab087555c92798db2ddd46" +checksum = "239ba7d28f8d0b5d77760dc6619c05c7e88e74ec8fbbe97f856f20a56745e620" dependencies = [ + "instant", "libp2p-core", "libp2p-identify", + "libp2p-identity", "libp2p-kad", "libp2p-ping", "libp2p-swarm", + "once_cell", "prometheus-client", ] [[package]] name = "libp2p-noise" -version = "0.42.2" +version = "0.43.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9c3673da89d29936bc6435bafc638e2f184180d554ce844db65915113f86ec5e" +checksum = "d2eeec39ad3ad0677551907dd304b2f13f17208ccebe333bef194076cd2e8921" dependencies = [ "bytes", - "curve25519-dalek 3.2.0", + "curve25519-dalek 4.1.3", "futures", "libp2p-core", "libp2p-identity", "log", + "multiaddr 0.18.1", + "multihash 0.19.1", "once_cell", "quick-protobuf", "rand 0.8.5", @@ -7660,21 +7942,22 @@ dependencies = [ "snow", "static_assertions", "thiserror", - "x25519-dalek 1.1.1", + "x25519-dalek", "zeroize", ] [[package]] name = "libp2p-ping" -version = "0.42.0" +version = "0.43.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e57759c19c28a73ef1eb3585ca410cefb72c1a709fcf6de1612a378e4219202" +checksum = "e702d75cd0827dfa15f8fd92d15b9932abe38d10d21f47c50438c71dd1b5dae3" dependencies = [ "either", "futures", "futures-timer", "instant", "libp2p-core", + "libp2p-identity", "libp2p-swarm", "log", "rand 0.8.5", @@ -7683,9 +7966,9 @@ dependencies = [ [[package]] name = "libp2p-quic" -version = "0.7.0-alpha.3" +version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c6b26abd81cd2398382a1edfe739b539775be8a90fa6914f39b2ab49571ec735" +checksum = "130d451d83f21b81eb7b35b360bc7972aeafb15177784adc56528db082e6b927" dependencies = [ "bytes", "futures", @@ -7696,18 +7979,20 @@ dependencies = [ "libp2p-tls", "log", "parking_lot 0.12.1", - "quinn-proto", + "quinn 0.10.2", "rand 0.8.5", - "rustls 0.20.8", + "ring 0.16.20", + "rustls 0.21.7", + "socket2 0.5.6", "thiserror", "tokio", ] [[package]] name = "libp2p-request-response" -version = "0.24.1" +version = "0.25.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ffdb374267d42dc5ed5bc53f6e601d4a64ac5964779c6e40bb9e4f14c1e30d5" +checksum = "d8e3b4d67870478db72bac87bfc260ee6641d0734e0e3e275798f089c3fecfd4" dependencies = [ "async-trait", "futures", @@ -7715,15 +8000,17 @@ dependencies = [ "libp2p-core", "libp2p-identity", "libp2p-swarm", + "log", "rand 0.8.5", "smallvec", + "void", ] [[package]] name = "libp2p-swarm" -version = "0.42.2" +version = "0.43.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "903b3d592d7694e56204d211f29d31bc004be99386644ba8731fc3e3ef27b296" +checksum = "580189e0074af847df90e75ef54f3f30059aedda37ea5a1659e8b9fca05c0141" dependencies = [ "either", "fnv", @@ -7734,6 +8021,8 @@ dependencies = [ "libp2p-identity", "libp2p-swarm-derive", "log", + "multistream-select", + "once_cell", "rand 0.8.5", "smallvec", "tokio", @@ -7742,36 +8031,39 @@ dependencies = [ [[package]] name = "libp2p-swarm-derive" -version = "0.32.0" +version = "0.33.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fba456131824ab6acd4c7bf61e9c0f0a3014b5fc9868ccb8e10d344594cdc4f" +checksum = "c4d5ec2a3df00c7836d7696c136274c9c59705bac69133253696a6c932cd1d74" dependencies = [ "heck 0.4.1", + "proc-macro-warning 0.4.2", + "proc-macro2 1.0.82", "quote 1.0.35", - "syn 1.0.109", + "syn 2.0.61", ] [[package]] name = "libp2p-tcp" -version = "0.39.0" +version = "0.40.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "33d33698596d7722d85d3ab0c86c2c322254fce1241e91208e3679b4eb3026cf" +checksum = "b558dd40d1bcd1aaaed9de898e9ec6a436019ecc2420dd0016e712fbb61c5508" dependencies = [ "futures", "futures-timer", "if-watch", "libc", "libp2p-core", + "libp2p-identity", "log", - "socket2 0.4.9", + "socket2 0.5.6", "tokio", ] [[package]] name = "libp2p-tls" -version = "0.1.0" +version = "0.2.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ff08d13d0dc66e5e9ba6279c1de417b84fa0d0adc3b03e5732928c180ec02781" +checksum = "8218d1d5482b122ccae396bbf38abdcb283ecc96fa54760e1dfd251f0546ac61" dependencies = [ "futures", "futures-rustls", @@ -7779,51 +8071,68 @@ dependencies = [ "libp2p-identity", "rcgen", "ring 0.16.20", - "rustls 0.20.8", + "rustls 0.21.7", + "rustls-webpki 0.101.4", "thiserror", - "webpki", - "x509-parser 0.14.0", + "x509-parser", "yasna", ] +[[package]] +name = "libp2p-upnp" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82775a47b34f10f787ad3e2a22e2c1541e6ebef4fe9f28f3ac553921554c94c1" +dependencies = [ + "futures", + "futures-timer", + "igd-next", + "libp2p-core", + "libp2p-swarm", + "log", + "tokio", + "void", +] + [[package]] name = "libp2p-wasm-ext" -version = "0.39.0" +version = "0.40.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "77dff9d32353a5887adb86c8afc1de1a94d9e8c3bc6df8b2201d7cdf5c848f43" +checksum = "1e5d8e3a9e07da0ef5b55a9f26c009c8fb3c725d492d8bb4b431715786eea79c" dependencies = [ "futures", "js-sys", "libp2p-core", - "parity-send-wrapper", + "send_wrapper", "wasm-bindgen", "wasm-bindgen-futures", ] [[package]] name = "libp2p-websocket" -version = "0.41.0" +version = "0.42.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "111273f7b3d3510524c752e8b7a5314b7f7a1fee7e68161c01a7d72cbb06db9f" +checksum = "3facf0691bab65f571bc97c6c65ffa836248ca631d631b7691ac91deb7fceb5f" dependencies = [ "either", "futures", "futures-rustls", "libp2p-core", + "libp2p-identity", "log", "parking_lot 0.12.1", "quicksink", "rw-stream-sink", - "soketto", + "soketto 0.7.1", "url", - "webpki-roots 0.22.6", + "webpki-roots 0.25.2", ] [[package]] name = "libp2p-yamux" -version = "0.43.1" +version = "0.44.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4dcd21d950662700a385d4c6d68e2f5f54d778e97068cdd718522222ef513bda" +checksum = "8eedcb62824c4300efb9cfd4e2a6edaf3ca097b9e68b36dabe45a44469fd6a85" dependencies = [ "futures", "libp2p-core", @@ -8005,7 +8314,7 @@ dependencies = [ "indexmap 2.2.3", "libc", "mockall 0.12.1", - "multiaddr", + "multiaddr 0.17.1", "multihash 0.17.0", "network-interface", "nohash-hasher", @@ -8013,11 +8322,11 @@ dependencies = [ "pin-project", "prost 0.11.9", "prost-build 0.11.9", - "quinn", + "quinn 0.9.4", "rand 0.8.5", "rcgen", "ring 0.16.20", - "rustls 0.20.8", + "rustls 0.20.9", "serde", "sha2 0.10.8", "simple-dns", @@ -8032,13 +8341,13 @@ dependencies = [ "tokio-tungstenite", "tokio-util", "tracing", - "trust-dns-resolver 0.23.2", + "trust-dns-resolver", "uint", "unsigned-varint", "url", "webpki", - "x25519-dalek 2.0.0", - "x509-parser 0.15.1", + "x25519-dalek", + "x509-parser", "yasna", "zeroize", ] @@ -8074,18 +8383,18 @@ dependencies = [ [[package]] name = "lru" -version = "0.10.1" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "718e8fae447df0c7e1ba7f5189829e63fd536945c8988d61444c19039f16b670" -dependencies = [ - "hashbrown 0.13.2", -] +checksum = "eedb2bdbad7e0634f83989bf596f497b070130daaa398ab22d84c39e266deec5" [[package]] name = "lru" -version = "0.11.0" +version = "0.12.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eedb2bdbad7e0634f83989bf596f497b070130daaa398ab22d84c39e266deec5" +checksum = "d3262e75e648fce39813cb56ac41f3c3e3f65217ebf3844d818d1f9398cfb0dc" +dependencies = [ + "hashbrown 0.14.3", +] [[package]] name = "lru-cache" @@ -8453,7 +8762,7 @@ dependencies = [ "bitflags 1.3.2", "blake2 0.10.6", "c2-chacha", - "curve25519-dalek 4.1.2", + "curve25519-dalek 4.1.3", "either", "hashlink", "lioness", @@ -8584,6 +8893,25 @@ dependencies = [ "url", ] +[[package]] +name = "multiaddr" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b852bc02a2da5feed68cd14fa50d0774b92790a5bdbfa932a813926c8472070" +dependencies = [ + "arrayref", + "byteorder", + "data-encoding", + "libp2p-identity", + "multibase", + "multihash 0.19.1", + "percent-encoding", + "serde", + "static_assertions", + "unsigned-varint", + "url", +] + [[package]] name = "multibase" version = "0.9.1" @@ -8606,7 +8934,7 @@ dependencies = [ "blake3", "core2", "digest 0.10.7", - "multihash-derive 0.8.0", + "multihash-derive", "sha2 0.10.8", "sha3", "unsigned-varint", @@ -8623,7 +8951,7 @@ dependencies = [ "blake3", "core2", "digest 0.10.7", - "multihash-derive 0.8.0", + "multihash-derive", "sha2 0.10.8", "sha3", "unsigned-varint", @@ -8639,26 +8967,6 @@ dependencies = [ "unsigned-varint", ] -[[package]] -name = "multihash-codetable" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f6d815ecb3c8238d00647f8630ede7060a642c9f704761cd6082cb4028af6935" -dependencies = [ - "blake2b_simd", - "blake2s_simd", - "blake3", - "core2", - "digest 0.10.7", - "multihash-derive 0.9.0", - "ripemd", - "serde", - "sha1", - "sha2 0.10.8", - "sha3", - "strobe-rs", -] - [[package]] name = "multihash-derive" version = "0.8.0" @@ -8673,31 +8981,6 @@ dependencies = [ "synstructure", ] -[[package]] -name = "multihash-derive" -version = "0.9.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "890e72cb7396cb99ed98c1246a97b243cc16394470d94e0bc8b0c2c11d84290e" -dependencies = [ - "core2", - "multihash 0.19.1", - "multihash-derive-impl", -] - -[[package]] -name = "multihash-derive-impl" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d38685e08adb338659871ecfc6ee47ba9b22dcc8abcf6975d379cc49145c3040" -dependencies = [ - "proc-macro-crate 1.3.1", - "proc-macro-error", - "proc-macro2 1.0.82", - "quote 1.0.35", - "syn 1.0.109", - "synstructure", -] - [[package]] name = "multimap" version = "0.8.3" @@ -8706,9 +8989,9 @@ checksum = "e5ce46fe64a9d73be07dcbe690a38ce1b293be448fd8ce1e6c1b8062c9f72c6a" [[package]] name = "multistream-select" -version = "0.12.1" +version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8552ab875c1313b97b8d20cb857b9fd63e2d1d6a0a1b53ce9821e575405f27a" +checksum = "ea0df8e5eec2298a62b326ee4f0d7fe1a6b90a09dfcf9df37b38f947a8c42f19" dependencies = [ "bytes", "futures", @@ -8868,7 +9151,7 @@ version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ab2156c4fce2f8df6c499cc1c763e4394b7482525bf2a9701c9d79d215f519e4" dependencies = [ - "bitflags 2.4.0", + "bitflags 2.6.0", "cfg-if", "cfg_aliases", "libc", @@ -9121,6 +9404,12 @@ dependencies = [ "num-traits", ] +[[package]] +name = "num-conv" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" + [[package]] name = "num-derive" version = "0.4.2" @@ -9270,7 +9559,7 @@ version = "0.10.64" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "95a0481286a310808298130d22dd1fef0fa571e05a8f44ec801801e84b216b1f" dependencies = [ - "bitflags 2.4.0", + "bitflags 2.6.0", "cfg-if", "foreign-types", "libc", @@ -9521,6 +9810,23 @@ dependencies = [ "sp-std 14.0.0", ] +[[package]] +name = "pallet-assets-freezer" +version = "0.1.0" +dependencies = [ + "frame-benchmarking", + "frame-support", + "frame-system", + "log", + "pallet-assets", + "pallet-balances", + "parity-scale-codec", + "scale-info", + "sp-core", + "sp-io", + "sp-runtime", +] + [[package]] name = "pallet-atomic-swap" version = "28.0.0" @@ -10451,6 +10757,7 @@ dependencies = [ "parity-scale-codec", "scale-info", "sp-core", + "sp-inherents", "sp-io", "sp-runtime", "sp-std 14.0.0", @@ -11684,7 +11991,7 @@ dependencies = [ "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", - "xcm-fee-payment-runtime-api", + "xcm-runtime-apis", ] [[package]] @@ -12017,12 +12324,6 @@ dependencies = [ "syn 1.0.109", ] -[[package]] -name = "parity-send-wrapper" -version = "0.1.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aa9777aa91b8ad9dd5aaa04a9b6bcb02c7f1deb952fca5a66034d5e63afc5c6f" - [[package]] name = "parity-util-mem" version = "0.12.0" @@ -12232,7 +12533,7 @@ dependencies = [ "staging-xcm-builder", "staging-xcm-executor", "substrate-wasm-builder", - "xcm-fee-payment-runtime-api", + "xcm-runtime-apis", ] [[package]] @@ -12333,7 +12634,7 @@ dependencies = [ "staging-xcm-executor", "substrate-wasm-builder", "testnet-parachains-constants", - "xcm-fee-payment-runtime-api", + "xcm-runtime-apis", ] [[package]] @@ -12434,7 +12735,7 @@ dependencies = [ "substrate-wasm-builder", "testnet-parachains-constants", "westend-runtime-constants", - "xcm-fee-payment-runtime-api", + "xcm-runtime-apis", ] [[package]] @@ -13182,6 +13483,7 @@ dependencies = [ "polkadot-node-subsystem-util", "polkadot-primitives", "polkadot-primitives-test-helpers", + "rstest", "sc-keystore", "sp-application-crypto", "sp-core", @@ -13391,7 +13693,7 @@ dependencies = [ "bs58 0.5.0", "futures", "futures-timer", - "hyper", + "hyper 0.14.27", "log", "parity-scale-codec", "polkadot-primitives", @@ -13875,7 +14177,6 @@ dependencies = [ "rand 0.8.5", "rand_chacha 0.3.1", "rstest", - "rustc-hex", "sc-keystore", "scale-info", "serde", @@ -13990,6 +14291,7 @@ dependencies = [ "pallet-asset-rate", "pallet-asset-tx-payment", "pallet-assets", + "pallet-assets-freezer", "pallet-atomic-swap", "pallet-aura", "pallet-authority-discovery", @@ -14281,8 +14583,8 @@ dependencies = [ "tracing-gum-proc-macro", "westend-runtime-constants", "xcm-emulator", - "xcm-fee-payment-runtime-api", "xcm-procedural", + "xcm-runtime-apis", "xcm-simulator", ] @@ -14302,6 +14604,7 @@ dependencies = [ "frame-support", "frame-system", "kitchensink-runtime", + "minimal-template-runtime", "pallet-assets", "pallet-aura", "pallet-authorship", @@ -14324,6 +14627,7 @@ dependencies = [ "pallet-transaction-payment", "pallet-uniques", "pallet-utility", + "parachain-template-runtime", "parity-scale-codec", "polkadot-sdk", "polkadot-sdk-frame", @@ -14343,6 +14647,7 @@ dependencies = [ "sc-service", "scale-info", "simple-mermaid 0.1.1", + "solochain-template-runtime", "sp-api", "sp-arithmetic", "sp-core", @@ -14351,6 +14656,9 @@ dependencies = [ "sp-keyring", "sp-offchain", "sp-runtime", + "sp-runtime-interface 24.0.0", + "sp-std 14.0.0", + "sp-tracing 16.0.0", "sp-version", "staging-chain-spec-builder", "staging-node-cli", @@ -14519,7 +14827,7 @@ dependencies = [ "tracing-gum", "westend-runtime", "westend-runtime-constants", - "xcm-fee-payment-runtime-api", + "xcm-runtime-apis", ] [[package]] @@ -14632,7 +14940,7 @@ dependencies = [ "sp-keystore", "sp-runtime", "sp-timestamp", - "strum 0.24.1", + "strum 0.26.2", "substrate-prometheus-endpoint", "tokio", "tracing-gum", @@ -14921,6 +15229,20 @@ dependencies = [ "windows-sys 0.48.0", ] +[[package]] +name = "polling" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30054e72317ab98eddd8561db0f6524df3367636884b7b21b703e4b280a84a14" +dependencies = [ + "cfg-if", + "concurrent-queue", + "pin-project-lite 0.2.12", + "rustix 0.38.21", + "tracing", + "windows-sys 0.52.0", +] + [[package]] name = "poly1305" version = "0.8.0" @@ -14959,6 +15281,12 @@ dependencies = [ "rand 0.8.5", ] +[[package]] +name = "powerfmt" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" + [[package]] name = "pprof" version = "0.12.1" @@ -15137,6 +15465,17 @@ version = "0.5.20+deprecated" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068" +[[package]] +name = "proc-macro-warning" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d1eaa7fa0aa1929ffdf7eeb6eac234dde6268914a14ad44d23521ab6a9b258e" +dependencies = [ + "proc-macro2 1.0.82", + "quote 1.0.35", + "syn 2.0.61", +] + [[package]] name = "proc-macro-warning" version = "1.0.0" @@ -15172,7 +15511,7 @@ version = "0.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "731e0d9356b0c25f16f33b5be79b1c57b562f141ebfcdb0ad8ac2c13a24293b4" dependencies = [ - "bitflags 2.4.0", + "bitflags 2.6.0", "chrono", "flate2", "hex", @@ -15187,7 +15526,7 @@ version = "0.16.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2d3554923a69f4ce04c4a754260c338f505ce22642d3830e049a399fc2059a29" dependencies = [ - "bitflags 2.4.0", + "bitflags 2.6.0", "chrono", "hex", ] @@ -15208,9 +15547,9 @@ dependencies = [ [[package]] name = "prometheus-client" -version = "0.19.0" +version = "0.21.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d6fa99d535dd930d1249e6c79cb3c2915f9172a540fe2b02a4c8f9ca954721e" +checksum = "3c99afa9a01501019ac3a14d71d9f94050346f55ca471ce90c799a15c58f61e2" dependencies = [ "dtoa", "itoa", @@ -15249,7 +15588,7 @@ checksum = "31b476131c3c86cb68032fdc5cb6d5a1045e3e42d96b69fa599fd77701e1f5bf" dependencies = [ "bit-set", "bit-vec", - "bitflags 2.4.0", + "bitflags 2.6.0", "lazy_static", "num-traits", "rand 0.8.5", @@ -15440,9 +15779,9 @@ dependencies = [ [[package]] name = "quick-protobuf-codec" -version = "0.1.0" +version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1693116345026436eb2f10b677806169c1a1260c1c60eaaffe3fb5a29ae23d8b" +checksum = "f8ededb1cd78531627244d51dd0c7139fbe736c7d57af0092a76f0ffb2f56e98" dependencies = [ "asynchronous-codec", "bytes", @@ -15451,6 +15790,17 @@ dependencies = [ "unsigned-varint", ] +[[package]] +name = "quick_cache" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5253a3a0d56548d5b0be25414171dc780cc6870727746d05bd2bde352eee96c5" +dependencies = [ + "ahash 0.8.11", + "hashbrown 0.13.2", + "parking_lot 0.12.1", +] + [[package]] name = "quickcheck" version = "1.0.3" @@ -15474,39 +15824,74 @@ dependencies = [ ] [[package]] -name = "quinn" -version = "0.9.4" +name = "quinn" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e8b432585672228923edbbf64b8b12c14e1112f62e88737655b4a083dbcd78e" +dependencies = [ + "bytes", + "pin-project-lite 0.2.12", + "quinn-proto 0.9.6", + "quinn-udp 0.3.2", + "rustc-hash", + "rustls 0.20.9", + "thiserror", + "tokio", + "tracing", + "webpki", +] + +[[package]] +name = "quinn" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cc2c5017e4b43d5995dcea317bc46c1e09404c0a9664d2908f7f02dfe943d75" +dependencies = [ + "bytes", + "futures-io", + "pin-project-lite 0.2.12", + "quinn-proto 0.10.6", + "quinn-udp 0.4.1", + "rustc-hash", + "rustls 0.21.7", + "thiserror", + "tokio", + "tracing", +] + +[[package]] +name = "quinn-proto" +version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2e8b432585672228923edbbf64b8b12c14e1112f62e88737655b4a083dbcd78e" +checksum = "94b0b33c13a79f669c85defaf4c275dc86a0c0372807d0ca3d78e0bb87274863" dependencies = [ "bytes", - "pin-project-lite 0.2.12", - "quinn-proto", - "quinn-udp", + "rand 0.8.5", + "ring 0.16.20", "rustc-hash", - "rustls 0.20.8", + "rustls 0.20.9", + "slab", "thiserror", - "tokio", + "tinyvec", "tracing", "webpki", ] [[package]] name = "quinn-proto" -version = "0.9.5" +version = "0.10.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c956be1b23f4261676aed05a0046e204e8a6836e50203902683a718af0797989" +checksum = "141bf7dfde2fbc246bfd3fe12f2455aa24b0fbd9af535d8c86c7bd1381ff2b1a" dependencies = [ "bytes", "rand 0.8.5", "ring 0.16.20", "rustc-hash", - "rustls 0.20.8", + "rustls 0.21.7", "slab", "thiserror", "tinyvec", "tracing", - "webpki", ] [[package]] @@ -15516,12 +15901,25 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "641538578b21f5e5c8ea733b736895576d0fe329bb883b937db6f4d163dbaaf4" dependencies = [ "libc", - "quinn-proto", + "quinn-proto 0.9.6", "socket2 0.4.9", "tracing", "windows-sys 0.42.0", ] +[[package]] +name = "quinn-udp" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "055b4e778e8feb9f93c4e439f71dc2156ef13360b432b799e179a8c4cdf0b1d7" +dependencies = [ + "bytes", + "libc", + "socket2 0.5.6", + "tracing", + "windows-sys 0.48.0", +] + [[package]] name = "quote" version = "0.6.13" @@ -15886,12 +16284,14 @@ dependencies = [ "pallet-transaction-payment-rpc-runtime-api", "pallet-utility", "parity-scale-codec", + "quick_cache", "rand 0.8.5", "relay-utils", "sc-chain-spec", "sc-rpc-api", "sc-transaction-pool-api", "scale-info", + "serde_json", "sp-consensus-grandpa", "sp-core", "sp-rpc", @@ -15956,11 +16356,11 @@ dependencies = [ "encoding_rs", "futures-core", "futures-util", - "h2", - "http", - "http-body", - "hyper", - "hyper-rustls", + "h2 0.3.26", + "http 0.2.9", + "http-body 0.4.5", + "hyper 0.14.27", + "hyper-rustls 0.24.1", "ipnet", "js-sys", "log", @@ -15968,7 +16368,7 @@ dependencies = [ "once_cell", "percent-encoding", "pin-project-lite 0.2.12", - "rustls 0.21.6", + "rustls 0.21.7", "rustls-pemfile 1.0.3", "serde", "serde_json", @@ -16049,15 +16449,6 @@ dependencies = [ "windows-sys 0.48.0", ] -[[package]] -name = "ripemd" -version = "0.1.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bd124222d17ad93a644ed9d011a40f4fb64aa54275c08cc216524a9ea82fb09f" -dependencies = [ - "digest 0.10.7", -] - [[package]] name = "rle-decode-fast" version = "1.0.3" @@ -16256,7 +16647,7 @@ dependencies = [ "substrate-wasm-builder", "tiny-keccak", "tokio", - "xcm-fee-payment-runtime-api", + "xcm-runtime-apis", ] [[package]] @@ -16489,7 +16880,7 @@ version = "0.38.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2b426b0506e5d50a7d8dafcf2e81471400deb602392c7dd110815afb4eaf02a3" dependencies = [ - "bitflags 2.4.0", + "bitflags 2.6.0", "errno", "libc", "linux-raw-sys 0.4.10", @@ -16498,11 +16889,10 @@ dependencies = [ [[package]] name = "rustls" -version = "0.20.8" +version = "0.20.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fff78fc74d175294f4e83b28343315ffcfb114b156f0185e9741cb5570f50e2f" +checksum = "1b80e3dec595989ea8510028f30c408a4630db12c9cbb8de34203b89d6577e99" dependencies = [ - "log", "ring 0.16.20", "sct", "webpki", @@ -16510,9 +16900,9 @@ dependencies = [ [[package]] name = "rustls" -version = "0.21.6" +version = "0.21.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1d1feddffcfcc0b33f5c6ce9a29e341e4cd59c3f78e7ee45f4a40c038b1d6cbb" +checksum = "cd8d6c9f025a446bc4d18ad9632e69aec8f287aa84499ee335599fabd20c3fd8" dependencies = [ "log", "ring 0.16.20", @@ -16522,14 +16912,15 @@ dependencies = [ [[package]] name = "rustls" -version = "0.22.2" +version = "0.23.10" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e87c9956bd9807afa1f77e0f7594af32566e830e088a5576d27c5b6f30f49d41" +checksum = "05cff451f60db80f490f3c182b77c35260baace73209e9cdbbe526bfe3a4d402" dependencies = [ "log", + "once_cell", "ring 0.17.7", "rustls-pki-types", - "rustls-webpki 0.102.2", + "rustls-webpki 0.102.4", "subtle 2.5.0", "zeroize", ] @@ -16580,9 +16971,36 @@ dependencies = [ [[package]] name = "rustls-pki-types" -version = "1.2.0" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "976295e77ce332211c0d24d92c0e83e50f5c5f046d11082cea19f3df13a3562d" + +[[package]] +name = "rustls-platform-verifier" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5f0d26fa1ce3c790f9590868f0109289a044acb954525f933e2aa3b871c157d" +dependencies = [ + "core-foundation", + "core-foundation-sys", + "jni", + "log", + "once_cell", + "rustls 0.23.10", + "rustls-native-certs 0.7.0", + "rustls-platform-verifier-android", + "rustls-webpki 0.102.4", + "security-framework", + "security-framework-sys", + "webpki-roots 0.26.3", + "winapi", +] + +[[package]] +name = "rustls-platform-verifier-android" +version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a716eb65e3158e90e17cd93d855216e27bde02745ab842f2cab4a39dba1bacf" +checksum = "84e217e7fdc8466b5b35d30f8c0a30febd29173df4a3a0c2115d306b9c4117ad" [[package]] name = "rustls-webpki" @@ -16596,9 +17014,9 @@ dependencies = [ [[package]] name = "rustls-webpki" -version = "0.102.2" +version = "0.102.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "faaa0a62740bedb9b2ef5afa303da42764c012f743917351dc9a237ea1663610" +checksum = "ff448f7e92e913c4b7d4c6d8e4540a1724b319b4152b8aef6d4cf8339712b33e" dependencies = [ "ring 0.17.7", "rustls-pki-types", @@ -16636,9 +17054,9 @@ dependencies = [ [[package]] name = "rw-stream-sink" -version = "0.3.0" +version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "26338f5e09bb721b85b135ea05af7767c90b52f6de4f087d4f4a3a9d64e7dc04" +checksum = "d8c9026ff5d2f23da5e45bbc283f156383001bfb09c4e44256d02c1a685fe9a1" dependencies = [ "futures", "pin-project", @@ -16699,8 +17117,7 @@ dependencies = [ "libp2p", "linked_hash_set", "log", - "multihash 0.17.0", - "multihash-codetable", + "multihash 0.19.1", "parity-scale-codec", "prost 0.12.4", "prost-build 0.12.4", @@ -16915,7 +17332,6 @@ version = "0.33.0" dependencies = [ "async-trait", "futures", - "futures-timer", "log", "mockall 0.11.4", "parking_lot 0.12.1", @@ -17407,7 +17823,7 @@ dependencies = [ "futures-timer", "log", "mixnet", - "multiaddr", + "multiaddr 0.18.1", "parity-scale-codec", "parking_lot 0.12.1", "sc-client-api", @@ -17513,7 +17929,6 @@ dependencies = [ "async-trait", "futures", "futures-timer", - "libp2p", "log", "parity-scale-codec", "quickcheck", @@ -17556,7 +17971,6 @@ dependencies = [ "array-bytes", "async-channel", "futures", - "libp2p", "log", "parity-scale-codec", "sc-network", @@ -17647,7 +18061,6 @@ version = "0.33.0" dependencies = [ "array-bytes", "futures", - "libp2p", "log", "parity-scale-codec", "sc-network", @@ -17668,8 +18081,9 @@ dependencies = [ "ed25519-dalek 2.1.1", "libp2p-identity", "litep2p", - "multiaddr", - "multihash 0.17.0", + "log", + "multiaddr 0.18.1", + "multihash 0.19.1", "quickcheck", "rand 0.8.5", "thiserror", @@ -17686,10 +18100,9 @@ dependencies = [ "fnv", "futures", "futures-timer", - "hyper", - "hyper-rustls", + "hyper 0.14.27", + "hyper-rustls 0.24.1", "lazy_static", - "libp2p", "log", "num_cpus", "once_cell", @@ -17795,11 +18208,13 @@ dependencies = [ "forwarded-header-value", "futures", "governor", - "http", - "hyper", + "http 1.1.0", + "http-body-util", + "hyper 1.3.1", "ip_network", "jsonrpsee", "log", + "serde", "serde_json", "substrate-prometheus-endpoint", "tokio", @@ -18292,7 +18707,7 @@ dependencies = [ "aead", "arrayref", "arrayvec 0.7.4", - "curve25519-dalek 4.1.2", + "curve25519-dalek 4.1.3", "getrandom_or_panic", "merlin", "rand_core 0.6.4", @@ -18398,22 +18813,23 @@ dependencies = [ [[package]] name = "security-framework" -version = "2.9.2" +version = "2.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "05b64fb303737d99b81884b2c63433e9ae28abebe5eb5045dcdd175dc2ecf4de" +checksum = "c627723fd09706bacdb5cf41499e95098555af3c3c29d014dc3c458ef6be11c0" dependencies = [ - "bitflags 1.3.2", + "bitflags 2.6.0", "core-foundation", "core-foundation-sys", "libc", + "num-bigint", "security-framework-sys", ] [[package]] name = "security-framework-sys" -version = "2.9.1" +version = "2.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e932934257d3b408ed8f30db49d85ea163bfe74961f017f405b025af298f0c7a" +checksum = "317936bbbd05227752583946b9e66d7ce3b489f84e11a94a510b4437fef407d7" dependencies = [ "core-foundation-sys", "libc", @@ -18505,6 +18921,12 @@ dependencies = [ "pest", ] +[[package]] +name = "send_wrapper" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73" + [[package]] name = "separator" version = "0.4.1" @@ -18835,7 +19257,7 @@ version = "0.5.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cae9a3fcdadafb6d97f4c0e007e4247b114ee0f119f650c3cbf3a8b3a1479694" dependencies = [ - "bitflags 2.4.0", + "bitflags 2.6.0", ] [[package]] @@ -18916,12 +19338,12 @@ dependencies = [ "async-channel", "async-executor", "async-fs", - "async-io", - "async-lock", + "async-io 1.13.0", + "async-lock 2.8.0", "async-net", "async-process", "blocking", - "futures-lite", + "futures-lite 1.13.0", ] [[package]] @@ -18940,7 +19362,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c0bb30cf57b7b5f6109ce17c3164445e2d6f270af2cb48f6e4d31c2967c9a9f5" dependencies = [ "arrayvec 0.7.4", - "async-lock", + "async-lock 2.8.0", "atomic-take", "base64 0.21.2", "bip39", @@ -18951,9 +19373,9 @@ dependencies = [ "derive_more", "ed25519-zebra", "either", - "event-listener", + "event-listener 2.5.3", "fnv", - "futures-lite", + "futures-lite 1.13.0", "futures-util", "hashbrown 0.14.3", "hex", @@ -18980,10 +19402,10 @@ dependencies = [ "siphasher", "slab", "smallvec", - "soketto", + "soketto 0.7.1", "twox-hash", "wasmi 0.31.2", - "x25519-dalek 2.0.0", + "x25519-dalek", "zeroize", ] @@ -18994,15 +19416,15 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "256b5bad1d6b49045e95fe87492ce73d5af81545d8b4d8318a872d2007024c33" dependencies = [ "async-channel", - "async-lock", + "async-lock 2.8.0", "base64 0.21.2", "blake2-rfc", "derive_more", "either", - "event-listener", + "event-listener 2.5.3", "fnv", "futures-channel", - "futures-lite", + "futures-lite 1.13.0", "futures-util", "hashbrown 0.14.3", "hex", @@ -19038,7 +19460,7 @@ dependencies = [ "aes-gcm", "blake2 0.10.6", "chacha20poly1305", - "curve25519-dalek 4.1.2", + "curve25519-dalek 4.1.3", "rand_core 0.6.4", "ring 0.17.7", "rustc_version 0.4.0", @@ -19300,7 +19722,6 @@ dependencies = [ "hex-literal", "log", "parity-scale-codec", - "rustc-hex", "scale-info", "snowbridge-core", "sp-core", @@ -19395,15 +19816,29 @@ checksum = "41d1c5305e39e09653383c2c7244f2f78b3bcae37cf50c64cb4789c9f5096ec2" dependencies = [ "base64 0.13.1", "bytes", - "flate2", "futures", - "http", "httparse", "log", "rand 0.8.5", "sha-1 0.9.8", ] +[[package]] +name = "soketto" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37468c595637c10857701c990f93a40ce0e357cedb0953d1c26c8d8027f9bb53" +dependencies = [ + "base64 0.22.1", + "bytes", + "futures", + "http 1.1.0", + "httparse", + "log", + "rand 0.8.5", + "sha1", +] + [[package]] name = "solochain-template-node" version = "0.0.0" @@ -19488,6 +19923,7 @@ dependencies = [ name = "sp-api" version = "26.0.0" dependencies = [ + "docify", "hash-db", "log", "parity-scale-codec", @@ -19981,6 +20417,7 @@ name = "sp-io" version = "30.0.0" dependencies = [ "bytes", + "docify", "ed25519-dalek 2.1.1", "libsecp256k1", "log", @@ -20282,6 +20719,7 @@ dependencies = [ name = "sp-state-machine" version = "0.35.0" dependencies = [ + "arbitrary", "array-bytes", "assert_matches", "hash-db", @@ -20306,7 +20744,7 @@ name = "sp-statement-store" version = "10.0.0" dependencies = [ "aes-gcm", - "curve25519-dalek 4.1.2", + "curve25519-dalek 4.1.3", "ed25519-dalek 2.1.1", "hkdf", "parity-scale-codec", @@ -20321,7 +20759,7 @@ dependencies = [ "sp-runtime", "sp-runtime-interface 24.0.0", "thiserror", - "x25519-dalek 2.0.0", + "x25519-dalek", ] [[package]] @@ -20629,7 +21067,7 @@ dependencies = [ "scale-info", "serde", "serde_json", - "soketto", + "soketto 0.7.1", "staging-node-inspect", "substrate-cli-test-utils", "tempfile", @@ -20809,19 +21247,6 @@ dependencies = [ "serde", ] -[[package]] -name = "strobe-rs" -version = "0.8.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fabb238a1cccccfa4c4fb703670c0d157e1256c1ba695abf1b93bd2bb14bab2d" -dependencies = [ - "bitflags 1.3.2", - "byteorder", - "keccak", - "subtle 2.5.0", - "zeroize", -] - [[package]] name = "strsim" version = "0.8.0" @@ -21014,7 +21439,7 @@ dependencies = [ name = "substrate-prometheus-endpoint" version = "0.17.0" dependencies = [ - "hyper", + "hyper 0.14.27", "log", "prometheus", "thiserror", @@ -21775,14 +22200,16 @@ dependencies = [ [[package]] name = "time" -version = "0.3.27" +version = "0.3.36" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0bb39ee79a6d8de55f48f2293a830e040392f1c5f16e336bdd1788cd0aadce07" +checksum = "5dfd88e563464686c916c7e46e623e520ddc6d79fa6641390f2e3fa86e83e885" dependencies = [ "deranged", "itoa", "libc", + "num-conv", "num_threads", + "powerfmt", "serde", "time-core", "time-macros", @@ -21790,16 +22217,17 @@ dependencies = [ [[package]] name = "time-core" -version = "0.1.1" +version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7300fbefb4dadc1af235a9cef3737cea692a9d97e1b9cbcd4ebdae6f8868e6fb" +checksum = "ef927ca75afb808a4d64dd374f00a2adf8d0fcff8e7b184af886c3c87ec4a3f3" [[package]] name = "time-macros" -version = "0.2.13" +version = "0.2.18" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "733d258752e9303d392b94b75230d07b0b9c489350c69b851fc6c065fde3e8f9" +checksum = "3f252a68540fde3a3877aeea552b832b40ab9a69e318efd078774a01ddee1ccf" dependencies = [ + "num-conv", "time-core", ] @@ -21884,17 +22312,17 @@ version = "0.24.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c28327cf380ac148141087fbfb9de9d7bd4e84ab5d2c28fbc911d753de8a7081" dependencies = [ - "rustls 0.21.6", + "rustls 0.21.7", "tokio", ] [[package]] name = "tokio-rustls" -version = "0.25.0" +version = "0.26.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "775e0c0f0adb3a2f22a00c4745d728b479985fc15ee7ca6a2608388c5569860f" +checksum = "0c7bc40d0e5a97695bb96e27995cd3a08538541b0a846f65bba7a359f36700d4" dependencies = [ - "rustls 0.22.2", + "rustls 0.23.10", "rustls-pki-types", "tokio", ] @@ -21932,7 +22360,7 @@ checksum = "212d5dcb2a1ce06d81107c3d0ffa3121fe974b73f068c8282cb1c32328113b6c" dependencies = [ "futures-util", "log", - "rustls 0.21.6", + "rustls 0.21.7", "rustls-native-certs 0.6.3", "tokio", "tokio-rustls 0.24.1", @@ -22017,6 +22445,7 @@ dependencies = [ "futures-util", "pin-project", "pin-project-lite 0.2.12", + "tokio", "tower-layer", "tower-service", "tracing", @@ -22024,17 +22453,15 @@ dependencies = [ [[package]] name = "tower-http" -version = "0.4.3" +version = "0.5.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "55ae70283aba8d2a8b411c695c437fe25b8b5e44e23e780662002fc72fb47a82" +checksum = "1e9cd434a998747dd2c4276bc96ee2e0c7a2eadf3cae88e52be55a05fa9053f5" dependencies = [ - "bitflags 2.4.0", + "bitflags 2.6.0", "bytes", - "futures-core", - "futures-util", - "http", - "http-body", - "http-range-header", + "http 1.1.0", + "http-body 1.0.0", + "http-body-util", "pin-project-lite 0.2.12", "tower-layer", "tower-service", @@ -22289,26 +22716,6 @@ dependencies = [ "url", ] -[[package]] -name = "trust-dns-resolver" -version = "0.22.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aff21aa4dcefb0a1afbfac26deb0adc93888c7d295fb63ab273ef276ba2b7cfe" -dependencies = [ - "cfg-if", - "futures-util", - "ipconfig", - "lazy_static", - "lru-cache", - "parking_lot 0.12.1", - "resolv-conf", - "smallvec", - "thiserror", - "tokio", - "tracing", - "trust-dns-proto 0.22.0", -] - [[package]] name = "trust-dns-resolver" version = "0.23.2" @@ -22367,11 +22774,11 @@ dependencies = [ "byteorder", "bytes", "data-encoding", - "http", + "http 0.2.9", "httparse", "log", "rand 0.8.5", - "rustls 0.21.6", + "rustls 0.21.7", "sha1", "thiserror", "url", @@ -23170,18 +23577,18 @@ dependencies = [ [[package]] name = "webpki-roots" -version = "0.22.6" +version = "0.25.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b6c71e40d7d2c34a5106301fb632274ca37242cd0c9d3e64dbece371a40a2d87" -dependencies = [ - "webpki", -] +checksum = "14247bb57be4f377dfb94c72830b8ce8fc6beac03cf4bf7b9732eadd414123fc" [[package]] name = "webpki-roots" -version = "0.25.2" +version = "0.26.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "14247bb57be4f377dfb94c72830b8ce8fc6beac03cf4bf7b9732eadd414123fc" +checksum = "bd7c23921eeb1713a4e851530e9b9756e4fb0e89978582942612524cf09f01cd" +dependencies = [ + "rustls-pki-types", +] [[package]] name = "westend-emulated-chain" @@ -23200,7 +23607,7 @@ dependencies = [ "staging-xcm", "westend-runtime", "westend-runtime-constants", - "xcm-fee-payment-runtime-api", + "xcm-runtime-apis", ] [[package]] @@ -23277,7 +23684,6 @@ dependencies = [ "polkadot-primitives", "polkadot-runtime-common", "polkadot-runtime-parachains", - "rustc-hex", "scale-info", "serde", "serde_derive", @@ -23313,7 +23719,7 @@ dependencies = [ "tiny-keccak", "tokio", "westend-runtime-constants", - "xcm-fee-payment-runtime-api", + "xcm-runtime-apis", ] [[package]] @@ -23404,23 +23810,20 @@ checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" [[package]] name = "windows" -version = "0.34.0" +version = "0.48.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "45296b64204227616fdbf2614cefa4c236b98ee64dfaaaa435207ed99fe7829f" +checksum = "e686886bc078bc1b0b600cac0147aadb815089b6e4da64016cbd754b6342700f" dependencies = [ - "windows_aarch64_msvc 0.34.0", - "windows_i686_gnu 0.34.0", - "windows_i686_msvc 0.34.0", - "windows_x86_64_gnu 0.34.0", - "windows_x86_64_msvc 0.34.0", + "windows-targets 0.48.5", ] [[package]] name = "windows" -version = "0.48.0" +version = "0.51.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e686886bc078bc1b0b600cac0147aadb815089b6e4da64016cbd754b6342700f" +checksum = "ca229916c5ee38c2f2bc1e9d8f04df975b4bd93f9955dc69fabb5d91270045c9" dependencies = [ + "windows-core 0.51.1", "windows-targets 0.48.5", ] @@ -23430,10 +23833,19 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e48a53791691ab099e5e2ad123536d0fff50652600abaf43bbf952894110d0be" dependencies = [ - "windows-core", + "windows-core 0.52.0", "windows-targets 0.52.0", ] +[[package]] +name = "windows-core" +version = "0.51.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1f8cf84f35d2db49a46868f947758c7a1138116f7fac3bc844f43ade1292e64" +dependencies = [ + "windows-targets 0.48.5", +] + [[package]] name = "windows-core" version = "0.52.0" @@ -23548,12 +23960,6 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cb7764e35d4db8a7921e09562a0304bf2f93e0a51bfccee0bd0bb0b666b015ea" -[[package]] -name = "windows_aarch64_msvc" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17cffbe740121affb56fad0fc0e421804adf0ae00891205213b5cecd30db881d" - [[package]] name = "windows_aarch64_msvc" version = "0.42.2" @@ -23572,12 +23978,6 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbaa0368d4f1d2aaefc55b6fcfee13f41544ddf36801e793edbbfd7d7df075ef" -[[package]] -name = "windows_i686_gnu" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2564fde759adb79129d9b4f54be42b32c89970c18ebf93124ca8870a498688ed" - [[package]] name = "windows_i686_gnu" version = "0.42.2" @@ -23596,12 +23996,6 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a28637cb1fa3560a16915793afb20081aba2c92ee8af57b4d5f28e4b3e7df313" -[[package]] -name = "windows_i686_msvc" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9cd9d32ba70453522332c14d38814bceeb747d80b3958676007acadd7e166956" - [[package]] name = "windows_i686_msvc" version = "0.42.2" @@ -23620,12 +24014,6 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ffe5e8e31046ce6230cc7215707b816e339ff4d4d67c65dffa206fd0f7aa7b9a" -[[package]] -name = "windows_x86_64_gnu" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cfce6deae227ee8d356d19effc141a509cc503dfd1f850622ec4b0f84428e1f4" - [[package]] name = "windows_x86_64_gnu" version = "0.42.2" @@ -23662,12 +24050,6 @@ version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1a657e1e9d3f514745a572a6846d3c7aa7dbe1658c056ed9c3344c4109a6949e" -[[package]] -name = "windows_x86_64_msvc" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d19538ccc21819d01deaf88d6a17eae6596a12e9aafdbb97916fb49896d89de9" - [[package]] name = "windows_x86_64_msvc" version = "0.42.2" @@ -23714,47 +24096,18 @@ dependencies = [ "tap", ] -[[package]] -name = "x25519-dalek" -version = "1.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5a0c105152107e3b96f6a00a65e86ce82d9b125230e1c4302940eca58ff71f4f" -dependencies = [ - "curve25519-dalek 3.2.0", - "rand_core 0.5.1", - "zeroize", -] - [[package]] name = "x25519-dalek" version = "2.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fb66477291e7e8d2b0ff1bcb900bf29489a9692816d79874bea351e7a8b6de96" dependencies = [ - "curve25519-dalek 4.1.2", + "curve25519-dalek 4.1.3", "rand_core 0.6.4", "serde", "zeroize", ] -[[package]] -name = "x509-parser" -version = "0.14.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0ecbeb7b67ce215e40e3cc7f2ff902f94a223acf44995934763467e7b1febc8" -dependencies = [ - "asn1-rs", - "base64 0.13.1", - "data-encoding", - "der-parser", - "lazy_static", - "nom", - "oid-registry", - "rusticata-macros", - "thiserror", - "time", -] - [[package]] name = "x509-parser" version = "0.15.1" @@ -23864,13 +24217,26 @@ dependencies = [ ] [[package]] -name = "xcm-fee-payment-runtime-api" +name = "xcm-procedural" +version = "7.0.0" +dependencies = [ + "Inflector", + "proc-macro2 1.0.82", + "quote 1.0.35", + "staging-xcm", + "syn 2.0.61", + "trybuild", +] + +[[package]] +name = "xcm-runtime-apis" version = "0.1.0" dependencies = [ - "env_logger 0.9.3", + "env_logger 0.11.3", "frame-executive", "frame-support", "frame-system", + "hex-literal", "log", "pallet-assets", "pallet-balances", @@ -23879,7 +24245,6 @@ dependencies = [ "scale-info", "sp-api", "sp-io", - "sp-runtime", "sp-std 14.0.0", "sp-weights", "staging-xcm", @@ -23887,18 +24252,6 @@ dependencies = [ "staging-xcm-executor", ] -[[package]] -name = "xcm-procedural" -version = "7.0.0" -dependencies = [ - "Inflector", - "proc-macro2 1.0.82", - "quote 1.0.35", - "staging-xcm", - "syn 2.0.61", - "trybuild", -] - [[package]] name = "xcm-simulator" version = "7.0.0" @@ -23975,16 +24328,32 @@ dependencies = [ "xcm-simulator", ] +[[package]] +name = "xml-rs" +version = "0.8.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791978798f0597cfc70478424c2b4fdc2b7a8024aaff78497ef00f24ef674193" + +[[package]] +name = "xmltree" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d8a75eaf6557bb84a65ace8609883db44a29951042ada9b393151532e41fcb" +dependencies = [ + "xml-rs", +] + [[package]] name = "yamux" -version = "0.10.2" +version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e5d9ba232399af1783a58d8eb26f6b5006fbefe2dc9ef36bd283324792d03ea5" +checksum = "9ed0164ae619f2dc144909a9f082187ebb5893693d8c0196e8085283ccd4b776" dependencies = [ "futures", "log", "nohash-hasher", "parking_lot 0.12.1", + "pin-project", "rand 0.8.5", "static_assertions", ] diff --git a/Cargo.toml b/Cargo.toml index 2b2a1cdc17d5ca70d876f6fc907f8e1fdd3cfd52..aa8fad5da8b88abf16b551dbe472841402a6bc18 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -226,7 +226,7 @@ members = [ "polkadot/xcm/xcm-builder", "polkadot/xcm/xcm-executor", "polkadot/xcm/xcm-executor/integration-tests", - "polkadot/xcm/xcm-fee-payment-runtime-api", + "polkadot/xcm/xcm-runtime-apis", "polkadot/xcm/xcm-simulator", "polkadot/xcm/xcm-simulator/example", "polkadot/xcm/xcm-simulator/fuzzer", @@ -306,6 +306,7 @@ members = [ "substrate/frame/asset-conversion/ops", "substrate/frame/asset-rate", "substrate/frame/assets", + "substrate/frame/assets-freezer", "substrate/frame/atomic-swap", "substrate/frame/aura", "substrate/frame/authority-discovery", @@ -564,19 +565,783 @@ extra-unused-type-parameters = { level = "allow", priority = 2 } # stylistic default_constructed_unit_structs = { level = "allow", priority = 2 } # stylistic [workspace.dependencies] +Inflector = { version = "0.11.4" } +aes-gcm = { version = "0.10" } +ahash = { version = "0.8.2" } +alloy-primitives = { version = "0.4.2", default-features = false } +alloy-sol-types = { version = "0.4.2", default-features = false } +always-assert = { version = "0.1" } +ansi_term = { version = "0.12.1" } +anyhow = { version = "1.0.81" } +aquamarine = { version = "0.5.0" } +arbitrary = { version = "1.3.2" } +ark-bls12-377 = { version = "0.4.0", default-features = false } +ark-bls12-377-ext = { version = "0.4.1", default-features = false } +ark-bls12-381 = { version = "0.4.0", default-features = false } +ark-bls12-381-ext = { version = "0.4.1", default-features = false } +ark-bw6-761 = { version = "0.4.0", default-features = false } +ark-bw6-761-ext = { version = "0.4.1", default-features = false } +ark-ec = { version = "0.4.2", default-features = false } +ark-ed-on-bls12-377 = { version = "0.4.0", default-features = false } +ark-ed-on-bls12-377-ext = { version = "0.4.1", default-features = false } +ark-ed-on-bls12-381-bandersnatch = { version = "0.4.0", default-features = false } +ark-ed-on-bls12-381-bandersnatch-ext = { version = "0.4.1", default-features = false } +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_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 } +asset-hub-westend-emulated-chain = { path = "cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-westend" } +asset-hub-westend-runtime = { path = "cumulus/parachains/runtimes/assets/asset-hub-westend" } +asset-test-utils = { path = "cumulus/parachains/runtimes/assets/test-utils", default-features = false } +assets-common = { path = "cumulus/parachains/runtimes/assets/common", default-features = false } +async-channel = { version = "1.8.0" } +async-std = { version = "1.9.0" } +async-trait = { version = "0.1.79" } +asynchronous-codec = { version = "0.6" } +backoff = { version = "0.4" } +backtrace = { version = "0.3.64" } +binary-merkle-tree = { path = "substrate/utils/binary-merkle-tree", default-features = false } +bincode = { version = "1.3.3" } +bip39 = { version = "2.0.0" } +bitflags = { version = "1.3.2" } +bitvec = { version = "1.0.1", default-features = false } +blake2 = { version = "0.10.4", default-features = false } +blake2b_simd = { version = "1.0.1", default-features = false } +blake3 = { version = "1.5" } +bounded-collections = { version = "0.2.0", default-features = false } +bounded-vec = { version = "0.7" } +bp-asset-hub-rococo = { path = "bridges/chains/chain-asset-hub-rococo", default-features = false } +bp-asset-hub-westend = { path = "bridges/chains/chain-asset-hub-westend", default-features = false } +bp-beefy = { path = "bridges/primitives/beefy", default-features = false } +bp-bridge-hub-cumulus = { path = "bridges/chains/chain-bridge-hub-cumulus", default-features = false } +bp-bridge-hub-kusama = { default-features = false, path = "bridges/chains/chain-bridge-hub-kusama" } +bp-bridge-hub-polkadot = { path = "bridges/chains/chain-bridge-hub-polkadot", default-features = false } +bp-bridge-hub-rococo = { path = "bridges/chains/chain-bridge-hub-rococo", default-features = false } +bp-bridge-hub-westend = { path = "bridges/chains/chain-bridge-hub-westend", default-features = false } +bp-header-chain = { path = "bridges/primitives/header-chain", default-features = false } +bp-kusama = { default-features = false, path = "bridges/chains/chain-kusama" } +bp-messages = { path = "bridges/primitives/messages", default-features = false } +bp-parachains = { path = "bridges/primitives/parachains", default-features = false } +bp-polkadot = { default-features = false, path = "bridges/chains/chain-polkadot" } +bp-polkadot-bulletin = { path = "bridges/chains/chain-polkadot-bulletin", default-features = false } +bp-polkadot-core = { path = "bridges/primitives/polkadot-core", default-features = false } +bp-relayers = { path = "bridges/primitives/relayers", default-features = false } +bp-rococo = { path = "bridges/chains/chain-rococo", default-features = false } +bp-runtime = { path = "bridges/primitives/runtime", default-features = false } +bp-test-utils = { path = "bridges/primitives/test-utils", default-features = false } +bp-westend = { path = "bridges/chains/chain-westend", default-features = false } +bp-xcm-bridge-hub = { path = "bridges/primitives/xcm-bridge-hub", default-features = false } +bp-xcm-bridge-hub-router = { path = "bridges/primitives/xcm-bridge-hub-router", default-features = false } +bridge-hub-common = { path = "cumulus/parachains/runtimes/bridge-hubs/common", default-features = false } +bridge-hub-rococo-emulated-chain = { path = "cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-rococo" } +bridge-hub-rococo-runtime = { path = "cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo", default-features = false } +bridge-hub-test-utils = { path = "cumulus/parachains/runtimes/bridge-hubs/test-utils", default-features = false } +bridge-hub-westend-emulated-chain = { path = "cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-westend" } +bridge-hub-westend-runtime = { path = "cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend", default-features = false } +bridge-runtime-common = { path = "bridges/bin/runtime-common", default-features = false } +bs58 = { version = "0.5.0", default-features = false } +build-helper = { version = "0.1.1" } +byte-slice-cast = { version = "1.2.1", default-features = false } +byteorder = { version = "1.3.2", default-features = false } +bytes = { version = "1.4.0", default-features = false } +cargo_metadata = { version = "0.15.4" } +cfg-expr = { version = "0.15.5" } +cfg-if = { version = "1.0" } +chain-spec-builder = { path = "substrate/bin/utils/chain-spec-builder", default-features = false, package = "staging-chain-spec-builder" } +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-num = { version = "1.0.2" } +clap_complete = { version = "4.0.2" } +coarsetime = { version = "0.1.22" } +codec = { version = "3.6.12", default-features = false, package = "parity-scale-codec" } +collectives-westend-emulated-chain = { path = "cumulus/parachains/integration-tests/emulated/chains/parachains/collectives/collectives-westend" } +collectives-westend-runtime = { path = "cumulus/parachains/runtimes/collectives/collectives-westend" } +color-eyre = { version = "0.6.1", default-features = false } +color-print = { version = "0.3.4" } +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-runtime = { path = "cumulus/parachains/runtimes/coretime/coretime-rococo" } +coretime-westend-runtime = { path = "cumulus/parachains/runtimes/coretime/coretime-westend" } +cpu-time = { version = "1.0.0" } +criterion = { version = "0.5.1", default-features = false } +cumulus-client-cli = { path = "cumulus/client/cli", default-features = false } +cumulus-client-collator = { path = "cumulus/client/collator", default-features = false } +cumulus-client-consensus-aura = { path = "cumulus/client/consensus/aura", default-features = false } +cumulus-client-consensus-common = { path = "cumulus/client/consensus/common", default-features = false } +cumulus-client-consensus-proposer = { path = "cumulus/client/consensus/proposer", default-features = false } +cumulus-client-consensus-relay-chain = { path = "cumulus/client/consensus/relay-chain", default-features = false } +cumulus-client-network = { path = "cumulus/client/network", default-features = false } +cumulus-client-parachain-inherent = { path = "cumulus/client/parachain-inherent", default-features = false } +cumulus-client-pov-recovery = { path = "cumulus/client/pov-recovery", default-features = false } +cumulus-client-service = { path = "cumulus/client/service", default-features = false } +cumulus-pallet-aura-ext = { path = "cumulus/pallets/aura-ext", default-features = false } +cumulus-pallet-dmp-queue = { default-features = false, path = "cumulus/pallets/dmp-queue" } +cumulus-pallet-parachain-system = { path = "cumulus/pallets/parachain-system", default-features = false } +cumulus-pallet-parachain-system-proc-macro = { path = "cumulus/pallets/parachain-system/proc-macro", default-features = false } +cumulus-pallet-session-benchmarking = { path = "cumulus/pallets/session-benchmarking", default-features = false } +cumulus-pallet-solo-to-para = { path = "cumulus/pallets/solo-to-para", default-features = false } +cumulus-pallet-xcm = { path = "cumulus/pallets/xcm", default-features = false } +cumulus-pallet-xcmp-queue = { path = "cumulus/pallets/xcmp-queue", default-features = false } +cumulus-ping = { path = "cumulus/parachains/pallets/ping", default-features = false } +cumulus-primitives-aura = { path = "cumulus/primitives/aura", default-features = false } +cumulus-primitives-core = { path = "cumulus/primitives/core", default-features = false } +cumulus-primitives-parachain-inherent = { path = "cumulus/primitives/parachain-inherent", default-features = false } +cumulus-primitives-proof-size-hostfunction = { path = "cumulus/primitives/proof-size-hostfunction", default-features = false } +cumulus-primitives-storage-weight-reclaim = { path = "cumulus/primitives/storage-weight-reclaim", default-features = false } +cumulus-primitives-timestamp = { path = "cumulus/primitives/timestamp", default-features = false } +cumulus-primitives-utility = { path = "cumulus/primitives/utility", default-features = false } +cumulus-relay-chain-inprocess-interface = { path = "cumulus/client/relay-chain-inprocess-interface", default-features = false } +cumulus-relay-chain-interface = { path = "cumulus/client/relay-chain-interface", default-features = false } +cumulus-relay-chain-minimal-node = { path = "cumulus/client/relay-chain-minimal-node", default-features = false } +cumulus-relay-chain-rpc-interface = { path = "cumulus/client/relay-chain-rpc-interface", default-features = false } +cumulus-test-client = { path = "cumulus/test/client" } +cumulus-test-relay-sproof-builder = { path = "cumulus/test/relay-sproof-builder", default-features = false } +cumulus-test-runtime = { path = "cumulus/test/runtime" } +cumulus-test-service = { path = "cumulus/test/service" } +curve25519-dalek = { version = "4.1.3" } +derivative = { version = "2.2.0", default-features = false } +derive-syn-parse = { version = "0.2.0" } +derive_more = { version = "0.99.17", default-features = false } +digest = { version = "0.10.3", default-features = false } +directories = { version = "5.0.1" } +dlmalloc = { version = "0.2.4" } +docify = { version = "0.2.8" } +dyn-clonable = { version = "0.9.0" } +dyn-clone = { version = "1.0.16" } +ed25519-dalek = { version = "2.1", default-features = false } +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" } +env_logger = { version = "0.11.3" } +environmental = { version = "1.1.4", default-features = false } +equivocation-detector = { path = "bridges/relays/equivocation" } +ethabi = { version = "1.0.0", default-features = false, package = "ethabi-decode" } +ethbloom = { version = "0.13.0", default-features = false } +ethereum-types = { version = "0.14.1", default-features = false } +exit-future = { version = "0.2.0" } +expander = { version = "2.0.0" } +fatality = { version = "0.1.1" } +fdlimit = { version = "0.3.0" } +femme = { version = "2.2.1" } +filetime = { version = "0.2.16" } +finality-grandpa = { version = "0.16.2", default-features = false } +finality-relay = { path = "bridges/relays/finality" } +flate2 = { version = "1.0" } +fnv = { version = "1.0.6" } +fork-tree = { path = "substrate/utils/fork-tree", default-features = false } +forwarded-header-value = { version = "0.1.1" } +fraction = { version = "0.13.1" } +frame = { path = "substrate/frame", default-features = false, package = "polkadot-sdk-frame" } +frame-benchmarking = { path = "substrate/frame/benchmarking", default-features = false } +frame-benchmarking-cli = { path = "substrate/utils/frame/benchmarking-cli", default-features = false } +frame-benchmarking-pallet-pov = { default-features = false, path = "substrate/frame/benchmarking/pov" } +frame-election-provider-solution-type = { path = "substrate/frame/election-provider-support/solution-type", default-features = false } +frame-election-provider-support = { path = "substrate/frame/election-provider-support", default-features = false } +frame-executive = { path = "substrate/frame/executive", default-features = false } +frame-metadata = { version = "16.0.0", default-features = false } +frame-metadata-hash-extension = { path = "substrate/frame/metadata-hash-extension", default-features = false } +frame-support = { path = "substrate/frame/support", default-features = false } +frame-support-procedural = { path = "substrate/frame/support/procedural", default-features = false } +frame-support-procedural-tools = { path = "substrate/frame/support/procedural/tools", default-features = false } +frame-support-procedural-tools-derive = { path = "substrate/frame/support/procedural/tools/derive", default-features = false } +frame-support-test = { path = "substrate/frame/support/test" } +frame-system = { path = "substrate/frame/system", default-features = false } +frame-system-benchmarking = { path = "substrate/frame/system/benchmarking", default-features = false } +frame-system-rpc-runtime-api = { path = "substrate/frame/system/rpc/runtime-api", default-features = false } +frame-try-runtime = { path = "substrate/frame/try-runtime", default-features = false } +fs4 = { version = "0.7.0" } +fs_extra = { version = "1.3.0" } +futures = { version = "0.3.30" } +futures-channel = { version = "0.3.23" } +futures-timer = { version = "3.0.2" } +futures-util = { version = "0.3.30", default-features = false } +generate-bags = { path = "substrate/utils/frame/generate-bags", default-features = false } +gethostname = { version = "0.2.3" } +glob = { version = "0.3" } +glutton-westend-runtime = { path = "cumulus/parachains/runtimes/glutton/glutton-westend" } +governor = { version = "0.6.0" } +gum = { path = "polkadot/node/gum", default-features = false, package = "tracing-gum" } +gum-proc-macro = { path = "polkadot/node/gum/proc-macro", default-features = false, package = "tracing-gum-proc-macro" } +handlebars = { version = "5.1.0" } +hash-db = { version = "0.16.0", default-features = false } +hash256-std-hasher = { version = "0.15.2", default-features = false } +hex = { version = "0.4.3", default-features = false } +hex-literal = { version = "0.4.1", default-features = false } +hkdf = { version = "0.12.0" } +hmac = { version = "0.12.1" } +honggfuzz = { version = "0.5.55" } +http = { version = "0.2.8" } +http-body-util = { version = "0.1.2" } +hyper = { version = "0.14.27", default-features = false } +hyper-rustls = { version = "0.24.0" } +impl-serde = { version = "0.4.0", default-features = false } +impl-trait-for-tuples = { version = "0.2.2" } +indexmap = { version = "2.0.0" } +indicatif = { version = "0.17.7" } +integer-sqrt = { version = "0.1.2" } +ip_network = { version = "0.4.1" } +is-terminal = { version = "0.4.9" } +is_executable = { version = "1.0.1" } +isahc = { version = "1.2" } +itertools = { version = "0.11" } +jsonpath_lib = { version = "0.3" } +jsonrpsee = { version = "0.23.2" } +jsonrpsee-core = { version = "0.23.2" } +k256 = { version = "0.13.3", default-features = false } +kitchensink-runtime = { path = "substrate/bin/node/runtime" } +kvdb = { version = "0.13.0" } +kvdb-memorydb = { version = "0.13.0" } +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" } +libfuzzer-sys = { version = "0.4" } +libp2p = { version = "0.52.4" } +libp2p-identity = { version = "0.2.3" } +libsecp256k1 = { version = "0.7.0", default-features = false } +linked-hash-map = { version = "0.5.4" } +linked_hash_set = { version = "0.1.4" } +linregress = { version = "0.5.1" } +lite-json = { version = "0.2.0", default-features = false } +litep2p = { version = "0.5.0" } +log = { version = "0.4.21", default-features = false } +macro_magic = { version = "0.5.0" } +maplit = { version = "1.0.2" } +memmap2 = { version = "0.9.3" } +memory-db = { version = "0.32.0", default-features = false } +merkleized-metadata = { version = "0.1.0" } +merlin = { version = "3.0", default-features = false } +messages-relay = { path = "bridges/relays/messages" } +metered = { version = "0.6.1", default-features = false, package = "prioritized-metered-channel" } +mick-jaeger = { version = "0.1.8" } +milagro-bls = { version = "1.5.4", default-features = false, package = "snowbridge-milagro-bls" } +minimal-template-node = { path = "templates/minimal/node" } +minimal-template-runtime = { path = "templates/minimal/runtime" } +mixnet = { version = "0.7.0" } +mmr-gadget = { path = "substrate/client/merkle-mountain-range", default-features = false } +mmr-lib = { version = "0.5.2", package = "ckb-merkle-mountain-range" } +mmr-rpc = { path = "substrate/client/merkle-mountain-range/rpc", default-features = false } +mockall = { version = "0.11.3" } +multiaddr = { version = "0.18.1" } +multihash = { version = "0.19.1", default-features = false } +multihash-codetable = { version = "0.1.1" } +multistream-select = { version = "0.13.0" } +names = { version = "0.14.0", default-features = false } +nix = { version = "0.28.0" } +node-cli = { path = "substrate/bin/node/cli", package = "staging-node-cli" } +node-inspect = { path = "substrate/bin/node/inspect", default-features = false, package = "staging-node-inspect" } +node-primitives = { path = "substrate/bin/node/primitives", default-features = false } +node-rpc = { path = "substrate/bin/node/rpc" } +node-testing = { path = "substrate/bin/node/testing" } +nohash-hasher = { version = "0.2.0" } +novelpoly = { version = "2.0.0", package = "reed-solomon-novelpoly" } +num-bigint = { version = "0.4.3" } +num-format = { version = "0.4.3" } +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 } +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 } +pallet-asset-conversion-tx-payment = { path = "substrate/frame/transaction-payment/asset-conversion-tx-payment", default-features = false } +pallet-asset-rate = { path = "substrate/frame/asset-rate", default-features = false } +pallet-asset-tx-payment = { path = "substrate/frame/transaction-payment/asset-tx-payment", default-features = false } +pallet-assets = { path = "substrate/frame/assets", default-features = false } +pallet-assets-freezer = { path = "substrate/frame/assets-freezer", default-features = false } +pallet-atomic-swap = { default-features = false, path = "substrate/frame/atomic-swap" } +pallet-aura = { path = "substrate/frame/aura", default-features = false } +pallet-authority-discovery = { path = "substrate/frame/authority-discovery", default-features = false } +pallet-authorship = { path = "substrate/frame/authorship", default-features = false } +pallet-babe = { path = "substrate/frame/babe", default-features = false } +pallet-bags-list = { path = "substrate/frame/bags-list", default-features = false } +pallet-bags-list-remote-tests = { path = "substrate/frame/bags-list/remote-tests" } +pallet-balances = { path = "substrate/frame/balances", default-features = false } +pallet-beefy = { path = "substrate/frame/beefy", default-features = false } +pallet-beefy-mmr = { path = "substrate/frame/beefy-mmr", default-features = false } +pallet-bounties = { path = "substrate/frame/bounties", default-features = false } +pallet-bridge-grandpa = { path = "bridges/modules/grandpa", default-features = false } +pallet-bridge-messages = { path = "bridges/modules/messages", default-features = false } +pallet-bridge-parachains = { path = "bridges/modules/parachains", default-features = false } +pallet-bridge-relayers = { path = "bridges/modules/relayers", default-features = false } +pallet-broker = { path = "substrate/frame/broker", default-features = false } +pallet-child-bounties = { path = "substrate/frame/child-bounties", default-features = false } +pallet-collator-selection = { path = "cumulus/pallets/collator-selection", default-features = false } +pallet-collective = { path = "substrate/frame/collective", default-features = false } +pallet-collective-content = { path = "cumulus/parachains/pallets/collective-content", default-features = false } +pallet-contracts = { path = "substrate/frame/contracts", default-features = false } +pallet-contracts-fixtures = { path = "substrate/frame/contracts/fixtures" } +pallet-contracts-mock-network = { default-features = false, path = "substrate/frame/contracts/mock-network" } +pallet-contracts-proc-macro = { path = "substrate/frame/contracts/proc-macro", default-features = false } +pallet-contracts-uapi = { path = "substrate/frame/contracts/uapi", default-features = false } +pallet-conviction-voting = { path = "substrate/frame/conviction-voting", default-features = false } +pallet-core-fellowship = { path = "substrate/frame/core-fellowship", default-features = false } +pallet-default-config-example = { path = "substrate/frame/examples/default-config", default-features = false } +pallet-delegated-staking = { path = "substrate/frame/delegated-staking", default-features = false } +pallet-democracy = { path = "substrate/frame/democracy", default-features = false } +pallet-dev-mode = { path = "substrate/frame/examples/dev-mode", default-features = false } +pallet-election-provider-multi-phase = { path = "substrate/frame/election-provider-multi-phase", default-features = false } +pallet-election-provider-support-benchmarking = { path = "substrate/frame/election-provider-support/benchmarking", default-features = false } +pallet-elections-phragmen = { path = "substrate/frame/elections-phragmen", default-features = false } +pallet-example-basic = { path = "substrate/frame/examples/basic", default-features = false } +pallet-example-frame-crate = { path = "substrate/frame/examples/frame-crate", default-features = false } +pallet-example-kitchensink = { path = "substrate/frame/examples/kitchensink", default-features = false } +pallet-example-mbm = { path = "substrate/frame/examples/multi-block-migrations", default-features = false } +pallet-example-offchain-worker = { path = "substrate/frame/examples/offchain-worker", default-features = false } +pallet-example-single-block-migrations = { path = "substrate/frame/examples/single-block-migrations", default-features = false } +pallet-example-split = { path = "substrate/frame/examples/split", default-features = false } +pallet-example-tasks = { path = "substrate/frame/examples/tasks", default-features = false } +pallet-examples = { path = "substrate/frame/examples" } +pallet-fast-unstake = { path = "substrate/frame/fast-unstake", default-features = false } +pallet-glutton = { path = "substrate/frame/glutton", default-features = false } +pallet-grandpa = { path = "substrate/frame/grandpa", default-features = false } +pallet-identity = { path = "substrate/frame/identity", default-features = false } +pallet-im-online = { path = "substrate/frame/im-online", default-features = false } +pallet-indices = { path = "substrate/frame/indices", default-features = false } +pallet-insecure-randomness-collective-flip = { path = "substrate/frame/insecure-randomness-collective-flip", default-features = false } +pallet-lottery = { default-features = false, path = "substrate/frame/lottery" } +pallet-membership = { path = "substrate/frame/membership", default-features = false } +pallet-message-queue = { path = "substrate/frame/message-queue", default-features = false } +pallet-migrations = { path = "substrate/frame/migrations", default-features = false } +pallet-minimal-template = { path = "templates/minimal/pallets/template", default-features = false } +pallet-mixnet = { default-features = false, path = "substrate/frame/mixnet" } +pallet-mmr = { path = "substrate/frame/merkle-mountain-range", default-features = false } +pallet-multisig = { path = "substrate/frame/multisig", default-features = false } +pallet-nft-fractionalization = { path = "substrate/frame/nft-fractionalization", default-features = false } +pallet-nfts = { path = "substrate/frame/nfts", default-features = false } +pallet-nfts-runtime-api = { path = "substrate/frame/nfts/runtime-api", default-features = false } +pallet-nis = { path = "substrate/frame/nis", default-features = false } +pallet-node-authorization = { default-features = false, path = "substrate/frame/node-authorization" } +pallet-nomination-pools = { path = "substrate/frame/nomination-pools", default-features = false } +pallet-nomination-pools-benchmarking = { path = "substrate/frame/nomination-pools/benchmarking", default-features = false } +pallet-nomination-pools-runtime-api = { path = "substrate/frame/nomination-pools/runtime-api", default-features = false } +pallet-offences = { path = "substrate/frame/offences", default-features = false } +pallet-offences-benchmarking = { path = "substrate/frame/offences/benchmarking", default-features = false } +pallet-paged-list = { path = "substrate/frame/paged-list", default-features = false } +pallet-parachain-template = { path = "templates/parachain/pallets/template", default-features = false } +pallet-parameters = { path = "substrate/frame/parameters", default-features = false } +pallet-preimage = { path = "substrate/frame/preimage", default-features = false } +pallet-proxy = { path = "substrate/frame/proxy", default-features = false } +pallet-ranked-collective = { path = "substrate/frame/ranked-collective", default-features = false } +pallet-recovery = { path = "substrate/frame/recovery", default-features = false } +pallet-referenda = { path = "substrate/frame/referenda", default-features = false } +pallet-remark = { default-features = false, path = "substrate/frame/remark" } +pallet-root-offences = { default-features = false, path = "substrate/frame/root-offences" } +pallet-root-testing = { path = "substrate/frame/root-testing", default-features = false } +pallet-safe-mode = { default-features = false, path = "substrate/frame/safe-mode" } +pallet-salary = { path = "substrate/frame/salary", default-features = false } +pallet-scheduler = { path = "substrate/frame/scheduler", default-features = false } +pallet-scored-pool = { default-features = false, path = "substrate/frame/scored-pool" } +pallet-session = { path = "substrate/frame/session", default-features = false } +pallet-session-benchmarking = { path = "substrate/frame/session/benchmarking", default-features = false } +pallet-skip-feeless-payment = { path = "substrate/frame/transaction-payment/skip-feeless-payment", default-features = false } +pallet-society = { path = "substrate/frame/society", default-features = false } +pallet-staking = { path = "substrate/frame/staking", default-features = false } +pallet-staking-reward-curve = { path = "substrate/frame/staking/reward-curve", default-features = false } +pallet-staking-reward-fn = { path = "substrate/frame/staking/reward-fn", default-features = false } +pallet-staking-runtime-api = { path = "substrate/frame/staking/runtime-api", default-features = false } +pallet-state-trie-migration = { path = "substrate/frame/state-trie-migration", default-features = false } +pallet-statement = { default-features = false, path = "substrate/frame/statement" } +pallet-sudo = { path = "substrate/frame/sudo", default-features = false } +pallet-template = { path = "templates/solochain/pallets/template", default-features = false } +pallet-timestamp = { path = "substrate/frame/timestamp", default-features = false } +pallet-tips = { path = "substrate/frame/tips", default-features = false } +pallet-transaction-payment = { path = "substrate/frame/transaction-payment", default-features = false } +pallet-transaction-payment-rpc = { path = "substrate/frame/transaction-payment/rpc", default-features = false } +pallet-transaction-payment-rpc-runtime-api = { path = "substrate/frame/transaction-payment/rpc/runtime-api", default-features = false } +pallet-transaction-storage = { default-features = false, path = "substrate/frame/transaction-storage" } +pallet-treasury = { path = "substrate/frame/treasury", default-features = false } +pallet-tx-pause = { default-features = false, path = "substrate/frame/tx-pause" } +pallet-uniques = { path = "substrate/frame/uniques", default-features = false } +pallet-utility = { path = "substrate/frame/utility", default-features = false } +pallet-vesting = { path = "substrate/frame/vesting", default-features = false } +pallet-whitelist = { path = "substrate/frame/whitelist", default-features = false } +pallet-xcm = { path = "polkadot/xcm/pallet-xcm", default-features = false } +pallet-xcm-benchmarks = { path = "polkadot/xcm/pallet-xcm-benchmarks", default-features = false } +pallet-xcm-bridge-hub = { path = "bridges/modules/xcm-bridge-hub", default-features = false } +pallet-xcm-bridge-hub-router = { path = "bridges/modules/xcm-bridge-hub-router", default-features = false } +parachain-info = { path = "cumulus/parachains/pallets/parachain-info", default-features = false, package = "staging-parachain-info" } +parachain-template-runtime = { path = "templates/parachain/runtime" } +parachains-common = { path = "cumulus/parachains/common", default-features = false } +parachains-relay = { path = "bridges/relays/parachains" } +parachains-runtimes-test-utils = { path = "cumulus/parachains/runtimes/test-utils", default-features = false } +parity-bytes = { version = "0.1.2", default-features = false } +parity-db = { version = "0.4.12" } +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 } +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" } +people-rococo-emulated-chain = { path = "cumulus/parachains/integration-tests/emulated/chains/parachains/people/people-rococo" } +people-rococo-runtime = { path = "cumulus/parachains/runtimes/people/people-rococo" } +people-westend-emulated-chain = { path = "cumulus/parachains/integration-tests/emulated/chains/parachains/people/people-westend" } +people-westend-runtime = { path = "cumulus/parachains/runtimes/people/people-westend" } +pin-project = { version = "1.1.3" } +platforms = { version = "3.0" } +polkadot-approval-distribution = { path = "polkadot/node/network/approval-distribution", default-features = false } +polkadot-availability-bitfield-distribution = { path = "polkadot/node/network/bitfield-distribution", default-features = false } +polkadot-availability-distribution = { path = "polkadot/node/network/availability-distribution", default-features = false } +polkadot-availability-recovery = { path = "polkadot/node/network/availability-recovery", default-features = false } +polkadot-cli = { path = "polkadot/cli", default-features = false } +polkadot-collator-protocol = { path = "polkadot/node/network/collator-protocol", default-features = false } +polkadot-core-primitives = { path = "polkadot/core-primitives", default-features = false } +polkadot-dispute-distribution = { path = "polkadot/node/network/dispute-distribution", default-features = false } +polkadot-erasure-coding = { path = "polkadot/erasure-coding", default-features = false } +polkadot-gossip-support = { path = "polkadot/node/network/gossip-support", default-features = false } +polkadot-network-bridge = { path = "polkadot/node/network/bridge", default-features = false } +polkadot-node-collation-generation = { path = "polkadot/node/collation-generation", default-features = false } +polkadot-node-core-approval-voting = { path = "polkadot/node/core/approval-voting", default-features = false } +polkadot-node-core-av-store = { path = "polkadot/node/core/av-store", default-features = false } +polkadot-node-core-backing = { path = "polkadot/node/core/backing", default-features = false } +polkadot-node-core-bitfield-signing = { path = "polkadot/node/core/bitfield-signing", default-features = false } +polkadot-node-core-candidate-validation = { path = "polkadot/node/core/candidate-validation", default-features = false } +polkadot-node-core-chain-api = { path = "polkadot/node/core/chain-api", default-features = false } +polkadot-node-core-chain-selection = { path = "polkadot/node/core/chain-selection", default-features = false } +polkadot-node-core-dispute-coordinator = { path = "polkadot/node/core/dispute-coordinator", default-features = false } +polkadot-node-core-parachains-inherent = { path = "polkadot/node/core/parachains-inherent", default-features = false } +polkadot-node-core-prospective-parachains = { path = "polkadot/node/core/prospective-parachains", default-features = false } +polkadot-node-core-provisioner = { path = "polkadot/node/core/provisioner", default-features = false } +polkadot-node-core-pvf = { path = "polkadot/node/core/pvf", default-features = false } +polkadot-node-core-pvf-checker = { path = "polkadot/node/core/pvf-checker", default-features = false } +polkadot-node-core-pvf-common = { path = "polkadot/node/core/pvf/common", default-features = false } +polkadot-node-core-pvf-execute-worker = { path = "polkadot/node/core/pvf/execute-worker", default-features = false } +polkadot-node-core-pvf-prepare-worker = { path = "polkadot/node/core/pvf/prepare-worker", default-features = false } +polkadot-node-core-runtime-api = { path = "polkadot/node/core/runtime-api", default-features = false } +polkadot-node-jaeger = { path = "polkadot/node/jaeger", default-features = false } +polkadot-node-metrics = { path = "polkadot/node/metrics", default-features = false } +polkadot-node-network-protocol = { path = "polkadot/node/network/protocol", default-features = false } +polkadot-node-primitives = { path = "polkadot/node/primitives", default-features = false } +polkadot-node-subsystem = { path = "polkadot/node/subsystem", default-features = false } +polkadot-node-subsystem-test-helpers = { path = "polkadot/node/subsystem-test-helpers" } +polkadot-node-subsystem-types = { path = "polkadot/node/subsystem-types", default-features = false } +polkadot-node-subsystem-util = { path = "polkadot/node/subsystem-util", default-features = false } +polkadot-overseer = { path = "polkadot/node/overseer", default-features = false } +polkadot-parachain-primitives = { path = "polkadot/parachain", default-features = false } +polkadot-primitives = { path = "polkadot/primitives", default-features = false } +polkadot-primitives-test-helpers = { path = "polkadot/primitives/test-helpers" } +polkadot-rpc = { path = "polkadot/rpc", default-features = false } +polkadot-runtime-common = { path = "polkadot/runtime/common", default-features = false } +polkadot-runtime-metrics = { path = "polkadot/runtime/metrics", default-features = false } +polkadot-runtime-parachains = { path = "polkadot/runtime/parachains", default-features = false } +polkadot-sdk = { path = "umbrella", default-features = false } +polkadot-sdk-docs = { path = "docs/sdk" } +polkadot-service = { path = "polkadot/node/service", default-features = false } +polkadot-statement-distribution = { path = "polkadot/node/network/statement-distribution", default-features = false } +polkadot-statement-table = { path = "polkadot/statement-table", default-features = false } +polkadot-subsystem-bench = { path = "polkadot/node/subsystem-bench" } +polkadot-test-client = { path = "polkadot/node/test/client" } +polkadot-test-runtime = { path = "polkadot/runtime/test-runtime" } +polkadot-test-service = { path = "polkadot/node/test/service" } polkavm = "0.9.3" -polkavm-linker = "0.9.2" polkavm-derive = "0.9.1" -log = { version = "0.4.21", default-features = false } +polkavm-linker = "0.9.2" +portpicker = { version = "0.1.1" } +pretty_assertions = { version = "1.3.0" } +primitive-types = { version = "0.12.1", default-features = false } +proc-macro-crate = { version = "3.0.0" } +proc-macro-warning = { version = "1.0.0", default-features = false } +proc-macro2 = { version = "1.0.64" } +procfs = { version = "0.16.0" } +prometheus = { version = "0.13.0", default-features = false } +prometheus-endpoint = { path = "substrate/utils/prometheus", default-features = false, package = "substrate-prometheus-endpoint" } +prometheus-parse = { version = "0.2.2" } +prost = { version = "0.12.4" } +prost-build = { version = "0.12.4" } +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" } +rand = { version = "0.8.5", default-features = false } +rand_chacha = { version = "0.3.1", default-features = false } +rand_core = { version = "0.6.2" } +rand_distr = { version = "0.4.3" } +rand_pcg = { version = "0.3.1" } +rayon = { version = "1.5.1" } +rbtag = { version = "0.3" } +ref-cast = { version = "1.0.0" } +regex = { version = "1.10.2" } +relay-substrate-client = { path = "bridges/relays/client-substrate" } +relay-utils = { path = "bridges/relays/utils" } +remote-externalities = { path = "substrate/utils/frame/remote-externalities", default-features = false, package = "frame-remote-externalities" } +reqwest = { version = "0.11", default-features = false } +rlp = { version = "0.5.2", default-features = false } +rococo-emulated-chain = { path = "cumulus/parachains/integration-tests/emulated/chains/relays/rococo" } +rococo-parachain-runtime = { path = "cumulus/parachains/runtimes/testing/rococo-parachain" } +rococo-runtime = { path = "polkadot/runtime/rococo" } +rococo-runtime-constants = { path = "polkadot/runtime/rococo/constants", default-features = false } +rococo-system-emulated-network = { path = "cumulus/parachains/integration-tests/emulated/networks/rococo-system" } +rococo-westend-system-emulated-network = { path = "cumulus/parachains/integration-tests/emulated/networks/rococo-westend-system" } +rpassword = { version = "7.0.0" } +rstest = { version = "0.18.2" } +rustc-hash = { version = "1.1.0" } +rustc-hex = { version = "2.1.0", default-features = false } +rustix = { version = "0.36.7", default-features = false } +rustversion = { version = "1.0.6" } +rusty-fork = { version = "0.3.0", default-features = false } +safe-mix = { version = "1.0", default-features = false } +sc-allocator = { path = "substrate/client/allocator", default-features = false } +sc-authority-discovery = { path = "substrate/client/authority-discovery", default-features = false } +sc-basic-authorship = { path = "substrate/client/basic-authorship", default-features = false } +sc-block-builder = { path = "substrate/client/block-builder", default-features = false } +sc-chain-spec = { path = "substrate/client/chain-spec", default-features = false } +sc-chain-spec-derive = { path = "substrate/client/chain-spec/derive", default-features = false } +sc-cli = { path = "substrate/client/cli", default-features = false } +sc-client-api = { path = "substrate/client/api", default-features = false } +sc-client-db = { path = "substrate/client/db", default-features = false } +sc-consensus = { path = "substrate/client/consensus/common", default-features = false } +sc-consensus-aura = { path = "substrate/client/consensus/aura", default-features = false } +sc-consensus-babe = { path = "substrate/client/consensus/babe", default-features = false } +sc-consensus-babe-rpc = { path = "substrate/client/consensus/babe/rpc", default-features = false } +sc-consensus-beefy = { path = "substrate/client/consensus/beefy", default-features = false } +sc-consensus-beefy-rpc = { path = "substrate/client/consensus/beefy/rpc", default-features = false } +sc-consensus-epochs = { path = "substrate/client/consensus/epochs", default-features = false } +sc-consensus-grandpa = { path = "substrate/client/consensus/grandpa", default-features = false } +sc-consensus-grandpa-rpc = { path = "substrate/client/consensus/grandpa/rpc", default-features = false } +sc-consensus-manual-seal = { path = "substrate/client/consensus/manual-seal", default-features = false } +sc-consensus-pow = { path = "substrate/client/consensus/pow", default-features = false } +sc-consensus-slots = { path = "substrate/client/consensus/slots", default-features = false } +sc-executor = { path = "substrate/client/executor", default-features = false } +sc-executor-common = { path = "substrate/client/executor/common", default-features = false } +sc-executor-polkavm = { path = "substrate/client/executor/polkavm", default-features = false } +sc-executor-wasmtime = { path = "substrate/client/executor/wasmtime", default-features = false } +sc-informant = { path = "substrate/client/informant", default-features = false } +sc-keystore = { path = "substrate/client/keystore", default-features = false } +sc-mixnet = { path = "substrate/client/mixnet", default-features = false } +sc-network = { path = "substrate/client/network", default-features = false } +sc-network-common = { path = "substrate/client/network/common", default-features = false } +sc-network-gossip = { path = "substrate/client/network-gossip", default-features = false } +sc-network-light = { path = "substrate/client/network/light", default-features = false } +sc-network-statement = { default-features = false, path = "substrate/client/network/statement" } +sc-network-sync = { path = "substrate/client/network/sync", default-features = false } +sc-network-test = { path = "substrate/client/network/test" } +sc-network-transactions = { path = "substrate/client/network/transactions", default-features = false } +sc-network-types = { path = "substrate/client/network/types", default-features = false } +sc-offchain = { path = "substrate/client/offchain", default-features = false } +sc-proposer-metrics = { path = "substrate/client/proposer-metrics", default-features = false } +sc-rpc = { path = "substrate/client/rpc", default-features = false } +sc-rpc-api = { path = "substrate/client/rpc-api", default-features = false } +sc-rpc-server = { path = "substrate/client/rpc-servers", default-features = false } +sc-rpc-spec-v2 = { path = "substrate/client/rpc-spec-v2", default-features = false } +sc-runtime-test = { path = "substrate/client/executor/runtime-test" } +sc-service = { path = "substrate/client/service", default-features = false } +sc-service-test = { path = "substrate/client/service/test" } +sc-state-db = { path = "substrate/client/state-db", default-features = false } +sc-statement-store = { default-features = false, path = "substrate/client/statement-store" } +sc-storage-monitor = { path = "substrate/client/storage-monitor", default-features = false } +sc-sync-state-rpc = { path = "substrate/client/sync-state-rpc", default-features = false } +sc-sysinfo = { path = "substrate/client/sysinfo", default-features = false } +sc-telemetry = { path = "substrate/client/telemetry", default-features = false } +sc-tracing = { path = "substrate/client/tracing", default-features = false } +sc-tracing-proc-macro = { path = "substrate/client/tracing/proc-macro", default-features = false } +sc-transaction-pool = { path = "substrate/client/transaction-pool", default-features = false } +sc-transaction-pool-api = { path = "substrate/client/transaction-pool/api", default-features = false } +sc-utils = { path = "substrate/client/utils", default-features = false } +scale-info = { version = "2.11.1", default-features = false } +schemars = { version = "0.8.13", default-features = false } +schnellru = { version = "0.2.1" } +schnorrkel = { version = "0.11.4", default-features = false } +seccompiler = { version = "0.4.0" } +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-big-array = { version = "0.3.2" } serde_derive = { version = "1.0.117" } serde_json = { version = "1.0.114", default-features = false } serde_yaml = { version = "0.9" } +serial_test = { version = "2.0.0" } +sha1 = { version = "0.10.6" } +sha2 = { version = "0.10.7", default-features = false } +sha3 = { version = "0.10.0", default-features = false } +shell-runtime = { path = "cumulus/parachains/runtimes/starters/shell" } +slot-range-helper = { path = "polkadot/runtime/common/slot_range_helper", default-features = false } +slotmap = { version = "1.0" } +smallvec = { version = "1.11.0", default-features = false } +smoldot = { version = "0.11.0", default-features = false } +smoldot-light = { version = "0.9.0", default-features = false } +snowbridge-beacon-primitives = { path = "bridges/snowbridge/primitives/beacon", default-features = false } +snowbridge-core = { path = "bridges/snowbridge/primitives/core", default-features = false } +snowbridge-ethereum = { path = "bridges/snowbridge/primitives/ethereum", default-features = false } +snowbridge-outbound-queue-merkle-tree = { path = "bridges/snowbridge/pallets/outbound-queue/merkle-tree", default-features = false } +snowbridge-outbound-queue-runtime-api = { path = "bridges/snowbridge/pallets/outbound-queue/runtime-api", default-features = false } +snowbridge-pallet-ethereum-client = { path = "bridges/snowbridge/pallets/ethereum-client", default-features = false } +snowbridge-pallet-ethereum-client-fixtures = { path = "bridges/snowbridge/pallets/ethereum-client/fixtures", default-features = false } +snowbridge-pallet-inbound-queue = { path = "bridges/snowbridge/pallets/inbound-queue", default-features = false } +snowbridge-pallet-inbound-queue-fixtures = { path = "bridges/snowbridge/pallets/inbound-queue/fixtures", default-features = false } +snowbridge-pallet-outbound-queue = { path = "bridges/snowbridge/pallets/outbound-queue", default-features = false } +snowbridge-pallet-system = { path = "bridges/snowbridge/pallets/system", default-features = false } +snowbridge-router-primitives = { path = "bridges/snowbridge/primitives/router", default-features = false } +snowbridge-runtime-common = { path = "bridges/snowbridge/runtime/runtime-common", default-features = false } +snowbridge-runtime-test-common = { path = "bridges/snowbridge/runtime/test-common", default-features = false } +snowbridge-system-runtime-api = { path = "bridges/snowbridge/pallets/system/runtime-api", default-features = false } +soketto = { version = "0.7.1" } +solochain-template-runtime = { path = "templates/solochain/runtime" } +sp-api = { path = "substrate/primitives/api", default-features = false } +sp-api-proc-macro = { path = "substrate/primitives/api/proc-macro", default-features = false } +sp-application-crypto = { path = "substrate/primitives/application-crypto", default-features = false } +sp-arithmetic = { path = "substrate/primitives/arithmetic", default-features = false } +sp-authority-discovery = { path = "substrate/primitives/authority-discovery", default-features = false } +sp-block-builder = { path = "substrate/primitives/block-builder", default-features = false } +sp-blockchain = { path = "substrate/primitives/blockchain", default-features = false } +sp-consensus = { path = "substrate/primitives/consensus/common", default-features = false } +sp-consensus-aura = { path = "substrate/primitives/consensus/aura", default-features = false } +sp-consensus-babe = { path = "substrate/primitives/consensus/babe", default-features = false } +sp-consensus-beefy = { path = "substrate/primitives/consensus/beefy", default-features = false } +sp-consensus-grandpa = { path = "substrate/primitives/consensus/grandpa", default-features = false } +sp-consensus-pow = { path = "substrate/primitives/consensus/pow", default-features = false } +sp-consensus-sassafras = { path = "substrate/primitives/consensus/sassafras", default-features = false } +sp-consensus-slots = { path = "substrate/primitives/consensus/slots", default-features = false } +sp-core = { path = "substrate/primitives/core", default-features = false } +sp-core-hashing = { default-features = false, path = "substrate/deprecated/hashing" } +sp-core-hashing-proc-macro = { default-features = false, path = "substrate/deprecated/hashing/proc-macro" } +sp-crypto-ec-utils = { default-features = false, path = "substrate/primitives/crypto/ec-utils" } +sp-crypto-hashing = { path = "substrate/primitives/crypto/hashing", default-features = false } +sp-crypto-hashing-proc-macro = { path = "substrate/primitives/crypto/hashing/proc-macro", default-features = false } +sp-database = { path = "substrate/primitives/database", default-features = false } +sp-debug-derive = { path = "substrate/primitives/debug-derive", default-features = false } +sp-externalities = { path = "substrate/primitives/externalities", default-features = false } +sp-genesis-builder = { path = "substrate/primitives/genesis-builder", default-features = false } +sp-inherents = { path = "substrate/primitives/inherents", default-features = false } +sp-io = { path = "substrate/primitives/io", default-features = false } +sp-keyring = { path = "substrate/primitives/keyring", default-features = false } +sp-keystore = { path = "substrate/primitives/keystore", default-features = false } +sp-maybe-compressed-blob = { path = "substrate/primitives/maybe-compressed-blob", default-features = false } +sp-metadata-ir = { path = "substrate/primitives/metadata-ir", default-features = false } +sp-mixnet = { path = "substrate/primitives/mixnet", default-features = false } +sp-mmr-primitives = { path = "substrate/primitives/merkle-mountain-range", default-features = false } +sp-npos-elections = { path = "substrate/primitives/npos-elections", default-features = false } +sp-offchain = { path = "substrate/primitives/offchain", default-features = false } +sp-panic-handler = { path = "substrate/primitives/panic-handler", default-features = false } +sp-rpc = { path = "substrate/primitives/rpc", default-features = false } +sp-runtime = { path = "substrate/primitives/runtime", default-features = false } +sp-runtime-interface = { path = "substrate/primitives/runtime-interface", default-features = false } +sp-runtime-interface-proc-macro = { path = "substrate/primitives/runtime-interface/proc-macro", default-features = false } +sp-runtime-interface-test-wasm = { path = "substrate/primitives/runtime-interface/test-wasm" } +sp-runtime-interface-test-wasm-deprecated = { path = "substrate/primitives/runtime-interface/test-wasm-deprecated" } +sp-session = { path = "substrate/primitives/session", default-features = false } +sp-staking = { path = "substrate/primitives/staking", default-features = false } +sp-state-machine = { path = "substrate/primitives/state-machine", default-features = false } +sp-statement-store = { path = "substrate/primitives/statement-store", default-features = false } +sp-std = { path = "substrate/primitives/std", default-features = false } +sp-storage = { path = "substrate/primitives/storage", default-features = false } +sp-test-primitives = { path = "substrate/primitives/test-primitives" } +sp-timestamp = { path = "substrate/primitives/timestamp", default-features = false } +sp-tracing = { path = "substrate/primitives/tracing", default-features = false } +sp-transaction-pool = { path = "substrate/primitives/transaction-pool", default-features = false } +sp-transaction-storage-proof = { path = "substrate/primitives/transaction-storage-proof", default-features = false } +sp-trie = { path = "substrate/primitives/trie", default-features = false } +sp-version = { path = "substrate/primitives/version", default-features = false } +sp-version-proc-macro = { path = "substrate/primitives/version/proc-macro", default-features = false } +sp-wasm-interface = { path = "substrate/primitives/wasm-interface", default-features = false } +sp-weights = { path = "substrate/primitives/weights", default-features = false } +spinners = { version = "4.1.0" } +ss58-registry = { version = "1.34.0", default-features = false } +ssz_rs = { version = "0.9.0", default-features = false } +ssz_rs_derive = { version = "0.9.0", default-features = false } +static_assertions = { version = "1.1.0", default-features = false } +static_init = { version = "1.0.3" } +structopt = { version = "0.3" } +strum = { version = "0.26.2", default-features = false } +subkey = { path = "substrate/bin/utils/subkey", default-features = false } +substrate-bip39 = { path = "substrate/utils/substrate-bip39", default-features = false } +substrate-build-script-utils = { path = "substrate/utils/build-script-utils", default-features = false } +substrate-cli-test-utils = { path = "substrate/test-utils/cli" } +substrate-frame-rpc-support = { default-features = false, path = "substrate/utils/frame/rpc/support" } +substrate-frame-rpc-system = { path = "substrate/utils/frame/rpc/system", default-features = false } +substrate-rpc-client = { path = "substrate/utils/frame/rpc/client", default-features = false } +substrate-state-trie-migration-rpc = { path = "substrate/utils/frame/rpc/state-trie-migration-rpc", default-features = false } +substrate-test-client = { path = "substrate/test-utils/client" } +substrate-test-runtime = { path = "substrate/test-utils/runtime" } +substrate-test-runtime-client = { path = "substrate/test-utils/runtime/client" } +substrate-test-runtime-transaction-pool = { path = "substrate/test-utils/runtime/transaction-pool" } +substrate-test-utils = { path = "substrate/test-utils" } +substrate-wasm-builder = { path = "substrate/utils/wasm-builder", default-features = false } syn = { version = "2.0.53" } +sysinfo = { version = "0.30" } +tar = { version = "0.4" } +tempfile = { version = "3.8.1" } +test-log = { version = "0.2.14" } +test-pallet = { path = "substrate/frame/support/test/pallet", default-features = false, package = "frame-support-test-pallet" } +test-parachain-adder = { path = "polkadot/parachain/test-parachains/adder" } +test-parachain-halt = { path = "polkadot/parachain/test-parachains/halt" } +test-parachain-undying = { path = "polkadot/parachain/test-parachains/undying" } +test-runtime-constants = { path = "polkadot/runtime/test-runtime/constants", default-features = false } +testnet-parachains-constants = { path = "cumulus/parachains/runtimes/constants", default-features = false } thiserror = { version = "1.0.48" } +thousands = { version = "0.2.0" } +threadpool = { version = "1.7" } +tikv-jemalloc-ctl = { version = "0.5.0" } +tikv-jemallocator = { version = "0.5.0" } +time = { version = "0.3" } +tiny-keccak = { version = "2.0.2" } +tokio = { version = "1.37.0", default-features = false } +tokio-retry = { version = "0.3.0" } +tokio-stream = { version = "0.1.14" } +tokio-test = { version = "0.4.2" } +tokio-tungstenite = { version = "0.20.1" } +tokio-util = { version = "0.7.8" } +toml = { version = "0.8.8" } +toml_edit = { version = "0.19" } +tower = { version = "0.4.13" } +tower-http = { version = "0.5.2" } +tracing = { version = "0.1.37", default-features = false } +tracing-core = { version = "0.1.32", default-features = false } +tracing-futures = { version = "0.2.4" } +tracing-log = { version = "0.2.0" } tracing-subscriber = { version = "0.3.18" } +tracking-allocator = { path = "polkadot/node/tracking-allocator", default-features = false, package = "staging-tracking-allocator" } +trie-bench = { version = "0.39.0" } +trie-db = { version = "0.29.0", default-features = false } +trie-root = { version = "0.18.0", default-features = false } +trie-standardmap = { version = "0.16.0" } +trybuild = { version = "1.0.88" } +tt-call = { version = "1.0.8" } +tuplex = { version = "0.1", default-features = false } +twox-hash = { version = "1.6.3", default-features = false } +unsigned-varint = { version = "0.7.2" } +url = { version = "2.4.0" } +void = { version = "1.0.2" } +w3f-bls = { version = "0.1.3", default-features = false } +wait-timeout = { version = "0.2" } +walkdir = { version = "2.4.0" } +wasm-bindgen-test = { version = "0.3.19" } +wasm-instrument = { version = "0.4", default-features = false } +wasm-opt = { version = "0.116" } +wasm-timer = { version = "0.2.5" } +wasmi = { version = "0.32.3", default-features = false } +wasmtime = { version = "8.0.1", default-features = false } +wat = { version = "1.0.0" } +westend-emulated-chain = { path = "cumulus/parachains/integration-tests/emulated/chains/relays/westend", default-features = false } +westend-runtime = { path = "polkadot/runtime/westend" } +westend-runtime-constants = { path = "polkadot/runtime/westend/constants", default-features = false } +westend-system-emulated-network = { path = "cumulus/parachains/integration-tests/emulated/networks/westend-system" } +x25519-dalek = { version = "2.0" } +xcm = { path = "polkadot/xcm", default-features = false, package = "staging-xcm" } +xcm-builder = { path = "polkadot/xcm/xcm-builder", default-features = false, package = "staging-xcm-builder" } +xcm-docs = { path = "polkadot/xcm/docs" } +xcm-emulator = { path = "cumulus/xcm/xcm-emulator", default-features = false } +xcm-executor = { path = "polkadot/xcm/xcm-executor", default-features = false, package = "staging-xcm-executor" } +xcm-procedural = { path = "polkadot/xcm/procedural", default-features = false } +xcm-runtime-apis = { path = "polkadot/xcm/xcm-runtime-apis", default-features = false } +xcm-simulator = { path = "polkadot/xcm/xcm-simulator", default-features = false } +zeroize = { version = "1.7.0", default-features = false } +zstd = { version = "0.12.4", default-features = false } [profile.release] # Polkadot runtime requires unwinding. diff --git a/README.md b/README.md index 50972da058afed21167361b13c98254639eed07a..92901d070db0854dd4b1daef8c3ed7a3fd3893f2 100644 --- a/README.md +++ b/README.md @@ -24,8 +24,12 @@ forks](https://img.shields.io/github/forks/paritytech/polkadot-sdk) ## ๐Ÿ“š Documentation * [๐Ÿฆ€ rust-docs](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/index.html) - * [Introduction](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/index.html) - to each component of the Polkadot SDK: Substrate, FRAME, Cumulus, and XCM + * [Introduction](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/index.html) + to each component of the Polkadot SDK: Substrate, FRAME, Cumulus, and XCM + * [Guides](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/guides/index.html), + namely how to build your first FRAME pallet. + * [Templates](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/templates/index.html) + for starting a new project. * Other Resources: * [Polkadot Wiki -> Build](https://wiki.polkadot.network/docs/build-guide) @@ -39,6 +43,9 @@ The Polkadot-SDK has two release channels: `stable` and `nightly`. Production so only use `stable`. `nightly` is meant for tinkerers to try out the latest features. The detailed release process is described in [RELEASE.md](docs/RELEASE.md). +You can use [`psvm`](https://github.com/paritytech/psvm) to manage your Polkadot-SDK dependency +versions in downstream projects. + ### ๐Ÿ˜Œ Stable `stable` releases have a support duration of **three months**. In this period, the release will not @@ -50,6 +57,12 @@ non-breaking features on a **two week** cadence. `nightly` releases are released every night from the `master` branch, potentially with breaking changes. They have pre-release version numbers in the format `major.0.0-nightlyYYMMDD`. +## ๐Ÿ› ๏ธ Tooling + +[Polkadot SDK Version Manager](https://github.com/paritytech/psvm): +A simple tool to manage and update the Polkadot SDK dependencies in any Cargo.toml file. +It will automatically update the Polkadot SDK dependencies to their correct crates.io version. + ## ๐Ÿ” Security The security policy and procedures can be found in @@ -81,7 +94,3 @@ fellowship, this separation, the RFC process This repository is the amalgamation of 3 separate repositories that used to make up Polkadot SDK, namely Substrate, Polkadot and Cumulus. Read more about the merge and its history [here](https://polkadot-public.notion.site/Polkadot-SDK-FAQ-fbc4cecc2c46443fb37b9eeec2f0d85f). - -## Other useful resources and tooling - -* A simple tool to manage and update the Polkadot SDK dependencies (https://github.com/paritytech/psvm) diff --git a/bridges/bin/runtime-common/Cargo.toml b/bridges/bin/runtime-common/Cargo.toml index 783009a8c890768bcc85dafec14dc3da9e8da573..d69a064aab81a41c946b073f232ebb8c778b9609 100644 --- a/bridges/bin/runtime-common/Cargo.toml +++ b/bridges/bin/runtime-common/Cargo.toml @@ -11,48 +11,48 @@ license = "GPL-3.0-or-later WITH Classpath-exception-2.0" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -hash-db = { version = "0.16.0", default-features = false } +codec = { features = ["derive"], workspace = true } +hash-db = { workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -static_assertions = { version = "1.1", optional = true } -tuplex = { version = "0.1", default-features = false } +scale-info = { features = ["derive"], workspace = true } +static_assertions = { optional = true, workspace = true, default-features = true } +tuplex = { workspace = true } # Bridge dependencies -bp-header-chain = { path = "../../primitives/header-chain", default-features = false } -bp-messages = { path = "../../primitives/messages", default-features = false } -bp-parachains = { path = "../../primitives/parachains", default-features = false } -bp-polkadot-core = { path = "../../primitives/polkadot-core", default-features = false } -bp-relayers = { path = "../../primitives/relayers", default-features = false } -bp-runtime = { path = "../../primitives/runtime", default-features = false } -bp-xcm-bridge-hub = { path = "../../primitives/xcm-bridge-hub", default-features = false } -bp-xcm-bridge-hub-router = { path = "../../primitives/xcm-bridge-hub-router", default-features = false } -pallet-bridge-grandpa = { path = "../../modules/grandpa", default-features = false } -pallet-bridge-messages = { path = "../../modules/messages", default-features = false } -pallet-bridge-parachains = { path = "../../modules/parachains", default-features = false } -pallet-bridge-relayers = { path = "../../modules/relayers", default-features = false } +bp-header-chain = { workspace = true } +bp-messages = { workspace = true } +bp-parachains = { workspace = true } +bp-polkadot-core = { workspace = true } +bp-relayers = { workspace = true } +bp-runtime = { workspace = true } +bp-xcm-bridge-hub = { workspace = true } +bp-xcm-bridge-hub-router = { workspace = true } +pallet-bridge-grandpa = { workspace = true } +pallet-bridge-messages = { workspace = true } +pallet-bridge-parachains = { workspace = true } +pallet-bridge-relayers = { workspace = true } # Substrate dependencies -frame-support = { path = "../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -pallet-transaction-payment = { path = "../../../substrate/frame/transaction-payment", default-features = false } -pallet-utility = { path = "../../../substrate/frame/utility", default-features = false } -sp-api = { path = "../../../substrate/primitives/api", default-features = false } -sp-core = { path = "../../../substrate/primitives/core", default-features = false } -sp-io = { path = "../../../substrate/primitives/io", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } -sp-trie = { path = "../../../substrate/primitives/trie", default-features = false } +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 } # Polkadot dependencies -xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../polkadot/xcm/xcm-builder", default-features = false } +xcm = { workspace = true } +xcm-builder = { workspace = true } [dev-dependencies] -bp-test-utils = { path = "../../primitives/test-utils" } -pallet-balances = { path = "../../../substrate/frame/balances" } +bp-test-utils = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/bridges/bin/runtime-common/src/extensions/check_obsolete_extension.rs b/bridges/bin/runtime-common/src/extensions/check_obsolete_extension.rs index 2c152aef68226aee36e791a882b5859427a9a33d..df75092af6e8b89fb76003cf0bfff508214ea825 100644 --- a/bridges/bin/runtime-common/src/extensions/check_obsolete_extension.rs +++ b/bridges/bin/runtime-common/src/extensions/check_obsolete_extension.rs @@ -36,6 +36,12 @@ use sp_runtime::{ transaction_validity::{TransactionPriority, TransactionValidity, ValidTransactionBuilder}, }; +// Re-export to avoid include tuplex dependency everywhere. +#[doc(hidden)] +pub mod __private { + pub use tuplex; +} + /// A duplication of the `FilterCall` trait. /// /// We need this trait in order to be able to implement it for the messages pallet, @@ -313,7 +319,7 @@ macro_rules! generate_bridge_reject_obsolete_headers_and_messages { info: &sp_runtime::traits::DispatchInfoOf, len: usize, ) -> Result { - use tuplex::PushBack; + use $crate::extensions::check_obsolete_extension::__private::tuplex::PushBack; let to_post_dispatch = (); $( let (from_validate, call_filter_validity) = < @@ -336,7 +342,7 @@ macro_rules! generate_bridge_reject_obsolete_headers_and_messages { len: usize, result: &sp_runtime::DispatchResult, ) -> Result<(), sp_runtime::transaction_validity::TransactionValidityError> { - use tuplex::PopFront; + use $crate::extensions::check_obsolete_extension::__private::tuplex::PopFront; let Some((relayer, to_post_dispatch)) = to_post_dispatch else { return Ok(()) }; let has_failed = result.is_err(); $( diff --git a/bridges/chains/chain-asset-hub-rococo/Cargo.toml b/bridges/chains/chain-asset-hub-rococo/Cargo.toml index d9afe2c8bf76713104beead1ad4c36dc08dae1ed..b765fbc57bb0aec2eb4544a01dd84c057ced16ef 100644 --- a/bridges/chains/chain-asset-hub-rococo/Cargo.toml +++ b/bridges/chains/chain-asset-hub-rococo/Cargo.toml @@ -11,14 +11,14 @@ repository.workspace = true workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { workspace = true } +scale-info = { features = ["derive"], workspace = true } # Substrate Dependencies -frame-support = { path = "../../../substrate/frame/support", default-features = false } +frame-support = { workspace = true } # Bridge Dependencies -bp-xcm-bridge-hub-router = { path = "../../primitives/xcm-bridge-hub-router", default-features = false } +bp-xcm-bridge-hub-router = { workspace = true } [features] default = ["std"] diff --git a/bridges/chains/chain-asset-hub-westend/Cargo.toml b/bridges/chains/chain-asset-hub-westend/Cargo.toml index 4b3ed052f1382d0c7f076ad5152c861f60d8bef1..ff89864fb2db4667d7929ef540ad4ec46cf2a36c 100644 --- a/bridges/chains/chain-asset-hub-westend/Cargo.toml +++ b/bridges/chains/chain-asset-hub-westend/Cargo.toml @@ -11,14 +11,14 @@ repository.workspace = true workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { workspace = true } +scale-info = { features = ["derive"], workspace = true } # Substrate Dependencies -frame-support = { path = "../../../substrate/frame/support", default-features = false } +frame-support = { workspace = true } # Bridge Dependencies -bp-xcm-bridge-hub-router = { path = "../../primitives/xcm-bridge-hub-router", default-features = false } +bp-xcm-bridge-hub-router = { workspace = true } [features] default = ["std"] diff --git a/bridges/chains/chain-bridge-hub-cumulus/Cargo.toml b/bridges/chains/chain-bridge-hub-cumulus/Cargo.toml index 4b900002a4d81abb9d7364f555a150a2af6c839c..5609398385f98b9d3731b196a057e939b1c099de 100644 --- a/bridges/chains/chain-bridge-hub-cumulus/Cargo.toml +++ b/bridges/chains/chain-bridge-hub-cumulus/Cargo.toml @@ -13,19 +13,19 @@ workspace = true [dependencies] # Bridge Dependencies -bp-polkadot-core = { path = "../../primitives/polkadot-core", default-features = false } -bp-messages = { path = "../../primitives/messages", default-features = false } -bp-runtime = { path = "../../primitives/runtime", default-features = false } +bp-polkadot-core = { workspace = true } +bp-messages = { workspace = true } +bp-runtime = { workspace = true } # Substrate Based Dependencies -frame-system = { path = "../../../substrate/frame/system", default-features = false } -frame-support = { path = "../../../substrate/frame/support", default-features = false } -sp-api = { path = "../../../substrate/primitives/api", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +frame-system = { workspace = true } +frame-support = { workspace = true } +sp-api = { workspace = true } +sp-std = { workspace = true } # Polkadot Dependencies -polkadot-primitives = { path = "../../../polkadot/primitives", default-features = false } +polkadot-primitives = { workspace = true } [features] default = ["std"] diff --git a/bridges/chains/chain-bridge-hub-kusama/Cargo.toml b/bridges/chains/chain-bridge-hub-kusama/Cargo.toml index ff6dd8849abe3897f1c3eb3cb1de8b7d89af5ca7..605643b0a4eb7e5d514edb1d4f1ad9db65a2c8ec 100644 --- a/bridges/chains/chain-bridge-hub-kusama/Cargo.toml +++ b/bridges/chains/chain-bridge-hub-kusama/Cargo.toml @@ -13,16 +13,16 @@ workspace = true [dependencies] # Bridge Dependencies -bp-bridge-hub-cumulus = { path = "../chain-bridge-hub-cumulus", default-features = false } -bp-runtime = { path = "../../primitives/runtime", default-features = false } -bp-messages = { path = "../../primitives/messages", default-features = false } +bp-bridge-hub-cumulus = { workspace = true } +bp-runtime = { workspace = true } +bp-messages = { workspace = true } # Substrate Based Dependencies -frame-support = { path = "../../../substrate/frame/support", default-features = false } -sp-api = { path = "../../../substrate/primitives/api", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +frame-support = { workspace = true } +sp-api = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [features] default = ["std"] diff --git a/bridges/chains/chain-bridge-hub-polkadot/Cargo.toml b/bridges/chains/chain-bridge-hub-polkadot/Cargo.toml index da8b8a82fa702eeab719335fa9968b78ee965163..97e36a19c748c0e5da990eda75bdbed9aa444e6f 100644 --- a/bridges/chains/chain-bridge-hub-polkadot/Cargo.toml +++ b/bridges/chains/chain-bridge-hub-polkadot/Cargo.toml @@ -14,16 +14,16 @@ workspace = true # Bridge Dependencies -bp-bridge-hub-cumulus = { path = "../chain-bridge-hub-cumulus", default-features = false } -bp-runtime = { path = "../../primitives/runtime", default-features = false } -bp-messages = { path = "../../primitives/messages", default-features = false } +bp-bridge-hub-cumulus = { workspace = true } +bp-runtime = { workspace = true } +bp-messages = { workspace = true } # Substrate Based Dependencies -frame-support = { path = "../../../substrate/frame/support", default-features = false } -sp-api = { path = "../../../substrate/primitives/api", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +frame-support = { workspace = true } +sp-api = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [features] default = ["std"] diff --git a/bridges/chains/chain-bridge-hub-rococo/Cargo.toml b/bridges/chains/chain-bridge-hub-rococo/Cargo.toml index f7672df012f2fc2a21cfc987468427a3222317ea..5c918470322353c32556c3e5d381fb2ea713b2ab 100644 --- a/bridges/chains/chain-bridge-hub-rococo/Cargo.toml +++ b/bridges/chains/chain-bridge-hub-rococo/Cargo.toml @@ -13,16 +13,16 @@ workspace = true [dependencies] # Bridge Dependencies -bp-bridge-hub-cumulus = { path = "../chain-bridge-hub-cumulus", default-features = false } -bp-runtime = { path = "../../primitives/runtime", default-features = false } -bp-messages = { path = "../../primitives/messages", default-features = false } +bp-bridge-hub-cumulus = { workspace = true } +bp-runtime = { workspace = true } +bp-messages = { workspace = true } # Substrate Based Dependencies -frame-support = { path = "../../../substrate/frame/support", default-features = false } -sp-api = { path = "../../../substrate/primitives/api", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +frame-support = { workspace = true } +sp-api = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [features] default = ["std"] diff --git a/bridges/chains/chain-bridge-hub-westend/Cargo.toml b/bridges/chains/chain-bridge-hub-westend/Cargo.toml index ec74c4b947d693dba92d4da5051526e49349e0a5..0b429ab9a0bd9793a9129ed8483a608f71bfb44c 100644 --- a/bridges/chains/chain-bridge-hub-westend/Cargo.toml +++ b/bridges/chains/chain-bridge-hub-westend/Cargo.toml @@ -14,16 +14,16 @@ workspace = true # Bridge Dependencies -bp-bridge-hub-cumulus = { path = "../chain-bridge-hub-cumulus", default-features = false } -bp-runtime = { path = "../../primitives/runtime", default-features = false } -bp-messages = { path = "../../primitives/messages", default-features = false } +bp-bridge-hub-cumulus = { workspace = true } +bp-runtime = { workspace = true } +bp-messages = { workspace = true } # Substrate Based Dependencies -frame-support = { path = "../../../substrate/frame/support", default-features = false } -sp-api = { path = "../../../substrate/primitives/api", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +frame-support = { workspace = true } +sp-api = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [features] default = ["std"] diff --git a/bridges/chains/chain-kusama/Cargo.toml b/bridges/chains/chain-kusama/Cargo.toml index 66061ff2793cbdd3419fa8894ab78e37486102ea..ec45c1eddce5d3b7be1f3a8ae9b83ca6332e7c28 100644 --- a/bridges/chains/chain-kusama/Cargo.toml +++ b/bridges/chains/chain-kusama/Cargo.toml @@ -14,15 +14,15 @@ workspace = true # Bridge Dependencies -bp-header-chain = { path = "../../primitives/header-chain", default-features = false } -bp-polkadot-core = { path = "../../primitives/polkadot-core", default-features = false } -bp-runtime = { path = "../../primitives/runtime", default-features = false } +bp-header-chain = { workspace = true } +bp-polkadot-core = { workspace = true } +bp-runtime = { workspace = true } # Substrate Based Dependencies -frame-support = { path = "../../../substrate/frame/support", default-features = false } -sp-api = { path = "../../../substrate/primitives/api", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +frame-support = { workspace = true } +sp-api = { workspace = true } +sp-std = { workspace = true } [features] default = ["std"] diff --git a/bridges/chains/chain-polkadot-bulletin/Cargo.toml b/bridges/chains/chain-polkadot-bulletin/Cargo.toml index 700247b7055a891bec2d4a40bfd126720a0d952c..ea5f4d2e77591bd8840e869f9b3567df5d56fd56 100644 --- a/bridges/chains/chain-polkadot-bulletin/Cargo.toml +++ b/bridges/chains/chain-polkadot-bulletin/Cargo.toml @@ -11,23 +11,23 @@ repository.workspace = true workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } # Bridge Dependencies -bp-header-chain = { path = "../../primitives/header-chain", default-features = false } -bp-messages = { path = "../../primitives/messages", default-features = false } -bp-polkadot-core = { path = "../../primitives/polkadot-core", default-features = false } -bp-runtime = { path = "../../primitives/runtime", default-features = false } +bp-header-chain = { workspace = true } +bp-messages = { workspace = true } +bp-polkadot-core = { workspace = true } +bp-runtime = { workspace = true } # Substrate Based Dependencies -frame-support = { path = "../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -sp-api = { path = "../../../substrate/primitives/api", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-api = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [features] default = ["std"] diff --git a/bridges/chains/chain-polkadot/Cargo.toml b/bridges/chains/chain-polkadot/Cargo.toml index c700935f3083b5f287277c7d9975be53352b2506..50f637af4251c8a7ed822861281a217ec12bdb28 100644 --- a/bridges/chains/chain-polkadot/Cargo.toml +++ b/bridges/chains/chain-polkadot/Cargo.toml @@ -14,15 +14,15 @@ workspace = true # Bridge Dependencies -bp-header-chain = { path = "../../primitives/header-chain", default-features = false } -bp-polkadot-core = { path = "../../primitives/polkadot-core", default-features = false } -bp-runtime = { path = "../../primitives/runtime", default-features = false } +bp-header-chain = { workspace = true } +bp-polkadot-core = { workspace = true } +bp-runtime = { workspace = true } # Substrate Based Dependencies -frame-support = { path = "../../../substrate/frame/support", default-features = false } -sp-api = { path = "../../../substrate/primitives/api", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +frame-support = { workspace = true } +sp-api = { workspace = true } +sp-std = { workspace = true } [features] default = ["std"] diff --git a/bridges/chains/chain-rococo/Cargo.toml b/bridges/chains/chain-rococo/Cargo.toml index 5a5613bb376a5a4f75c773b3350993262149f973..49a1a397ee096532cfc0b5d3a42cf14469f8ed46 100644 --- a/bridges/chains/chain-rococo/Cargo.toml +++ b/bridges/chains/chain-rococo/Cargo.toml @@ -14,15 +14,15 @@ workspace = true # Bridge Dependencies -bp-header-chain = { path = "../../primitives/header-chain", default-features = false } -bp-polkadot-core = { path = "../../primitives/polkadot-core", default-features = false } -bp-runtime = { path = "../../primitives/runtime", default-features = false } +bp-header-chain = { workspace = true } +bp-polkadot-core = { workspace = true } +bp-runtime = { workspace = true } # Substrate Based Dependencies -frame-support = { path = "../../../substrate/frame/support", default-features = false } -sp-api = { path = "../../../substrate/primitives/api", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +frame-support = { workspace = true } +sp-api = { workspace = true } +sp-std = { workspace = true } [features] default = ["std"] diff --git a/bridges/chains/chain-westend/Cargo.toml b/bridges/chains/chain-westend/Cargo.toml index 10b06d76507ef95bbff00f5560b705ecee1ec4ce..5e27bc647bfc5f07d5ab029307ef6dcf67121fb3 100644 --- a/bridges/chains/chain-westend/Cargo.toml +++ b/bridges/chains/chain-westend/Cargo.toml @@ -14,15 +14,15 @@ workspace = true # Bridge Dependencies -bp-header-chain = { path = "../../primitives/header-chain", default-features = false } -bp-polkadot-core = { path = "../../primitives/polkadot-core", default-features = false } -bp-runtime = { path = "../../primitives/runtime", default-features = false } +bp-header-chain = { workspace = true } +bp-polkadot-core = { workspace = true } +bp-runtime = { workspace = true } # Substrate Based Dependencies -frame-support = { path = "../../../substrate/frame/support", default-features = false } -sp-api = { path = "../../../substrate/primitives/api", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +frame-support = { workspace = true } +sp-api = { workspace = true } +sp-std = { workspace = true } [features] default = ["std"] diff --git a/bridges/modules/beefy/Cargo.toml b/bridges/modules/beefy/Cargo.toml index e36bbb615f23a20d4ef4a4f4ea8418e752d5b01f..cffc62d290828f032c5c57f27982e7f60f9b94ef 100644 --- a/bridges/modules/beefy/Cargo.toml +++ b/bridges/modules/beefy/Cargo.toml @@ -12,32 +12,32 @@ publish = false workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } +codec = { workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } serde = { optional = true, workspace = true } # Bridge Dependencies -bp-beefy = { path = "../../primitives/beefy", default-features = false } -bp-runtime = { path = "../../primitives/runtime", default-features = false } +bp-beefy = { workspace = true } +bp-runtime = { workspace = true } # Substrate Dependencies -frame-support = { path = "../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -sp-core = { path = "../../../substrate/primitives/core", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-core = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -sp-consensus-beefy = { path = "../../../substrate/primitives/consensus/beefy" } -mmr-lib = { package = "ckb-merkle-mountain-range", version = "0.5.2" } -pallet-beefy-mmr = { path = "../../../substrate/frame/beefy-mmr" } -pallet-mmr = { path = "../../../substrate/frame/merkle-mountain-range" } -rand = "0.8.5" -sp-io = { path = "../../../substrate/primitives/io" } -bp-test-utils = { path = "../../primitives/test-utils" } +sp-consensus-beefy = { workspace = true, default-features = true } +mmr-lib = { workspace = true } +pallet-beefy-mmr = { workspace = true, default-features = true } +pallet-mmr = { workspace = true, default-features = true } +rand = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +bp-test-utils = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/bridges/modules/grandpa/Cargo.toml b/bridges/modules/grandpa/Cargo.toml index 0ca6b67503511976ea9122f64e3c2e515e971177..307c7ddaaffd963e89f7b2faa7a487ce5db0dcca 100644 --- a/bridges/modules/grandpa/Cargo.toml +++ b/bridges/modules/grandpa/Cargo.toml @@ -13,32 +13,32 @@ workspace = true # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -finality-grandpa = { version = "0.16.2", default-features = false } +codec = { workspace = true } +finality-grandpa = { workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } # Bridge Dependencies -bp-runtime = { path = "../../primitives/runtime", default-features = false } -bp-header-chain = { path = "../../primitives/header-chain", default-features = false } +bp-runtime = { workspace = true } +bp-header-chain = { workspace = true } # Substrate Dependencies -frame-support = { path = "../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -sp-consensus-grandpa = { path = "../../../substrate/primitives/consensus/grandpa", default-features = false, features = ["serde"] } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false, features = ["serde"] } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } -sp-trie = { path = "../../../substrate/primitives/trie", default-features = false } +frame-support = { workspace = true } +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 = { path = "../../primitives/test-utils", default-features = false, optional = true } -frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-features = false, optional = true } +bp-test-utils = { optional = true, workspace = true } +frame-benchmarking = { optional = true, workspace = true } [dev-dependencies] -sp-core = { path = "../../../substrate/primitives/core" } -sp-io = { path = "../../../substrate/primitives/io" } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/bridges/modules/messages/Cargo.toml b/bridges/modules/messages/Cargo.toml index 71c86ccc0361708684d0a93166f858118dbf0d92..573d0ba47668cfd5513def1a2465be10002c676f 100644 --- a/bridges/modules/messages/Cargo.toml +++ b/bridges/modules/messages/Cargo.toml @@ -11,28 +11,28 @@ repository.workspace = true workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } +codec = { workspace = true } log = { workspace = true } -num-traits = { version = "0.2", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +num-traits = { workspace = true } +scale-info = { features = ["derive"], workspace = true } # Bridge dependencies -bp-messages = { path = "../../primitives/messages", default-features = false } -bp-runtime = { path = "../../primitives/runtime", default-features = false } +bp-messages = { workspace = true } +bp-runtime = { workspace = true } # Substrate Dependencies -frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-support = { path = "../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -bp-test-utils = { path = "../../primitives/test-utils" } -pallet-balances = { path = "../../../substrate/frame/balances" } -sp-io = { path = "../../../substrate/primitives/io" } +bp-test-utils = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/bridges/modules/messages/src/mock.rs b/bridges/modules/messages/src/mock.rs index ec63f15b94b5205d744b1379bd6697a4ae43534a..3a1e0063d5337769b75b35035116aaff6e2b2e08 100644 --- a/bridges/modules/messages/src/mock.rs +++ b/bridges/modules/messages/src/mock.rs @@ -86,7 +86,6 @@ impl frame_system::Config for TestRuntime { #[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for TestRuntime { - type ReserveIdentifier = [u8; 8]; type AccountStore = System; } diff --git a/bridges/modules/parachains/Cargo.toml b/bridges/modules/parachains/Cargo.toml index d3152f8d0a4aa9b6dc1c726441c5e139e08de162..97bad724a789ea0cdf0f0c972b153606fc302e7f 100644 --- a/bridges/modules/parachains/Cargo.toml +++ b/bridges/modules/parachains/Cargo.toml @@ -11,32 +11,32 @@ repository.workspace = true workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } +codec = { workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } # Bridge Dependencies -bp-header-chain = { path = "../../primitives/header-chain", default-features = false } -bp-parachains = { path = "../../primitives/parachains", default-features = false } -bp-polkadot-core = { path = "../../primitives/polkadot-core", default-features = false } -bp-runtime = { path = "../../primitives/runtime", default-features = false } -pallet-bridge-grandpa = { path = "../grandpa", default-features = false } +bp-header-chain = { workspace = true } +bp-parachains = { workspace = true } +bp-polkadot-core = { workspace = true } +bp-runtime = { workspace = true } +pallet-bridge-grandpa = { workspace = true } # Substrate Dependencies -frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-support = { path = "../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } -sp-trie = { path = "../../../substrate/primitives/trie", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +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 = { path = "../../primitives/header-chain" } -bp-test-utils = { path = "../../primitives/test-utils" } -sp-core = { path = "../../../substrate/primitives/core" } -sp-io = { path = "../../../substrate/primitives/io" } +bp-header-chain = { workspace = true, default-features = true } +bp-test-utils = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/bridges/modules/relayers/Cargo.toml b/bridges/modules/relayers/Cargo.toml index 08e1438d4f1946fb41f614b0e94c0ce6f1611fd5..27a28546afb482851040cbe16bd40071e86a70cb 100644 --- a/bridges/modules/relayers/Cargo.toml +++ b/bridges/modules/relayers/Cargo.toml @@ -11,31 +11,31 @@ repository.workspace = true workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } +codec = { workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } # Bridge dependencies -bp-messages = { path = "../../primitives/messages", default-features = false } -bp-relayers = { path = "../../primitives/relayers", default-features = false } -bp-runtime = { path = "../../primitives/runtime", default-features = false } -pallet-bridge-messages = { path = "../messages", default-features = false } +bp-messages = { workspace = true } +bp-relayers = { workspace = true } +bp-runtime = { workspace = true } +pallet-bridge-messages = { workspace = true } # Substrate Dependencies -frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-support = { path = "../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -sp-arithmetic = { path = "../../../substrate/primitives/arithmetic", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-arithmetic = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -bp-runtime = { path = "../../primitives/runtime" } -pallet-balances = { path = "../../../substrate/frame/balances" } -sp-io = { path = "../../../substrate/primitives/io" } -sp-runtime = { path = "../../../substrate/primitives/runtime" } +bp-runtime = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/bridges/modules/relayers/src/lib.rs b/bridges/modules/relayers/src/lib.rs index 7a3a0f9ea94cbe5768bf6ee8c850355193ea44f0..2c86ec01f5b915bc3b3b1e65c15adae7c45e1819 100644 --- a/bridges/modules/relayers/src/lib.rs +++ b/bridges/modules/relayers/src/lib.rs @@ -63,7 +63,7 @@ pub mod pallet { /// The overarching event type. type RuntimeEvent: From> + IsType<::RuntimeEvent>; /// Type of relayer reward. - type Reward: AtLeast32BitUnsigned + Copy + Parameter + MaxEncodedLen; + type Reward: AtLeast32BitUnsigned + Copy + Member + Parameter + MaxEncodedLen; /// Pay rewards scheme. type PaymentProcedure: PaymentProcedure; /// Stake and slash scheme. diff --git a/bridges/modules/xcm-bridge-hub-router/Cargo.toml b/bridges/modules/xcm-bridge-hub-router/Cargo.toml index b80240c974de9f5874e2825f5506885fea11ef3a..ec7c3b5628327f6cbb3d5b3920dba59521c6c209 100644 --- a/bridges/modules/xcm-bridge-hub-router/Cargo.toml +++ b/bridges/modules/xcm-bridge-hub-router/Cargo.toml @@ -11,31 +11,31 @@ repository.workspace = true workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } +codec = { workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["bit-vec", "derive", "serde"] } +scale-info = { features = ["bit-vec", "derive", "serde"], workspace = true } # Bridge dependencies -bp-xcm-bridge-hub-router = { path = "../../primitives/xcm-bridge-hub-router", default-features = false } +bp-xcm-bridge-hub-router = { workspace = true } # Substrate Dependencies -frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-support = { path = "../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -sp-core = { path = "../../../substrate/primitives/core", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-core = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } # Polkadot Dependencies -xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../polkadot/xcm/xcm-builder", default-features = false } +xcm = { workspace = true } +xcm-builder = { workspace = true } [dev-dependencies] -sp-io = { path = "../../../substrate/primitives/io" } -sp-std = { path = "../../../substrate/primitives/std" } +sp-io = { workspace = true, default-features = true } +sp-std = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/bridges/modules/xcm-bridge-hub/Cargo.toml b/bridges/modules/xcm-bridge-hub/Cargo.toml index 9b22770061a9a9ffd981f186de9231d7ff41cde9..092df477265fc0933180feaf355f174ca433df6f 100644 --- a/bridges/modules/xcm-bridge-hub/Cargo.toml +++ b/bridges/modules/xcm-bridge-hub/Cargo.toml @@ -11,33 +11,33 @@ repository.workspace = true workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } +codec = { workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } # Bridge Dependencies -bp-messages = { path = "../../primitives/messages", default-features = false } -bp-runtime = { path = "../../primitives/runtime", default-features = false } -bp-xcm-bridge-hub = { path = "../../primitives/xcm-bridge-hub", default-features = false } -pallet-bridge-messages = { path = "../messages", default-features = false } -bridge-runtime-common = { path = "../../bin/runtime-common", default-features = false } +bp-messages = { workspace = true } +bp-runtime = { workspace = true } +bp-xcm-bridge-hub = { workspace = true } +pallet-bridge-messages = { workspace = true } +bridge-runtime-common = { workspace = true } # Substrate Dependencies -frame-support = { path = "../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -sp-core = { path = "../../../substrate/primitives/core", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-core = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } # Polkadot Dependencies -xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../polkadot/xcm/xcm-builder", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../polkadot/xcm/xcm-executor", default-features = false } +xcm = { workspace = true } +xcm-builder = { workspace = true } +xcm-executor = { workspace = true } [dev-dependencies] -bp-header-chain = { path = "../../primitives/header-chain" } -pallet-balances = { path = "../../../substrate/frame/balances" } -sp-io = { path = "../../../substrate/primitives/io" } +bp-header-chain = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/bridges/primitives/beefy/Cargo.toml b/bridges/primitives/beefy/Cargo.toml index bd68076ca48fc8ccc7bb8f48611083c0930731f7..404acaff30af252f6e5c52d9b28e8ccc72d542ce 100644 --- a/bridges/primitives/beefy/Cargo.toml +++ b/bridges/primitives/beefy/Cargo.toml @@ -12,23 +12,23 @@ publish = false workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["bit-vec", "derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["bit-vec", "derive"] } -serde = { default-features = false, features = ["alloc", "derive"], workspace = true } +codec = { features = ["bit-vec", "derive"], workspace = true } +scale-info = { features = ["bit-vec", "derive"], workspace = true } +serde = { features = ["alloc", "derive"], workspace = true } # Bridge Dependencies -bp-runtime = { path = "../runtime", default-features = false } +bp-runtime = { workspace = true } # Substrate Dependencies -binary-merkle-tree = { path = "../../../substrate/utils/binary-merkle-tree", default-features = false } -sp-consensus-beefy = { path = "../../../substrate/primitives/consensus/beefy", default-features = false } -frame-support = { path = "../../../substrate/frame/support", default-features = false } -pallet-beefy-mmr = { path = "../../../substrate/frame/beefy-mmr", default-features = false } -pallet-mmr = { path = "../../../substrate/frame/merkle-mountain-range", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +binary-merkle-tree = { workspace = true } +sp-consensus-beefy = { workspace = true } +frame-support = { workspace = true } +pallet-beefy-mmr = { workspace = true } +pallet-mmr = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [features] default = ["std"] diff --git a/bridges/primitives/header-chain/Cargo.toml b/bridges/primitives/header-chain/Cargo.toml index def1f7ad4dfefb14c3f8459a3d2960c3890ddcf8..081bda479495f5bbd4599b4230d45f5c4e3c5e85 100644 --- a/bridges/primitives/header-chain/Cargo.toml +++ b/bridges/primitives/header-chain/Cargo.toml @@ -11,27 +11,27 @@ repository.workspace = true workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -finality-grandpa = { version = "0.16.2", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { workspace = true } +finality-grandpa = { workspace = true } +scale-info = { features = ["derive"], workspace = true } serde = { features = ["alloc", "derive"], workspace = true } # Bridge dependencies -bp-runtime = { path = "../runtime", default-features = false } +bp-runtime = { workspace = true } # Substrate Dependencies -frame-support = { path = "../../../substrate/frame/support", default-features = false } -sp-core = { path = "../../../substrate/primitives/core", default-features = false, features = ["serde"] } -sp-consensus-grandpa = { path = "../../../substrate/primitives/consensus/grandpa", default-features = false, features = ["serde"] } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false, features = ["serde"] } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +frame-support = { workspace = true } +sp-core = { features = ["serde"], workspace = true } +sp-consensus-grandpa = { features = ["serde"], workspace = true } +sp-runtime = { features = ["serde"], workspace = true } +sp-std = { workspace = true } [dev-dependencies] -bp-test-utils = { path = "../test-utils" } -hex = "0.4" -hex-literal = "0.4" +bp-test-utils = { workspace = true, default-features = true } +hex = { workspace = true, default-features = true } +hex-literal = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/bridges/primitives/messages/Cargo.toml b/bridges/primitives/messages/Cargo.toml index 20337873c2e6abac5872807adf67557be60a46e8..4a9037342bcea66d813cdb79969c4ff3172f0bab 100644 --- a/bridges/primitives/messages/Cargo.toml +++ b/bridges/primitives/messages/Cargo.toml @@ -11,24 +11,24 @@ repository.workspace = true workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["bit-vec", "derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["bit-vec", "derive"] } +codec = { features = ["bit-vec", "derive"], workspace = true } +scale-info = { features = ["bit-vec", "derive"], workspace = true } serde = { features = ["alloc", "derive"], workspace = true } # Bridge dependencies -bp-runtime = { path = "../runtime", default-features = false } -bp-header-chain = { path = "../header-chain", default-features = false } +bp-runtime = { workspace = true } +bp-header-chain = { workspace = true } # Substrate Dependencies -frame-support = { path = "../../../substrate/frame/support", default-features = false } -sp-core = { path = "../../../substrate/primitives/core", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +frame-support = { workspace = true } +sp-core = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -hex = "0.4" -hex-literal = "0.4" +hex = { workspace = true, default-features = true } +hex-literal = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/bridges/primitives/parachains/Cargo.toml b/bridges/primitives/parachains/Cargo.toml index a6e71876cefbb3963ef1923469d641281cda00dc..173380c8224d2855e2022cc6b6f9266fc8094ecd 100644 --- a/bridges/primitives/parachains/Cargo.toml +++ b/bridges/primitives/parachains/Cargo.toml @@ -11,22 +11,22 @@ repository.workspace = true workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -impl-trait-for-tuples = "0.2" -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +impl-trait-for-tuples = { workspace = true } +scale-info = { features = ["derive"], workspace = true } # Bridge dependencies -bp-header-chain = { path = "../header-chain", default-features = false } -bp-polkadot-core = { path = "../polkadot-core", default-features = false } -bp-runtime = { path = "../runtime", default-features = false } +bp-header-chain = { workspace = true } +bp-polkadot-core = { workspace = true } +bp-runtime = { workspace = true } # Substrate dependencies -frame-support = { path = "../../../substrate/frame/support", default-features = false } -sp-core = { path = "../../../substrate/primitives/core", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +frame-support = { workspace = true } +sp-core = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [features] default = ["std"] diff --git a/bridges/primitives/polkadot-core/Cargo.toml b/bridges/primitives/polkadot-core/Cargo.toml index d4b2f503e9e2ca92c095649f8aa36741d02c8037..acae2f431bf20aa8babf57e586cd4bb726fe2ec8 100644 --- a/bridges/primitives/polkadot-core/Cargo.toml +++ b/bridges/primitives/polkadot-core/Cargo.toml @@ -11,26 +11,26 @@ repository.workspace = true workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -parity-util-mem = { version = "0.12.0", optional = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +parity-util-mem = { optional = true, workspace = true } +scale-info = { features = ["derive"], workspace = true } serde = { optional = true, features = ["derive"], workspace = true, default-features = true } # Bridge Dependencies -bp-messages = { path = "../messages", default-features = false } -bp-runtime = { path = "../runtime", default-features = false } +bp-messages = { workspace = true } +bp-runtime = { workspace = true } # Substrate Based Dependencies -frame-support = { path = "../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -sp-core = { path = "../../../substrate/primitives/core", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-core = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -hex = "0.4" +hex = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/bridges/primitives/relayers/Cargo.toml b/bridges/primitives/relayers/Cargo.toml index 5081dddce1e61eccbae540f665257e122d777dd6..3448e8a4096339966023d0f5ddd0e158380ab12a 100644 --- a/bridges/primitives/relayers/Cargo.toml +++ b/bridges/primitives/relayers/Cargo.toml @@ -11,23 +11,23 @@ repository.workspace = true workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["bit-vec", "derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["bit-vec", "derive"] } +codec = { features = ["bit-vec", "derive"], workspace = true } +scale-info = { features = ["bit-vec", "derive"], workspace = true } # Bridge Dependencies -bp-messages = { path = "../messages", default-features = false } -bp-runtime = { path = "../runtime", default-features = false } +bp-messages = { workspace = true } +bp-runtime = { workspace = true } # Substrate Dependencies -frame-support = { path = "../../../substrate/frame/support", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +frame-support = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -hex = "0.4" -hex-literal = "0.4" +hex = { workspace = true, default-features = true } +hex-literal = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/bridges/primitives/relayers/src/lib.rs b/bridges/primitives/relayers/src/lib.rs index 2a9ef6a8e1e9aba999ea90045447f7a87fb3813b..436f33db4008013572592939b63c0e02e92b8e99 100644 --- a/bridges/primitives/relayers/src/lib.rs +++ b/bridges/primitives/relayers/src/lib.rs @@ -140,8 +140,8 @@ pub struct RelayerRewardsKeyProvider(PhantomData<(AccountId, impl StorageDoubleMapKeyProvider for RelayerRewardsKeyProvider where - AccountId: Codec + EncodeLike, - Reward: Codec + EncodeLike, + AccountId: 'static + Codec + EncodeLike + Send + Sync, + Reward: 'static + Codec + EncodeLike + Send + Sync, { const MAP_NAME: &'static str = "RelayerRewards"; diff --git a/bridges/primitives/runtime/Cargo.toml b/bridges/primitives/runtime/Cargo.toml index ac65ad538b4988c71e59d081cba46d47ebdc7c39..5fa35e688996f1c13ea7d94f0de5a3b9813d4574 100644 --- a/bridges/primitives/runtime/Cargo.toml +++ b/bridges/primitives/runtime/Cargo.toml @@ -11,28 +11,28 @@ repository.workspace = true workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -hash-db = { version = "0.16.0", default-features = false } -impl-trait-for-tuples = "0.2.2" +codec = { workspace = true } +hash-db = { workspace = true } +impl-trait-for-tuples = { workspace = true } log = { workspace = true } -num-traits = { version = "0.2", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +num-traits = { workspace = true } +scale-info = { features = ["derive"], workspace = true } serde = { features = ["alloc", "derive"], workspace = true } # Substrate Dependencies -frame-support = { path = "../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -sp-core = { path = "../../../substrate/primitives/core", default-features = false } -sp-io = { path = "../../../substrate/primitives/io", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false, features = ["serde"] } -sp-state-machine = { path = "../../../substrate/primitives/state-machine", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } -sp-trie = { path = "../../../substrate/primitives/trie", default-features = false } -trie-db = { version = "0.29.0", default-features = false } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-core = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { features = ["serde"], workspace = true } +sp-state-machine = { workspace = true } +sp-std = { workspace = true } +sp-trie = { workspace = true } +trie-db = { workspace = true } [dev-dependencies] -hex-literal = "0.4" +hex-literal = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/bridges/primitives/runtime/src/lib.rs b/bridges/primitives/runtime/src/lib.rs index 5daba0351ad48f0ae39b870990b6f5ccea1bec1e..d13c9b40efa0b4ddf1433fdc87ce59eb13c7d9a3 100644 --- a/bridges/primitives/runtime/src/lib.rs +++ b/bridges/primitives/runtime/src/lib.rs @@ -255,9 +255,9 @@ pub trait StorageMapKeyProvider { /// The same as `StorageMap::Hasher1`. type Hasher: StorageHasher; /// The same as `StorageMap::Key1`. - type Key: FullCodec; + type Key: FullCodec + Send + Sync; /// The same as `StorageMap::Value`. - type Value: FullCodec; + type Value: 'static + FullCodec; /// This is a copy of the /// `frame_support::storage::generator::StorageMap::storage_map_final_key`. @@ -277,13 +277,13 @@ pub trait StorageDoubleMapKeyProvider { /// The same as `StorageDoubleMap::Hasher1`. type Hasher1: StorageHasher; /// The same as `StorageDoubleMap::Key1`. - type Key1: FullCodec; + type Key1: FullCodec + Send + Sync; /// The same as `StorageDoubleMap::Hasher2`. type Hasher2: StorageHasher; /// The same as `StorageDoubleMap::Key2`. - type Key2: FullCodec; + type Key2: FullCodec + Send + Sync; /// The same as `StorageDoubleMap::Value`. - type Value: FullCodec; + type Value: 'static + FullCodec; /// This is a copy of the /// `frame_support::storage::generator::StorageDoubleMap::storage_double_map_final_key`. diff --git a/bridges/primitives/test-utils/Cargo.toml b/bridges/primitives/test-utils/Cargo.toml index 99f5ee0d1aee4528f64028bbb4ce089cfb6f4c44..0b7fb3fec077df6187ded588011cf99a64c588f0 100644 --- a/bridges/primitives/test-utils/Cargo.toml +++ b/bridges/primitives/test-utils/Cargo.toml @@ -11,19 +11,19 @@ repository.workspace = true workspace = true [dependencies] -bp-header-chain = { path = "../header-chain", default-features = false } -bp-parachains = { path = "../parachains", default-features = false } -bp-polkadot-core = { path = "../polkadot-core", default-features = false } -bp-runtime = { path = "../runtime", default-features = false } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -ed25519-dalek = { version = "2.1", default-features = false } -finality-grandpa = { version = "0.16.2", default-features = false } -sp-application-crypto = { path = "../../../substrate/primitives/application-crypto", default-features = false } -sp-consensus-grandpa = { path = "../../../substrate/primitives/consensus/grandpa", default-features = false } -sp-core = { path = "../../../substrate/primitives/core", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } -sp-trie = { path = "../../../substrate/primitives/trie", default-features = false } +bp-header-chain = { workspace = true } +bp-parachains = { workspace = true } +bp-polkadot-core = { workspace = true } +bp-runtime = { workspace = true } +codec = { workspace = true } +ed25519-dalek = { workspace = true } +finality-grandpa = { workspace = true } +sp-application-crypto = { workspace = true } +sp-consensus-grandpa = { workspace = true } +sp-core = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } +sp-trie = { workspace = true } [features] default = ["std"] diff --git a/bridges/primitives/xcm-bridge-hub-router/Cargo.toml b/bridges/primitives/xcm-bridge-hub-router/Cargo.toml index b94e722024562e526c33d2bf1efe9b89f1a035aa..c3cf3356184be676ffae0c212fc20455395d6d09 100644 --- a/bridges/primitives/xcm-bridge-hub-router/Cargo.toml +++ b/bridges/primitives/xcm-bridge-hub-router/Cargo.toml @@ -11,12 +11,12 @@ repository.workspace = true workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["bit-vec", "derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["bit-vec", "derive"] } +codec = { features = ["bit-vec", "derive"], workspace = true } +scale-info = { features = ["bit-vec", "derive"], workspace = true } # Substrate Dependencies -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-core = { path = "../../../substrate/primitives/core", default-features = false } +sp-runtime = { workspace = true } +sp-core = { workspace = true } [features] default = ["std"] diff --git a/bridges/primitives/xcm-bridge-hub/Cargo.toml b/bridges/primitives/xcm-bridge-hub/Cargo.toml index 27881bc99d1f838bb5a72c02fe565ef5dc0307fd..932e9ade019741dbc6a99fcea317aaee539ed9c9 100644 --- a/bridges/primitives/xcm-bridge-hub/Cargo.toml +++ b/bridges/primitives/xcm-bridge-hub/Cargo.toml @@ -13,7 +13,7 @@ workspace = true [dependencies] # Substrate Dependencies -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +sp-std = { workspace = true } [features] default = ["std"] diff --git a/bridges/relays/client-substrate/Cargo.toml b/bridges/relays/client-substrate/Cargo.toml index cb7eae4f340c7375ad69b111f6b561c84bc57144..66501d03691a949431c15060a398f1fd1c3cfa5f 100644 --- a/bridges/relays/client-substrate/Cargo.toml +++ b/bridges/relays/client-substrate/Cargo.toml @@ -11,50 +11,52 @@ publish = false workspace = true [dependencies] -async-std = { version = "1.9.0", features = ["attributes"] } -async-trait = "0.1.79" -codec = { package = "parity-scale-codec", version = "3.6.12" } -futures = "0.3.30" -jsonrpsee = { version = "0.22", features = ["macros", "ws-client"] } +async-std = { features = ["attributes"], workspace = true } +async-trait = { workspace = true } +codec = { workspace = true, default-features = true } +futures = { workspace = true } +jsonrpsee = { features = ["macros", "ws-client"], workspace = true } log = { workspace = true } -num-traits = "0.2" -rand = "0.8.5" -scale-info = { version = "2.11.1", features = ["derive"] } -tokio = { version = "1.37", features = ["rt-multi-thread"] } +num-traits = { workspace = true, default-features = true } +rand = { workspace = true, default-features = true } +serde_json = { workspace = true } +scale-info = { features = ["derive"], workspace = true, default-features = true } +tokio = { features = ["rt-multi-thread"], workspace = true, default-features = true } thiserror = { workspace = true } +quick_cache = { workspace = true } # Bridge dependencies -bp-header-chain = { path = "../../primitives/header-chain" } -bp-messages = { path = "../../primitives/messages" } -bp-polkadot-core = { path = "../../primitives/polkadot-core" } -bp-runtime = { path = "../../primitives/runtime" } -pallet-bridge-messages = { path = "../../modules/messages" } -finality-relay = { path = "../finality" } -relay-utils = { path = "../utils" } +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 = { path = "../../../substrate/frame/support" } -frame-system = { path = "../../../substrate/frame/system" } -pallet-balances = { path = "../../../substrate/frame/balances" } -pallet-transaction-payment = { path = "../../../substrate/frame/transaction-payment" } -pallet-transaction-payment-rpc-runtime-api = { path = "../../../substrate/frame/transaction-payment/rpc/runtime-api" } -pallet-utility = { path = "../../../substrate/frame/utility" } -sc-chain-spec = { path = "../../../substrate/client/chain-spec" } -sc-rpc-api = { path = "../../../substrate/client/rpc-api" } -sc-transaction-pool-api = { path = "../../../substrate/client/transaction-pool/api" } -sp-consensus-grandpa = { path = "../../../substrate/primitives/consensus/grandpa" } -sp-core = { path = "../../../substrate/primitives/core" } -sp-rpc = { path = "../../../substrate/primitives/rpc" } -sp-runtime = { path = "../../../substrate/primitives/runtime" } -sp-std = { path = "../../../substrate/primitives/std" } -sp-trie = { path = "../../../substrate/primitives/trie" } -sp-version = { path = "../../../substrate/primitives/version" } +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 } +sc-chain-spec = { workspace = true, default-features = true } +sc-rpc-api = { workspace = true, default-features = true } +sc-transaction-pool-api = { workspace = true, default-features = true } +sp-consensus-grandpa = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-rpc = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-std = { workspace = true, default-features = true } +sp-trie = { workspace = true, default-features = true } +sp-version = { workspace = true, default-features = true } # Polkadot Dependencies -xcm = { package = "staging-xcm", path = "../../../polkadot/xcm" } +xcm = { workspace = true, default-features = true } [features] default = [] diff --git a/bridges/relays/client-substrate/src/chain.rs b/bridges/relays/client-substrate/src/chain.rs index 40269fe64c879249e9f0ed5ffe070d9fc606bdb6..227e9c31c5bfc6a93df88bb117f29bdb1b7c61d3 100644 --- a/bridges/relays/client-substrate/src/chain.rs +++ b/bridges/relays/client-substrate/src/chain.rs @@ -36,6 +36,9 @@ use sp_runtime::{ }; use std::{fmt::Debug, time::Duration}; +/// Signed block type of given chain. +pub type SignedBlockOf = ::SignedBlock; + /// Substrate-based chain from minimal relay-client point of view. pub trait Chain: ChainBase + Clone { /// Chain name. diff --git a/bridges/relays/client-substrate/src/client.rs b/bridges/relays/client-substrate/src/client.rs deleted file mode 100644 index 2e7cb7455f76cceee1c63aae4efb4a5cfe9f2a69..0000000000000000000000000000000000000000 --- a/bridges/relays/client-substrate/src/client.rs +++ /dev/null @@ -1,1032 +0,0 @@ -// 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 . - -//! Substrate node client. - -use crate::{ - chain::{Chain, ChainWithTransactions}, - guard::Environment, - rpc::{ - SubstrateAuthorClient, SubstrateChainClient, SubstrateFinalityClient, - SubstrateFrameSystemClient, SubstrateStateClient, SubstrateSystemClient, - }, - transaction_stall_timeout, AccountKeyPairOf, ChainWithGrandpa, ConnectionParams, Error, HashOf, - HeaderIdOf, Result, SignParam, TransactionTracker, UnsignedTransaction, -}; - -use async_std::sync::{Arc, Mutex, RwLock}; -use async_trait::async_trait; -use bp_runtime::{HeaderIdProvider, StorageDoubleMapKeyProvider, StorageMapKeyProvider}; -use codec::{Decode, Encode}; -use frame_support::weights::Weight; -use futures::{SinkExt, StreamExt}; -use jsonrpsee::{ - core::DeserializeOwned, - ws_client::{WsClient as RpcClient, WsClientBuilder as RpcClientBuilder}, -}; -use num_traits::{Saturating, Zero}; -use pallet_transaction_payment::RuntimeDispatchInfo; -use relay_utils::{relay_loop::RECONNECT_DELAY, STALL_TIMEOUT}; -use sp_core::{ - storage::{StorageData, StorageKey}, - Bytes, Hasher, Pair, -}; -use sp_runtime::{ - traits::Header as HeaderT, - transaction_validity::{TransactionSource, TransactionValidity}, -}; -use sp_trie::StorageProof; -use sp_version::RuntimeVersion; -use std::{cmp::Ordering, future::Future}; - -const SUB_API_GRANDPA_AUTHORITIES: &str = "GrandpaApi_grandpa_authorities"; -const SUB_API_GRANDPA_GENERATE_KEY_OWNERSHIP_PROOF: &str = - "GrandpaApi_generate_key_ownership_proof"; -const SUB_API_TXPOOL_VALIDATE_TRANSACTION: &str = "TaggedTransactionQueue_validate_transaction"; -const SUB_API_TX_PAYMENT_QUERY_INFO: &str = "TransactionPaymentApi_query_info"; -const MAX_SUBSCRIPTION_CAPACITY: usize = 4096; - -/// The difference between best block number and number of its ancestor, that is enough -/// for us to consider that ancestor an "ancient" block with dropped state. -/// -/// The relay does not assume that it is connected to the archive node, so it always tries -/// to use the best available chain state. But sometimes it still may use state of some -/// old block. If the state of that block is already dropped, relay will see errors when -/// e.g. it tries to prove something. -/// -/// By default Substrate-based nodes are storing state for last 256 blocks. We'll use -/// half of this value. -pub const ANCIENT_BLOCK_THRESHOLD: u32 = 128; - -/// Returns `true` if we think that the state is already discarded for given block. -pub fn is_ancient_block + PartialOrd + Saturating>(block: N, best: N) -> bool { - best.saturating_sub(block) >= N::from(ANCIENT_BLOCK_THRESHOLD) -} - -/// Opaque justifications subscription type. -pub struct Subscription( - pub(crate) Mutex>>, - // The following field is not explicitly used by the code. But when it is dropped, - // the bakground task receives a shutdown signal. - #[allow(dead_code)] pub(crate) futures::channel::oneshot::Sender<()>, -); - -/// Opaque GRANDPA authorities set. -pub type OpaqueGrandpaAuthoritiesSet = Vec; - -/// A simple runtime version. It only includes the `spec_version` and `transaction_version`. -#[derive(Copy, Clone, Debug)] -pub struct SimpleRuntimeVersion { - /// Version of the runtime specification. - pub spec_version: u32, - /// All existing dispatches are fully compatible when this number doesn't change. - pub transaction_version: u32, -} - -impl SimpleRuntimeVersion { - /// Create a new instance of `SimpleRuntimeVersion` from a `RuntimeVersion`. - pub const fn from_runtime_version(runtime_version: &RuntimeVersion) -> Self { - Self { - spec_version: runtime_version.spec_version, - transaction_version: runtime_version.transaction_version, - } - } -} - -/// Chain runtime version in client -#[derive(Copy, Clone, Debug)] -pub enum ChainRuntimeVersion { - /// Auto query from chain. - Auto, - /// Custom runtime version, defined by user. - Custom(SimpleRuntimeVersion), -} - -/// Substrate client type. -/// -/// Cloning `Client` is a cheap operation that only clones internal references. Different -/// clones of the same client are guaranteed to use the same references. -pub struct Client { - // Lock order: `submit_signed_extrinsic_lock`, `data` - /// Client connection params. - params: Arc, - /// Saved chain runtime version. - chain_runtime_version: ChainRuntimeVersion, - /// If several tasks are submitting their transactions simultaneously using - /// `submit_signed_extrinsic` method, they may get the same transaction nonce. So one of - /// transactions will be rejected from the pool. This lock is here to prevent situations like - /// that. - submit_signed_extrinsic_lock: Arc>, - /// Genesis block hash. - genesis_hash: HashOf, - /// Shared dynamic data. - data: Arc>, -} - -/// Client data, shared by all `Client` clones. -struct ClientData { - /// Tokio runtime handle. - tokio: Arc, - /// Substrate RPC client. - client: Arc, -} - -/// Already encoded value. -struct PreEncoded(Vec); - -impl Encode for PreEncoded { - fn encode(&self) -> Vec { - self.0.clone() - } -} - -#[async_trait] -impl relay_utils::relay_loop::Client for Client { - type Error = Error; - - async fn reconnect(&mut self) -> Result<()> { - let mut data = self.data.write().await; - let (tokio, client) = Self::build_client(&self.params).await?; - data.tokio = tokio; - data.client = client; - Ok(()) - } -} - -impl Clone for Client { - fn clone(&self) -> Self { - Client { - params: self.params.clone(), - chain_runtime_version: self.chain_runtime_version, - submit_signed_extrinsic_lock: self.submit_signed_extrinsic_lock.clone(), - genesis_hash: self.genesis_hash, - data: self.data.clone(), - } - } -} - -impl std::fmt::Debug for Client { - fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { - fmt.debug_struct("Client").field("genesis_hash", &self.genesis_hash).finish() - } -} - -impl Client { - /// Returns client that is able to call RPCs on Substrate node over websocket connection. - /// - /// This function will keep connecting to given Substrate node until connection is established - /// and is functional. If attempt fail, it will wait for `RECONNECT_DELAY` and retry again. - pub async fn new(params: ConnectionParams) -> Self { - let params = Arc::new(params); - loop { - match Self::try_connect(params.clone()).await { - Ok(client) => return client, - Err(error) => log::error!( - target: "bridge", - "Failed to connect to {} node: {:?}. Going to retry in {}s", - C::NAME, - error, - RECONNECT_DELAY.as_secs(), - ), - } - - async_std::task::sleep(RECONNECT_DELAY).await; - } - } - - /// Try to connect to Substrate node over websocket. Returns Substrate RPC client if connection - /// has been established or error otherwise. - pub async fn try_connect(params: Arc) -> Result { - let (tokio, client) = Self::build_client(¶ms).await?; - - let number: C::BlockNumber = Zero::zero(); - let genesis_hash_client = client.clone(); - let genesis_hash = tokio - .spawn(async move { - SubstrateChainClient::::block_hash(&*genesis_hash_client, Some(number)).await - }) - .await??; - - let chain_runtime_version = params.chain_runtime_version; - let mut client = Self { - params, - chain_runtime_version, - submit_signed_extrinsic_lock: Arc::new(Mutex::new(())), - genesis_hash, - data: Arc::new(RwLock::new(ClientData { tokio, client })), - }; - Self::ensure_correct_runtime_version(&mut client, chain_runtime_version).await?; - Ok(client) - } - - // Check runtime version to understand if we need are connected to expected version, or we - // need to wait for upgrade, we need to abort immediately. - async fn ensure_correct_runtime_version>( - env: &mut E, - expected: ChainRuntimeVersion, - ) -> Result<()> { - // we are only interested if version mode is bundled or passed using CLI - let expected = match expected { - ChainRuntimeVersion::Auto => return Ok(()), - ChainRuntimeVersion::Custom(expected) => expected, - }; - - // we need to wait if actual version is < than expected, we are OK of versions are the - // same and we need to abort if actual version is > than expected - let actual = SimpleRuntimeVersion::from_runtime_version(&env.runtime_version().await?); - match actual.spec_version.cmp(&expected.spec_version) { - Ordering::Less => - Err(Error::WaitingForRuntimeUpgrade { chain: C::NAME.into(), expected, actual }), - Ordering::Equal => Ok(()), - Ordering::Greater => { - log::error!( - target: "bridge", - "The {} client is configured to use runtime version {expected:?} and actual \ - version is {actual:?}. Aborting", - C::NAME, - ); - env.abort().await; - Err(Error::Custom("Aborted".into())) - }, - } - } - - /// Build client to use in connection. - async fn build_client( - params: &ConnectionParams, - ) -> Result<(Arc, Arc)> { - let tokio = tokio::runtime::Runtime::new()?; - - let uri = match params.uri { - Some(ref uri) => uri.clone(), - None => { - format!( - "{}://{}:{}{}", - if params.secure { "wss" } else { "ws" }, - params.host, - params.port, - match params.path { - Some(ref path) => format!("/{}", path), - None => String::new(), - }, - ) - }, - }; - log::info!(target: "bridge", "Connecting to {} node at {}", C::NAME, uri); - - let client = tokio - .spawn(async move { - RpcClientBuilder::default() - .max_buffer_capacity_per_subscription(MAX_SUBSCRIPTION_CAPACITY) - .build(&uri) - .await - }) - .await??; - - Ok((Arc::new(tokio), Arc::new(client))) - } -} - -impl Client { - /// Return simple runtime version, only include `spec_version` and `transaction_version`. - pub async fn simple_runtime_version(&self) -> Result { - Ok(match &self.chain_runtime_version { - ChainRuntimeVersion::Auto => { - let runtime_version = self.runtime_version().await?; - SimpleRuntimeVersion::from_runtime_version(&runtime_version) - }, - ChainRuntimeVersion::Custom(version) => *version, - }) - } - - /// Returns true if client is connected to at least one peer and is in synced state. - pub async fn ensure_synced(&self) -> Result<()> { - self.jsonrpsee_execute(|client| async move { - let health = SubstrateSystemClient::::health(&*client).await?; - let is_synced = !health.is_syncing && (!health.should_have_peers || health.peers > 0); - if is_synced { - Ok(()) - } else { - Err(Error::ClientNotSynced(health)) - } - }) - .await - } - - /// Return hash of the genesis block. - pub fn genesis_hash(&self) -> &C::Hash { - &self.genesis_hash - } - - /// Return hash of the best finalized block. - pub async fn best_finalized_header_hash(&self) -> Result { - self.jsonrpsee_execute(|client| async move { - Ok(SubstrateChainClient::::finalized_head(&*client).await?) - }) - .await - .map_err(|e| Error::FailedToReadBestFinalizedHeaderHash { - chain: C::NAME.into(), - error: e.boxed(), - }) - } - - /// Return number of the best finalized block. - pub async fn best_finalized_header_number(&self) -> Result { - Ok(*self.best_finalized_header().await?.number()) - } - - /// Return header of the best finalized block. - pub async fn best_finalized_header(&self) -> Result { - self.header_by_hash(self.best_finalized_header_hash().await?).await - } - - /// Returns the best Substrate header. - pub async fn best_header(&self) -> Result - where - C::Header: DeserializeOwned, - { - self.jsonrpsee_execute(|client| async move { - Ok(SubstrateChainClient::::header(&*client, None).await?) - }) - .await - .map_err(|e| Error::FailedToReadBestHeader { chain: C::NAME.into(), error: e.boxed() }) - } - - /// Get a Substrate block from its hash. - pub async fn get_block(&self, block_hash: Option) -> Result { - self.jsonrpsee_execute(move |client| async move { - Ok(SubstrateChainClient::::block(&*client, block_hash).await?) - }) - .await - } - - /// Get a Substrate header by its hash. - pub async fn header_by_hash(&self, block_hash: C::Hash) -> Result - where - C::Header: DeserializeOwned, - { - self.jsonrpsee_execute(move |client| async move { - Ok(SubstrateChainClient::::header(&*client, Some(block_hash)).await?) - }) - .await - .map_err(|e| Error::FailedToReadHeaderByHash { - chain: C::NAME.into(), - hash: format!("{block_hash}"), - error: e.boxed(), - }) - } - - /// Get a Substrate block hash by its number. - pub async fn block_hash_by_number(&self, number: C::BlockNumber) -> Result { - self.jsonrpsee_execute(move |client| async move { - Ok(SubstrateChainClient::::block_hash(&*client, Some(number)).await?) - }) - .await - } - - /// Get a Substrate header by its number. - pub async fn header_by_number(&self, block_number: C::BlockNumber) -> Result - where - C::Header: DeserializeOwned, - { - let block_hash = Self::block_hash_by_number(self, block_number).await?; - let header_by_hash = Self::header_by_hash(self, block_hash).await?; - Ok(header_by_hash) - } - - /// Return runtime version. - pub async fn runtime_version(&self) -> Result { - self.jsonrpsee_execute(move |client| async move { - Ok(SubstrateStateClient::::runtime_version(&*client).await?) - }) - .await - } - - /// Read value from runtime storage. - pub async fn storage_value( - &self, - storage_key: StorageKey, - block_hash: Option, - ) -> Result> { - self.raw_storage_value(storage_key, block_hash) - .await? - .map(|encoded_value| { - T::decode(&mut &encoded_value.0[..]).map_err(Error::ResponseParseFailed) - }) - .transpose() - } - - /// Read `MapStorage` value from runtime storage. - pub async fn storage_map_value( - &self, - pallet_prefix: &str, - key: &T::Key, - block_hash: Option, - ) -> Result> { - let storage_key = T::final_key(pallet_prefix, key); - - self.raw_storage_value(storage_key, block_hash) - .await? - .map(|encoded_value| { - T::Value::decode(&mut &encoded_value.0[..]).map_err(Error::ResponseParseFailed) - }) - .transpose() - } - - /// Read `DoubleMapStorage` value from runtime storage. - pub async fn storage_double_map_value( - &self, - pallet_prefix: &str, - key1: &T::Key1, - key2: &T::Key2, - block_hash: Option, - ) -> Result> { - let storage_key = T::final_key(pallet_prefix, key1, key2); - - self.raw_storage_value(storage_key, block_hash) - .await? - .map(|encoded_value| { - T::Value::decode(&mut &encoded_value.0[..]).map_err(Error::ResponseParseFailed) - }) - .transpose() - } - - /// Read raw value from runtime storage. - pub async fn raw_storage_value( - &self, - storage_key: StorageKey, - block_hash: Option, - ) -> Result> { - let cloned_storage_key = storage_key.clone(); - self.jsonrpsee_execute(move |client| async move { - Ok(SubstrateStateClient::::storage(&*client, storage_key.clone(), block_hash) - .await?) - }) - .await - .map_err(|e| Error::FailedToReadRuntimeStorageValue { - chain: C::NAME.into(), - key: cloned_storage_key, - error: e.boxed(), - }) - } - - /// Get the nonce of the given Substrate account. - /// - /// Note: It's the caller's responsibility to make sure `account` is a valid SS58 address. - pub async fn next_account_index(&self, account: C::AccountId) -> Result { - self.jsonrpsee_execute(move |client| async move { - Ok(SubstrateFrameSystemClient::::account_next_index(&*client, account).await?) - }) - .await - } - - /// Submit unsigned extrinsic for inclusion in a block. - /// - /// Note: The given transaction needs to be SCALE encoded beforehand. - pub async fn submit_unsigned_extrinsic(&self, transaction: Bytes) -> Result { - // one last check that the transaction is valid. Most of checks happen in the relay loop and - // it is the "final" check before submission. - let best_header_hash = self.best_header().await?.hash(); - self.validate_transaction(best_header_hash, PreEncoded(transaction.0.clone())) - .await - .map_err(|e| { - log::error!(target: "bridge", "Pre-submit {} transaction validation failed: {:?}", C::NAME, e); - e - })??; - - self.jsonrpsee_execute(move |client| async move { - let tx_hash = SubstrateAuthorClient::::submit_extrinsic(&*client, transaction) - .await - .map_err(|e| { - log::error!(target: "bridge", "Failed to send transaction to {} node: {:?}", C::NAME, e); - e - })?; - log::trace!(target: "bridge", "Sent transaction to {} node: {:?}", C::NAME, tx_hash); - Ok(tx_hash) - }) - .await - } - - async fn build_sign_params(&self, signer: AccountKeyPairOf) -> Result> - where - C: ChainWithTransactions, - { - let runtime_version = self.simple_runtime_version().await?; - Ok(SignParam:: { - spec_version: runtime_version.spec_version, - transaction_version: runtime_version.transaction_version, - genesis_hash: self.genesis_hash, - signer, - }) - } - - /// Submit an extrinsic signed by given account. - /// - /// All calls of this method are synchronized, so there can't be more than one active - /// `submit_signed_extrinsic()` call. This guarantees that no nonces collision may happen - /// if all client instances are clones of the same initial `Client`. - /// - /// Note: The given transaction needs to be SCALE encoded beforehand. - pub async fn submit_signed_extrinsic( - &self, - signer: &AccountKeyPairOf, - prepare_extrinsic: impl FnOnce(HeaderIdOf, C::Nonce) -> Result> - + Send - + 'static, - ) -> Result - where - C: ChainWithTransactions, - C::AccountId: From<::Public>, - { - let _guard = self.submit_signed_extrinsic_lock.lock().await; - let transaction_nonce = self.next_account_index(signer.public().into()).await?; - let best_header = self.best_header().await?; - let signing_data = self.build_sign_params(signer.clone()).await?; - - // By using parent of best block here, we are protecing again best-block reorganizations. - // E.g. transaction may have been submitted when the best block was `A[num=100]`. Then it - // has been changed to `B[num=100]`. Hash of `A` has been included into transaction - // signature payload. So when signature will be checked, the check will fail and transaction - // will be dropped from the pool. - let best_header_id = best_header.parent_id().unwrap_or_else(|| best_header.id()); - - let extrinsic = prepare_extrinsic(best_header_id, transaction_nonce)?; - let signed_extrinsic = C::sign_transaction(signing_data, extrinsic)?.encode(); - - // one last check that the transaction is valid. Most of checks happen in the relay loop and - // it is the "final" check before submission. - self.validate_transaction(best_header_id.1, PreEncoded(signed_extrinsic.clone())) - .await - .map_err(|e| { - log::error!(target: "bridge", "Pre-submit {} transaction validation failed: {:?}", C::NAME, e); - e - })??; - - self.jsonrpsee_execute(move |client| async move { - let tx_hash = - SubstrateAuthorClient::::submit_extrinsic(&*client, Bytes(signed_extrinsic)) - .await - .map_err(|e| { - log::error!(target: "bridge", "Failed to send transaction to {} node: {:?}", C::NAME, e); - e - })?; - log::trace!(target: "bridge", "Sent transaction to {} node: {:?}", C::NAME, tx_hash); - Ok(tx_hash) - }) - .await - } - - /// Does exactly the same as `submit_signed_extrinsic`, but keeps watching for extrinsic status - /// after submission. - pub async fn submit_and_watch_signed_extrinsic( - &self, - signer: &AccountKeyPairOf, - prepare_extrinsic: impl FnOnce(HeaderIdOf, C::Nonce) -> Result> - + Send - + 'static, - ) -> Result> - where - C: ChainWithTransactions, - C::AccountId: From<::Public>, - { - let self_clone = self.clone(); - let signing_data = self.build_sign_params(signer.clone()).await?; - let _guard = self.submit_signed_extrinsic_lock.lock().await; - let transaction_nonce = self.next_account_index(signer.public().into()).await?; - let best_header = self.best_header().await?; - let best_header_id = best_header.id(); - - let extrinsic = prepare_extrinsic(best_header_id, transaction_nonce)?; - let stall_timeout = transaction_stall_timeout( - extrinsic.era.mortality_period(), - C::AVERAGE_BLOCK_INTERVAL, - STALL_TIMEOUT, - ); - let signed_extrinsic = C::sign_transaction(signing_data, extrinsic)?.encode(); - - // one last check that the transaction is valid. Most of checks happen in the relay loop and - // it is the "final" check before submission. - self.validate_transaction(best_header_id.1, PreEncoded(signed_extrinsic.clone())) - .await - .map_err(|e| { - log::error!(target: "bridge", "Pre-submit {} transaction validation failed: {:?}", C::NAME, e); - e - })??; - - let (cancel_sender, cancel_receiver) = futures::channel::oneshot::channel(); - let (sender, receiver) = futures::channel::mpsc::channel(MAX_SUBSCRIPTION_CAPACITY); - let (tracker, subscription) = self - .jsonrpsee_execute(move |client| async move { - let tx_hash = C::Hasher::hash(&signed_extrinsic); - let subscription = SubstrateAuthorClient::::submit_and_watch_extrinsic( - &*client, - Bytes(signed_extrinsic), - ) - .await - .map_err(|e| { - log::error!(target: "bridge", "Failed to send transaction to {} node: {:?}", C::NAME, e); - e - })?; - log::trace!(target: "bridge", "Sent transaction to {} node: {:?}", C::NAME, tx_hash); - let tracker = TransactionTracker::new( - self_clone, - stall_timeout, - tx_hash, - Subscription(Mutex::new(receiver), cancel_sender), - ); - Ok((tracker, subscription)) - }) - .await?; - self.data.read().await.tokio.spawn(Subscription::background_worker( - C::NAME.into(), - "extrinsic".into(), - subscription, - sender, - cancel_receiver, - )); - Ok(tracker) - } - - /// Returns pending extrinsics from transaction pool. - pub async fn pending_extrinsics(&self) -> Result> { - self.jsonrpsee_execute(move |client| async move { - Ok(SubstrateAuthorClient::::pending_extrinsics(&*client).await?) - }) - .await - } - - /// Validate transaction at given block state. - pub async fn validate_transaction( - &self, - at_block: C::Hash, - transaction: SignedTransaction, - ) -> Result { - self.jsonrpsee_execute(move |client| async move { - let call = SUB_API_TXPOOL_VALIDATE_TRANSACTION.to_string(); - let data = Bytes((TransactionSource::External, transaction, at_block).encode()); - - let encoded_response = - SubstrateStateClient::::call(&*client, call, data, Some(at_block)).await?; - let validity = TransactionValidity::decode(&mut &encoded_response.0[..]) - .map_err(Error::ResponseParseFailed)?; - - Ok(validity) - }) - .await - } - - /// Returns weight of the given transaction. - pub async fn extimate_extrinsic_weight( - &self, - transaction: SignedTransaction, - ) -> Result { - self.jsonrpsee_execute(move |client| async move { - let transaction_len = transaction.encoded_size() as u32; - - let call = SUB_API_TX_PAYMENT_QUERY_INFO.to_string(); - let data = Bytes((transaction, transaction_len).encode()); - - let encoded_response = - SubstrateStateClient::::call(&*client, call, data, None).await?; - let dispatch_info = - RuntimeDispatchInfo::::decode(&mut &encoded_response.0[..]) - .map_err(Error::ResponseParseFailed)?; - - Ok(dispatch_info.weight) - }) - .await - } - - /// Get the GRANDPA authority set at given block. - pub async fn grandpa_authorities_set( - &self, - block: C::Hash, - ) -> Result { - self.jsonrpsee_execute(move |client| async move { - let call = SUB_API_GRANDPA_AUTHORITIES.to_string(); - let data = Bytes(Vec::new()); - - let encoded_response = - SubstrateStateClient::::call(&*client, call, data, Some(block)).await?; - let authority_list = encoded_response.0; - - Ok(authority_list) - }) - .await - } - - /// Execute runtime call at given block, provided the input and output types. - /// It also performs the input encode and output decode. - pub async fn typed_state_call( - &self, - method_name: String, - input: Input, - at_block: Option, - ) -> Result { - let encoded_output = self - .state_call(method_name.clone(), Bytes(input.encode()), at_block) - .await - .map_err(|e| Error::ErrorExecutingRuntimeCall { - chain: C::NAME.into(), - method: method_name, - error: e.boxed(), - })?; - Output::decode(&mut &encoded_output.0[..]).map_err(Error::ResponseParseFailed) - } - - /// Execute runtime call at given block. - pub async fn state_call( - &self, - method: String, - data: Bytes, - at_block: Option, - ) -> Result { - self.jsonrpsee_execute(move |client| async move { - SubstrateStateClient::::call(&*client, method, data, at_block) - .await - .map_err(Into::into) - }) - .await - } - - /// Returns storage proof of given storage keys. - pub async fn prove_storage( - &self, - keys: Vec, - at_block: C::Hash, - ) -> Result { - self.jsonrpsee_execute(move |client| async move { - SubstrateStateClient::::prove_storage(&*client, keys, Some(at_block)) - .await - .map(|proof| { - StorageProof::new(proof.proof.into_iter().map(|b| b.0).collect::>()) - }) - .map_err(Into::into) - }) - .await - } - - /// Return `tokenDecimals` property from the set of chain properties. - pub async fn token_decimals(&self) -> Result> { - self.jsonrpsee_execute(move |client| async move { - let system_properties = SubstrateSystemClient::::properties(&*client).await?; - Ok(system_properties.get("tokenDecimals").and_then(|v| v.as_u64())) - }) - .await - } - - /// Return new finality justifications stream. - pub async fn subscribe_finality_justifications>( - &self, - ) -> Result> { - let subscription = self - .jsonrpsee_execute(move |client| async move { - Ok(FC::subscribe_justifications(&client).await?) - }) - .await?; - let (cancel_sender, cancel_receiver) = futures::channel::oneshot::channel(); - let (sender, receiver) = futures::channel::mpsc::channel(MAX_SUBSCRIPTION_CAPACITY); - self.data.read().await.tokio.spawn(Subscription::background_worker( - C::NAME.into(), - "justification".into(), - subscription, - sender, - cancel_receiver, - )); - Ok(Subscription(Mutex::new(receiver), cancel_sender)) - } - - /// Generates a proof of key ownership for the given authority in the given set. - pub async fn generate_grandpa_key_ownership_proof( - &self, - at: HashOf, - set_id: sp_consensus_grandpa::SetId, - authority_id: sp_consensus_grandpa::AuthorityId, - ) -> Result> - where - C: ChainWithGrandpa, - { - self.typed_state_call( - SUB_API_GRANDPA_GENERATE_KEY_OWNERSHIP_PROOF.into(), - (set_id, authority_id), - Some(at), - ) - .await - } - - /// Execute jsonrpsee future in tokio context. - async fn jsonrpsee_execute(&self, make_jsonrpsee_future: MF) -> Result - where - MF: FnOnce(Arc) -> F + Send + 'static, - F: Future> + Send + 'static, - T: Send + 'static, - { - let data = self.data.read().await; - let client = data.client.clone(); - data.tokio.spawn(make_jsonrpsee_future(client)).await? - } - - /// Returns `true` if version guard can be started. - /// - /// There's no reason to run version guard when version mode is set to `Auto`. It can - /// lead to relay shutdown when chain is upgraded, even though we have explicitly - /// said that we don't want to shutdown. - pub fn can_start_version_guard(&self) -> bool { - !matches!(self.chain_runtime_version, ChainRuntimeVersion::Auto) - } -} - -impl Subscription { - /// Consumes subscription and returns future statuses stream. - pub fn into_stream(self) -> impl futures::Stream { - futures::stream::unfold(Some(self), |mut this| async move { - let Some(this) = this.take() else { return None }; - let item = this.0.lock().await.next().await.unwrap_or(None); - match item { - Some(item) => Some((item, Some(this))), - None => { - // let's make it explicit here - let _ = this.1.send(()); - None - }, - } - }) - } - - /// Return next item from the subscription. - pub async fn next(&self) -> Result> { - let mut receiver = self.0.lock().await; - let item = receiver.next().await; - Ok(item.unwrap_or(None)) - } - - /// Background worker that is executed in tokio context as `jsonrpsee` requires. - async fn background_worker( - chain_name: String, - item_type: String, - subscription: jsonrpsee::core::client::Subscription, - mut sender: futures::channel::mpsc::Sender>, - cancel_receiver: futures::channel::oneshot::Receiver<()>, - ) { - log::trace!( - target: "bridge", - "Starting background worker for {} {} subscription stream.", - chain_name, - item_type, - ); - - futures::pin_mut!(subscription, cancel_receiver); - loop { - match futures::future::select(subscription.next(), &mut cancel_receiver).await { - futures::future::Either::Left((Some(Ok(item)), _)) => - if sender.send(Some(item)).await.is_err() { - log::trace!( - target: "bridge", - "{} {} subscription stream: no listener. Stopping background worker.", - chain_name, - item_type, - ); - - break - }, - futures::future::Either::Left((Some(Err(e)), _)) => { - log::trace!( - target: "bridge", - "{} {} subscription stream has returned '{:?}'. Stream needs to be restarted. Stopping background worker.", - chain_name, - item_type, - e, - ); - let _ = sender.send(None).await; - break - }, - futures::future::Either::Left((None, _)) => { - log::trace!( - target: "bridge", - "{} {} subscription stream has returned None. Stream needs to be restarted. Stopping background worker.", - chain_name, - item_type, - ); - let _ = sender.send(None).await; - break - }, - futures::future::Either::Right((_, _)) => { - log::trace!( - target: "bridge", - "{} {} subscription stream: listener has been dropped. Stopping background worker.", - chain_name, - item_type, - ); - break; - }, - } - } - } -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::{guard::tests::TestEnvironment, test_chain::TestChain}; - use futures::{channel::mpsc::unbounded, FutureExt}; - - async fn run_ensure_correct_runtime_version( - expected: ChainRuntimeVersion, - actual: RuntimeVersion, - ) -> Result<()> { - let ( - (mut runtime_version_tx, runtime_version_rx), - (slept_tx, _slept_rx), - (aborted_tx, mut aborted_rx), - ) = (unbounded(), unbounded(), unbounded()); - runtime_version_tx.send(actual).await.unwrap(); - let mut env = TestEnvironment { runtime_version_rx, slept_tx, aborted_tx }; - - let ensure_correct_runtime_version = - Client::::ensure_correct_runtime_version(&mut env, expected).boxed(); - let aborted = aborted_rx.next().map(|_| Err(Error::Custom("".into()))).boxed(); - futures::pin_mut!(ensure_correct_runtime_version, aborted); - futures::future::select(ensure_correct_runtime_version, aborted) - .await - .into_inner() - .0 - } - - #[async_std::test] - async fn ensure_correct_runtime_version_works() { - // when we are configured to use auto version - assert!(matches!( - run_ensure_correct_runtime_version( - ChainRuntimeVersion::Auto, - RuntimeVersion { - spec_version: 100, - transaction_version: 100, - ..Default::default() - }, - ) - .await, - Ok(()), - )); - // when actual == expected - assert!(matches!( - run_ensure_correct_runtime_version( - ChainRuntimeVersion::Custom(SimpleRuntimeVersion { - spec_version: 100, - transaction_version: 100 - }), - RuntimeVersion { - spec_version: 100, - transaction_version: 100, - ..Default::default() - }, - ) - .await, - Ok(()), - )); - // when actual spec version < expected spec version - assert!(matches!( - run_ensure_correct_runtime_version( - ChainRuntimeVersion::Custom(SimpleRuntimeVersion { - spec_version: 100, - transaction_version: 100 - }), - RuntimeVersion { spec_version: 99, transaction_version: 100, ..Default::default() }, - ) - .await, - Err(Error::WaitingForRuntimeUpgrade { - expected: SimpleRuntimeVersion { spec_version: 100, transaction_version: 100 }, - actual: SimpleRuntimeVersion { spec_version: 99, transaction_version: 100 }, - .. - }), - )); - // when actual spec version > expected spec version - assert!(matches!( - run_ensure_correct_runtime_version( - ChainRuntimeVersion::Custom(SimpleRuntimeVersion { - spec_version: 100, - transaction_version: 100 - }), - RuntimeVersion { - spec_version: 101, - transaction_version: 100, - ..Default::default() - }, - ) - .await, - Err(Error::Custom(_)), - )); - } -} diff --git a/bridges/relays/client-substrate/src/client/caching.rs b/bridges/relays/client-substrate/src/client/caching.rs new file mode 100644 index 0000000000000000000000000000000000000000..cb898cf517267a173b0ef4daf374c5b16b0757ba --- /dev/null +++ b/bridges/relays/client-substrate/src/client/caching.rs @@ -0,0 +1,468 @@ +// 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 . + +//! Client implementation that is caching (whenever possible) results of its backend +//! method calls. + +use crate::{ + client::{Client, SubscriptionBroadcaster}, + error::{Error, Result}, + AccountIdOf, AccountKeyPairOf, BlockNumberOf, Chain, ChainWithGrandpa, ChainWithTransactions, + HashOf, HeaderIdOf, HeaderOf, NonceOf, SignedBlockOf, SimpleRuntimeVersion, Subscription, + TransactionTracker, UnsignedTransaction, ANCIENT_BLOCK_THRESHOLD, +}; +use std::{cmp::Ordering, future::Future, task::Poll}; + +use async_std::{ + sync::{Arc, Mutex, RwLock}, + task::JoinHandle, +}; +use async_trait::async_trait; +use codec::Encode; +use frame_support::weights::Weight; +use futures::{FutureExt, StreamExt}; +use quick_cache::unsync::Cache; +use sp_consensus_grandpa::{AuthorityId, OpaqueKeyOwnershipProof, SetId}; +use sp_core::{ + storage::{StorageData, StorageKey}, + Bytes, Pair, +}; +use sp_runtime::{traits::Header as _, transaction_validity::TransactionValidity}; +use sp_trie::StorageProof; +use sp_version::RuntimeVersion; + +/// `quick_cache::unsync::Cache` wrapped in async-aware synchronization primitives. +type SyncCache = Arc>>; + +/// Client implementation that is caching (whenever possible) results of its backend +/// method calls. Apart from caching call results, it also supports some (at the +/// moment: justifications) subscription sharing, meaning that the single server +/// subscription may be shared by multiple subscribers at the client side. +#[derive(Clone)] +pub struct CachingClient> { + backend: B, + data: Arc>, +} + +/// Client data, shared by all `CachingClient` clones. +struct ClientData { + grandpa_justifications: Arc>>>, + beefy_justifications: Arc>>>, + background_task_handle: Arc>>>, + best_header: Arc>>>, + best_finalized_header: Arc>>>, + // `quick_cache::sync::Cache` has the `get_or_insert_async` method, which fits our needs, + // but it uses synchronization primitives that are not aware of async execution. They + // can block the executor threads and cause deadlocks => let's use primitives from + // `async_std` crate around `quick_cache::unsync::Cache` + header_hash_by_number_cache: SyncCache, HashOf>, + header_by_hash_cache: SyncCache, HeaderOf>, + block_by_hash_cache: SyncCache, SignedBlockOf>, + raw_storage_value_cache: SyncCache<(HashOf, StorageKey), Option>, + state_call_cache: SyncCache<(HashOf, String, Bytes), Bytes>, +} + +impl> CachingClient { + /// Creates new `CachingClient` on top of given `backend`. + pub async fn new(backend: B) -> Self { + // most of relayer operations will never touch more than `ANCIENT_BLOCK_THRESHOLD` + // headers, so we'll use this as a cache capacity for all chain-related caches + let chain_state_capacity = ANCIENT_BLOCK_THRESHOLD as usize; + let best_header = Arc::new(RwLock::new(None)); + let best_finalized_header = Arc::new(RwLock::new(None)); + let header_by_hash_cache = Arc::new(RwLock::new(Cache::new(chain_state_capacity))); + let background_task_handle = Self::start_background_task( + backend.clone(), + best_header.clone(), + best_finalized_header.clone(), + header_by_hash_cache.clone(), + ) + .await; + CachingClient { + backend, + data: Arc::new(ClientData { + grandpa_justifications: Arc::new(Mutex::new(None)), + beefy_justifications: Arc::new(Mutex::new(None)), + background_task_handle: Arc::new(Mutex::new(background_task_handle)), + best_header, + best_finalized_header, + header_hash_by_number_cache: Arc::new(RwLock::new(Cache::new( + chain_state_capacity, + ))), + header_by_hash_cache, + block_by_hash_cache: Arc::new(RwLock::new(Cache::new(chain_state_capacity))), + raw_storage_value_cache: Arc::new(RwLock::new(Cache::new(1_024))), + state_call_cache: Arc::new(RwLock::new(Cache::new(1_024))), + }), + } + } + + /// Try to get value from the cache, or compute and insert it using given future. + async fn get_or_insert_async( + &self, + cache: &Arc>>, + key: &K, + with: impl std::future::Future>, + ) -> Result { + // try to get cached value first using read lock + { + let cache = cache.read().await; + if let Some(value) = cache.get(key) { + return Ok(value.clone()) + } + } + + // let's compute the value without holding any locks - it may cause additional misses and + // double insertions, but that's better than holding a lock for a while + let value = with.await?; + + // insert/update the value in the cache + cache.write().await.insert(key.clone(), value.clone()); + Ok(value) + } + + /// Subscribe to finality justifications, trying to reuse existing subscription. + async fn subscribe_finality_justifications<'a>( + &'a self, + maybe_broadcaster: &Mutex>>, + do_subscribe: impl Future>> + 'a, + ) -> Result> { + let mut maybe_broadcaster = maybe_broadcaster.lock().await; + let broadcaster = match maybe_broadcaster.as_ref() { + Some(justifications) => justifications, + None => { + let broadcaster = match SubscriptionBroadcaster::new(do_subscribe.await?) { + Ok(broadcaster) => broadcaster, + Err(subscription) => return Ok(subscription), + }; + maybe_broadcaster.get_or_insert(broadcaster) + }, + }; + + broadcaster.subscribe().await + } + + /// Start background task that reads best (and best finalized) headers from subscriptions. + async fn start_background_task( + backend: B, + best_header: Arc>>>, + best_finalized_header: Arc>>>, + header_by_hash_cache: SyncCache, HeaderOf>, + ) -> JoinHandle> { + async_std::task::spawn(async move { + // initialize by reading headers directly from backend to avoid doing that in the + // high-level code + let mut last_finalized_header = + backend.header_by_hash(backend.best_finalized_header_hash().await?).await?; + *best_header.write().await = Some(backend.best_header().await?); + *best_finalized_header.write().await = Some(last_finalized_header.clone()); + + // ...and then continue with subscriptions + let mut best_headers = backend.subscribe_best_headers().await?; + let mut finalized_headers = backend.subscribe_finalized_headers().await?; + loop { + futures::select! { + new_best_header = best_headers.next().fuse() => { + // we assume that the best header is always the actual best header, even if its + // number is lower than the number of previous-best-header (chain may use its own + // best header selection algorithms) + let new_best_header = new_best_header + .ok_or_else(|| Error::ChannelError(format!("Mandatory best headers subscription for {} has finished", C::NAME)))?; + let new_best_header_hash = new_best_header.hash(); + header_by_hash_cache.write().await.insert(new_best_header_hash, new_best_header.clone()); + *best_header.write().await = Some(new_best_header); + }, + new_finalized_header = finalized_headers.next().fuse() => { + // in theory we'll always get finalized headers in order, but let's double check + let new_finalized_header = new_finalized_header. + ok_or_else(|| Error::ChannelError(format!("Finalized headers subscription for {} has finished", C::NAME)))?; + let new_finalized_header_number = *new_finalized_header.number(); + let last_finalized_header_number = *last_finalized_header.number(); + match new_finalized_header_number.cmp(&last_finalized_header_number) { + Ordering::Greater => { + let new_finalized_header_hash = new_finalized_header.hash(); + header_by_hash_cache.write().await.insert(new_finalized_header_hash, new_finalized_header.clone()); + *best_finalized_header.write().await = Some(new_finalized_header.clone()); + last_finalized_header = new_finalized_header; + }, + Ordering::Less => { + return Err(Error::unordered_finalized_headers::( + new_finalized_header_number, + last_finalized_header_number, + )); + }, + _ => (), + } + }, + } + } + }) + } + + /// Ensure that the background task is active. + async fn ensure_background_task_active(&self) -> Result<()> { + let mut background_task_handle = self.data.background_task_handle.lock().await; + if let Poll::Ready(result) = futures::poll!(&mut *background_task_handle) { + return Err(Error::ChannelError(format!( + "Background task of {} client has exited with result: {:?}", + C::NAME, + result + ))) + } + + Ok(()) + } + + /// Try to get header, read elsewhere by background task through subscription. + async fn read_header_from_background<'a>( + &'a self, + header: &Arc>>>, + read_header_from_backend: impl Future>> + 'a, + ) -> Result> { + // ensure that the background task is active + self.ensure_background_task_active().await?; + + // now we know that the background task is active, so we could trust that the + // `header` has the most recent updates from it + match header.read().await.clone() { + Some(header) => Ok(header), + None => { + // header has not yet been read from the subscription, which means that + // we are just starting - let's read header directly from backend this time + read_header_from_backend.await + }, + } + } +} + +impl> std::fmt::Debug for CachingClient { + fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { + fmt.write_fmt(format_args!("CachingClient<{:?}>", self.backend)) + } +} + +#[async_trait] +impl> Client for CachingClient { + async fn ensure_synced(&self) -> Result<()> { + self.backend.ensure_synced().await + } + + async fn reconnect(&self) -> Result<()> { + self.backend.reconnect().await?; + // since we have new underlying client, we need to restart subscriptions too + *self.data.grandpa_justifications.lock().await = None; + *self.data.beefy_justifications.lock().await = None; + // also restart background task too + *self.data.best_header.write().await = None; + *self.data.best_finalized_header.write().await = None; + *self.data.background_task_handle.lock().await = Self::start_background_task( + self.backend.clone(), + self.data.best_header.clone(), + self.data.best_finalized_header.clone(), + self.data.header_by_hash_cache.clone(), + ) + .await; + Ok(()) + } + + fn genesis_hash(&self) -> HashOf { + self.backend.genesis_hash() + } + + async fn header_hash_by_number(&self, number: BlockNumberOf) -> Result> { + self.get_or_insert_async( + &self.data.header_hash_by_number_cache, + &number, + self.backend.header_hash_by_number(number), + ) + .await + } + + async fn header_by_hash(&self, hash: HashOf) -> Result> { + self.get_or_insert_async( + &self.data.header_by_hash_cache, + &hash, + self.backend.header_by_hash(hash), + ) + .await + } + + async fn block_by_hash(&self, hash: HashOf) -> Result> { + self.get_or_insert_async( + &self.data.block_by_hash_cache, + &hash, + self.backend.block_by_hash(hash), + ) + .await + } + + async fn best_finalized_header_hash(&self) -> Result> { + self.read_header_from_background( + &self.data.best_finalized_header, + self.backend.best_finalized_header(), + ) + .await + .map(|h| h.hash()) + } + + async fn best_header(&self) -> Result> { + self.read_header_from_background(&self.data.best_header, self.backend.best_header()) + .await + } + + async fn subscribe_best_headers(&self) -> Result>> { + // we may share the sunbscription here, but atm there's no callers of this method + self.backend.subscribe_best_headers().await + } + + async fn subscribe_finalized_headers(&self) -> Result>> { + // we may share the sunbscription here, but atm there's no callers of this method + self.backend.subscribe_finalized_headers().await + } + + async fn subscribe_grandpa_finality_justifications(&self) -> Result> + where + C: ChainWithGrandpa, + { + self.subscribe_finality_justifications( + &self.data.grandpa_justifications, + self.backend.subscribe_grandpa_finality_justifications(), + ) + .await + } + + async fn generate_grandpa_key_ownership_proof( + &self, + at: HashOf, + set_id: SetId, + authority_id: AuthorityId, + ) -> Result> { + self.backend + .generate_grandpa_key_ownership_proof(at, set_id, authority_id) + .await + } + + async fn subscribe_beefy_finality_justifications(&self) -> Result> { + self.subscribe_finality_justifications( + &self.data.beefy_justifications, + self.backend.subscribe_beefy_finality_justifications(), + ) + .await + } + + async fn token_decimals(&self) -> Result> { + self.backend.token_decimals().await + } + + async fn runtime_version(&self) -> Result { + self.backend.runtime_version().await + } + + async fn simple_runtime_version(&self) -> Result { + self.backend.simple_runtime_version().await + } + + fn can_start_version_guard(&self) -> bool { + self.backend.can_start_version_guard() + } + + async fn raw_storage_value( + &self, + at: HashOf, + storage_key: StorageKey, + ) -> Result> { + self.get_or_insert_async( + &self.data.raw_storage_value_cache, + &(at, storage_key.clone()), + self.backend.raw_storage_value(at, storage_key), + ) + .await + } + + async fn pending_extrinsics(&self) -> Result> { + self.backend.pending_extrinsics().await + } + + async fn submit_unsigned_extrinsic(&self, transaction: Bytes) -> Result> { + self.backend.submit_unsigned_extrinsic(transaction).await + } + + async fn submit_signed_extrinsic( + &self, + signer: &AccountKeyPairOf, + prepare_extrinsic: impl FnOnce(HeaderIdOf, NonceOf) -> Result> + + Send + + 'static, + ) -> Result> + where + C: ChainWithTransactions, + AccountIdOf: From< as Pair>::Public>, + { + self.backend.submit_signed_extrinsic(signer, prepare_extrinsic).await + } + + async fn submit_and_watch_signed_extrinsic( + &self, + signer: &AccountKeyPairOf, + prepare_extrinsic: impl FnOnce(HeaderIdOf, NonceOf) -> Result> + + Send + + 'static, + ) -> Result> + where + C: ChainWithTransactions, + AccountIdOf: From< as Pair>::Public>, + { + self.backend + .submit_and_watch_signed_extrinsic(signer, prepare_extrinsic) + .await + .map(|t| t.switch_environment(self.clone())) + } + + async fn validate_transaction( + &self, + at: HashOf, + transaction: SignedTransaction, + ) -> Result { + self.backend.validate_transaction(at, transaction).await + } + + async fn estimate_extrinsic_weight( + &self, + at: HashOf, + transaction: SignedTransaction, + ) -> Result { + self.backend.estimate_extrinsic_weight(at, transaction).await + } + + async fn raw_state_call( + &self, + at: HashOf, + method: String, + arguments: Args, + ) -> Result { + let encoded_arguments = Bytes(arguments.encode()); + self.get_or_insert_async( + &self.data.state_call_cache, + &(at, method.clone(), encoded_arguments), + self.backend.raw_state_call(at, method, arguments), + ) + .await + } + + async fn prove_storage(&self, at: HashOf, keys: Vec) -> Result { + self.backend.prove_storage(at, keys).await + } +} diff --git a/bridges/relays/client-substrate/src/client/mod.rs b/bridges/relays/client-substrate/src/client/mod.rs new file mode 100644 index 0000000000000000000000000000000000000000..62a1119d718ff79fa45800166c01762e2044f781 --- /dev/null +++ b/bridges/relays/client-substrate/src/client/mod.rs @@ -0,0 +1,91 @@ +// 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 . + +//! Layered Substrate client implementation. + +use crate::{Chain, ConnectionParams}; + +use caching::CachingClient; +use num_traits::Saturating; +use rpc::RpcClient; +use sp_version::RuntimeVersion; + +pub mod caching; +pub mod rpc; + +mod rpc_api; +mod subscription; +mod traits; + +pub use subscription::{StreamDescription, Subscription, SubscriptionBroadcaster}; +pub use traits::Client; + +/// Type of RPC client with caching support. +pub type RpcWithCachingClient = CachingClient>; + +/// Creates new RPC client with caching support. +pub async fn rpc_with_caching(params: ConnectionParams) -> RpcWithCachingClient { + let rpc = rpc::RpcClient::::new(params).await; + caching::CachingClient::new(rpc).await +} + +/// The difference between best block number and number of its ancestor, that is enough +/// for us to consider that ancestor an "ancient" block with dropped state. +/// +/// The relay does not assume that it is connected to the archive node, so it always tries +/// to use the best available chain state. But sometimes it still may use state of some +/// old block. If the state of that block is already dropped, relay will see errors when +/// e.g. it tries to prove something. +/// +/// By default Substrate-based nodes are storing state for last 256 blocks. We'll use +/// half of this value. +pub const ANCIENT_BLOCK_THRESHOLD: u32 = 128; + +/// Returns `true` if we think that the state is already discarded for given block. +pub fn is_ancient_block + PartialOrd + Saturating>(block: N, best: N) -> bool { + best.saturating_sub(block) >= N::from(ANCIENT_BLOCK_THRESHOLD) +} + +/// Opaque GRANDPA authorities set. +pub type OpaqueGrandpaAuthoritiesSet = Vec; + +/// A simple runtime version. It only includes the `spec_version` and `transaction_version`. +#[derive(Copy, Clone, Debug)] +pub struct SimpleRuntimeVersion { + /// Version of the runtime specification. + pub spec_version: u32, + /// All existing dispatches are fully compatible when this number doesn't change. + pub transaction_version: u32, +} + +impl SimpleRuntimeVersion { + /// Create a new instance of `SimpleRuntimeVersion` from a `RuntimeVersion`. + pub const fn from_runtime_version(runtime_version: &RuntimeVersion) -> Self { + Self { + spec_version: runtime_version.spec_version, + transaction_version: runtime_version.transaction_version, + } + } +} + +/// Chain runtime version in client +#[derive(Copy, Clone, Debug)] +pub enum ChainRuntimeVersion { + /// Auto query from chain. + Auto, + /// Custom runtime version, defined by user. + Custom(SimpleRuntimeVersion), +} diff --git a/bridges/relays/client-substrate/src/client/rpc.rs b/bridges/relays/client-substrate/src/client/rpc.rs new file mode 100644 index 0000000000000000000000000000000000000000..bf7442a95141ff168229bffbc149f686d6b2771a --- /dev/null +++ b/bridges/relays/client-substrate/src/client/rpc.rs @@ -0,0 +1,743 @@ +// 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 . + +//! Client implementation that connects to the Substrate node over `ws`/`wss` connection +//! and is using RPC methods to get required data and submit transactions. + +use crate::{ + client::{ + rpc_api::{ + SubstrateAuthorClient, SubstrateBeefyClient, SubstrateChainClient, + SubstrateFrameSystemClient, SubstrateGrandpaClient, SubstrateStateClient, + SubstrateSystemClient, + }, + subscription::{StreamDescription, Subscription}, + Client, + }, + error::{Error, Result}, + guard::Environment, + transaction_stall_timeout, AccountIdOf, AccountKeyPairOf, BalanceOf, BlockNumberOf, Chain, + ChainRuntimeVersion, ChainWithGrandpa, ChainWithTransactions, ConnectionParams, HashOf, + HeaderIdOf, HeaderOf, NonceOf, SignParam, SignedBlockOf, SimpleRuntimeVersion, + TransactionTracker, UnsignedTransaction, +}; + +use async_std::sync::{Arc, Mutex, RwLock}; +use async_trait::async_trait; +use bp_runtime::HeaderIdProvider; +use codec::Encode; +use frame_support::weights::Weight; +use futures::TryFutureExt; +use jsonrpsee::{ + core::{client::Subscription as RpcSubscription, ClientError}, + ws_client::{WsClient, WsClientBuilder}, +}; +use num_traits::Zero; +use pallet_transaction_payment::RuntimeDispatchInfo; +use relay_utils::{relay_loop::RECONNECT_DELAY, STALL_TIMEOUT}; +use sp_core::{ + storage::{StorageData, StorageKey}, + Bytes, Hasher, Pair, +}; +use sp_runtime::transaction_validity::{TransactionSource, TransactionValidity}; +use sp_trie::StorageProof; +use sp_version::RuntimeVersion; +use std::{cmp::Ordering, future::Future, marker::PhantomData}; + +const MAX_SUBSCRIPTION_CAPACITY: usize = 4096; + +const SUB_API_TXPOOL_VALIDATE_TRANSACTION: &str = "TaggedTransactionQueue_validate_transaction"; +const SUB_API_TX_PAYMENT_QUERY_INFO: &str = "TransactionPaymentApi_query_info"; +const SUB_API_GRANDPA_GENERATE_KEY_OWNERSHIP_PROOF: &str = + "GrandpaApi_generate_key_ownership_proof"; + +/// Client implementation that connects to the Substrate node over `ws`/`wss` connection +/// and is using RPC methods to get required data and submit transactions. +pub struct RpcClient { + // Lock order: `submit_signed_extrinsic_lock`, `data` + /// Client connection params. + params: Arc, + /// If several tasks are submitting their transactions simultaneously using + /// `submit_signed_extrinsic` method, they may get the same transaction nonce. So one of + /// transactions will be rejected from the pool. This lock is here to prevent situations like + /// that. + submit_signed_extrinsic_lock: Arc>, + /// Genesis block hash. + genesis_hash: HashOf, + /// Shared dynamic data. + data: Arc>, + /// Generic arguments dump. + _phantom: PhantomData, +} + +/// Client data, shared by all `RpcClient` clones. +struct ClientData { + /// Tokio runtime handle. + tokio: Arc, + /// Substrate RPC client. + client: Arc, +} + +/// Already encoded value. +struct PreEncoded(Vec); + +impl Encode for PreEncoded { + fn encode(&self) -> Vec { + self.0.clone() + } +} + +impl std::fmt::Debug for RpcClient { + fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result { + fmt.write_fmt(format_args!("RpcClient<{}>", C::NAME)) + } +} + +impl RpcClient { + /// Returns client that is able to call RPCs on Substrate node over websocket connection. + /// + /// This function will keep connecting to given Substrate node until connection is established + /// and is functional. If attempt fail, it will wait for `RECONNECT_DELAY` and retry again. + pub async fn new(params: ConnectionParams) -> Self { + let params = Arc::new(params); + loop { + match Self::try_connect(params.clone()).await { + Ok(client) => return client, + Err(error) => log::error!( + target: "bridge", + "Failed to connect to {} node: {:?}. Going to retry in {}s", + C::NAME, + error, + RECONNECT_DELAY.as_secs(), + ), + } + + async_std::task::sleep(RECONNECT_DELAY).await; + } + } + + /// Try to connect to Substrate node over websocket. Returns Substrate RPC client if connection + /// has been established or error otherwise. + async fn try_connect(params: Arc) -> Result { + let (tokio, client) = Self::build_client(¶ms).await?; + + let genesis_hash_client = client.clone(); + let genesis_hash = tokio + .spawn(async move { + SubstrateChainClient::::block_hash(&*genesis_hash_client, Some(Zero::zero())) + .await + }) + .await??; + + let chain_runtime_version = params.chain_runtime_version; + let mut client = Self { + params, + submit_signed_extrinsic_lock: Arc::new(Mutex::new(())), + genesis_hash, + data: Arc::new(RwLock::new(ClientData { tokio, client })), + _phantom: PhantomData, + }; + Self::ensure_correct_runtime_version(&mut client, chain_runtime_version).await?; + Ok(client) + } + + // Check runtime version to understand if we need are connected to expected version, or we + // need to wait for upgrade, we need to abort immediately. + async fn ensure_correct_runtime_version>( + env: &mut E, + expected: ChainRuntimeVersion, + ) -> Result<()> { + // we are only interested if version mode is bundled or passed using CLI + let expected = match expected { + ChainRuntimeVersion::Auto => return Ok(()), + ChainRuntimeVersion::Custom(expected) => expected, + }; + + // we need to wait if actual version is < than expected, we are OK of versions are the + // same and we need to abort if actual version is > than expected + let actual = SimpleRuntimeVersion::from_runtime_version(&env.runtime_version().await?); + match actual.spec_version.cmp(&expected.spec_version) { + Ordering::Less => + Err(Error::WaitingForRuntimeUpgrade { chain: C::NAME.into(), expected, actual }), + Ordering::Equal => Ok(()), + Ordering::Greater => { + log::error!( + target: "bridge", + "The {} client is configured to use runtime version {expected:?} and actual \ + version is {actual:?}. Aborting", + C::NAME, + ); + env.abort().await; + Err(Error::Custom("Aborted".into())) + }, + } + } + + /// Build client to use in connection. + async fn build_client( + params: &ConnectionParams, + ) -> Result<(Arc, Arc)> { + let tokio = tokio::runtime::Runtime::new()?; + let uri = match params.uri { + Some(ref uri) => uri.clone(), + None => { + format!( + "{}://{}:{}{}", + if params.secure { "wss" } else { "ws" }, + params.host, + params.port, + match params.path { + Some(ref path) => format!("/{}", path), + None => String::new(), + }, + ) + }, + }; + log::info!(target: "bridge", "Connecting to {} node at {}", C::NAME, uri); + + let client = tokio + .spawn(async move { + WsClientBuilder::default() + .max_buffer_capacity_per_subscription(MAX_SUBSCRIPTION_CAPACITY) + .build(&uri) + .await + }) + .await??; + + Ok((Arc::new(tokio), Arc::new(client))) + } + + /// Execute jsonrpsee future in tokio context. + async fn jsonrpsee_execute(&self, make_jsonrpsee_future: MF) -> Result + where + MF: FnOnce(Arc) -> F + Send + 'static, + F: Future> + Send + 'static, + T: Send + 'static, + { + let data = self.data.read().await; + let client = data.client.clone(); + data.tokio.spawn(make_jsonrpsee_future(client)).await? + } + + /// Prepare parameters used to sign chain transactions. + async fn build_sign_params(&self, signer: AccountKeyPairOf) -> Result> + where + C: ChainWithTransactions, + { + let runtime_version = self.simple_runtime_version().await?; + Ok(SignParam:: { + spec_version: runtime_version.spec_version, + transaction_version: runtime_version.transaction_version, + genesis_hash: self.genesis_hash, + signer, + }) + } + + /// Get the nonce of the given Substrate account. + pub async fn next_account_index(&self, account: AccountIdOf) -> Result> { + self.jsonrpsee_execute(move |client| async move { + Ok(SubstrateFrameSystemClient::::account_next_index(&*client, account).await?) + }) + .await + } + + /// Subscribe to finality justifications. + async fn subscribe_finality_justifications( + &self, + gadget_name: &str, + do_subscribe: impl FnOnce(Arc) -> Fut + Send + 'static, + ) -> Result> + where + Fut: Future, ClientError>> + Send, + { + let subscription = self + .jsonrpsee_execute(move |client| async move { Ok(do_subscribe(client).await?) }) + .map_err(|e| Error::failed_to_subscribe_justification::(e)) + .await?; + + Ok(Subscription::new_forwarded( + StreamDescription::new(format!("{} justifications", gadget_name), C::NAME.into()), + subscription, + )) + } + + /// Subscribe to headers stream. + async fn subscribe_headers( + &self, + stream_name: &str, + do_subscribe: impl FnOnce(Arc) -> Fut + Send + 'static, + map_err: impl FnOnce(Error) -> Error, + ) -> Result>> + where + Fut: Future>, ClientError>> + Send, + { + let subscription = self + .jsonrpsee_execute(move |client| async move { Ok(do_subscribe(client).await?) }) + .map_err(map_err) + .await?; + + Ok(Subscription::new_forwarded( + StreamDescription::new(format!("{} headers", stream_name), C::NAME.into()), + subscription, + )) + } +} + +impl Clone for RpcClient { + fn clone(&self) -> Self { + RpcClient { + params: self.params.clone(), + submit_signed_extrinsic_lock: self.submit_signed_extrinsic_lock.clone(), + genesis_hash: self.genesis_hash, + data: self.data.clone(), + _phantom: PhantomData, + } + } +} + +#[async_trait] +impl Client for RpcClient { + async fn ensure_synced(&self) -> Result<()> { + let health = self + .jsonrpsee_execute(|client| async move { + Ok(SubstrateSystemClient::::health(&*client).await?) + }) + .await + .map_err(|e| Error::failed_to_get_system_health::(e))?; + + let is_synced = !health.is_syncing && (!health.should_have_peers || health.peers > 0); + if is_synced { + Ok(()) + } else { + Err(Error::ClientNotSynced(health)) + } + } + + async fn reconnect(&self) -> Result<()> { + let mut data = self.data.write().await; + let (tokio, client) = Self::build_client(&self.params).await?; + data.tokio = tokio; + data.client = client; + Ok(()) + } + + fn genesis_hash(&self) -> HashOf { + self.genesis_hash + } + + async fn header_hash_by_number(&self, number: BlockNumberOf) -> Result> { + self.jsonrpsee_execute(move |client| async move { + Ok(SubstrateChainClient::::block_hash(&*client, Some(number)).await?) + }) + .await + .map_err(|e| Error::failed_to_read_header_hash_by_number::(number, e)) + } + + async fn header_by_hash(&self, hash: HashOf) -> Result> { + self.jsonrpsee_execute(move |client| async move { + Ok(SubstrateChainClient::::header(&*client, Some(hash)).await?) + }) + .await + .map_err(|e| Error::failed_to_read_header_by_hash::(hash, e)) + } + + async fn block_by_hash(&self, hash: HashOf) -> Result> { + self.jsonrpsee_execute(move |client| async move { + Ok(SubstrateChainClient::::block(&*client, Some(hash)).await?) + }) + .await + .map_err(|e| Error::failed_to_read_block_by_hash::(hash, e)) + } + + async fn best_finalized_header_hash(&self) -> Result> { + self.jsonrpsee_execute(|client| async move { + Ok(SubstrateChainClient::::finalized_head(&*client).await?) + }) + .await + .map_err(|e| Error::failed_to_read_best_finalized_header_hash::(e)) + } + + async fn best_header(&self) -> Result> { + self.jsonrpsee_execute(|client| async move { + Ok(SubstrateChainClient::::header(&*client, None).await?) + }) + .await + .map_err(|e| Error::failed_to_read_best_header::(e)) + } + + async fn subscribe_best_headers(&self) -> Result>> { + self.subscribe_headers( + "best headers", + move |client| async move { SubstrateChainClient::::subscribe_new_heads(&*client).await }, + |e| Error::failed_to_subscribe_best_headers::(e), + ) + .await + } + + async fn subscribe_finalized_headers(&self) -> Result>> { + self.subscribe_headers( + "best finalized headers", + move |client| async move { + SubstrateChainClient::::subscribe_finalized_heads(&*client).await + }, + |e| Error::failed_to_subscribe_finalized_headers::(e), + ) + .await + } + + async fn subscribe_grandpa_finality_justifications(&self) -> Result> + where + C: ChainWithGrandpa, + { + self.subscribe_finality_justifications("GRANDPA", move |client| async move { + SubstrateGrandpaClient::::subscribe_justifications(&*client).await + }) + .await + } + + async fn generate_grandpa_key_ownership_proof( + &self, + at: HashOf, + set_id: sp_consensus_grandpa::SetId, + authority_id: sp_consensus_grandpa::AuthorityId, + ) -> Result> { + self.state_call( + at, + SUB_API_GRANDPA_GENERATE_KEY_OWNERSHIP_PROOF.into(), + (set_id, authority_id), + ) + .await + } + + async fn subscribe_beefy_finality_justifications(&self) -> Result> { + self.subscribe_finality_justifications("BEEFY", move |client| async move { + SubstrateBeefyClient::::subscribe_justifications(&*client).await + }) + .await + } + + async fn token_decimals(&self) -> Result> { + self.jsonrpsee_execute(move |client| async move { + let system_properties = SubstrateSystemClient::::properties(&*client).await?; + Ok(system_properties.get("tokenDecimals").and_then(|v| v.as_u64())) + }) + .await + } + + async fn runtime_version(&self) -> Result { + self.jsonrpsee_execute(move |client| async move { + Ok(SubstrateStateClient::::runtime_version(&*client).await?) + }) + .await + .map_err(|e| Error::failed_to_read_runtime_version::(e)) + } + + async fn simple_runtime_version(&self) -> Result { + Ok(match self.params.chain_runtime_version { + ChainRuntimeVersion::Auto => { + let runtime_version = self.runtime_version().await?; + SimpleRuntimeVersion::from_runtime_version(&runtime_version) + }, + ChainRuntimeVersion::Custom(ref version) => *version, + }) + } + + fn can_start_version_guard(&self) -> bool { + !matches!(self.params.chain_runtime_version, ChainRuntimeVersion::Auto) + } + + async fn raw_storage_value( + &self, + at: HashOf, + storage_key: StorageKey, + ) -> Result> { + let cloned_storage_key = storage_key.clone(); + self.jsonrpsee_execute(move |client| async move { + Ok(SubstrateStateClient::::storage(&*client, cloned_storage_key, Some(at)).await?) + }) + .await + .map_err(|e| Error::failed_to_read_storage_value::(at, storage_key, e)) + } + + async fn pending_extrinsics(&self) -> Result> { + self.jsonrpsee_execute(move |client| async move { + Ok(SubstrateAuthorClient::::pending_extrinsics(&*client).await?) + }) + .await + .map_err(|e| Error::failed_to_get_pending_extrinsics::(e)) + } + + async fn submit_unsigned_extrinsic(&self, transaction: Bytes) -> Result> { + // one last check that the transaction is valid. Most of checks happen in the relay loop and + // it is the "final" check before submission. + let best_header_hash = self.best_header_hash().await?; + self.validate_transaction(best_header_hash, PreEncoded(transaction.0.clone())) + .await + .map_err(|e| Error::failed_to_submit_transaction::(e))? + .map_err(|e| Error::failed_to_submit_transaction::(Error::TransactionInvalid(e)))?; + + self.jsonrpsee_execute(move |client| async move { + let tx_hash = SubstrateAuthorClient::::submit_extrinsic(&*client, transaction) + .await + .map_err(|e| { + log::error!(target: "bridge", "Failed to send transaction to {} node: {:?}", C::NAME, e); + e + })?; + log::trace!(target: "bridge", "Sent transaction to {} node: {:?}", C::NAME, tx_hash); + Ok(tx_hash) + }) + .await + .map_err(|e| Error::failed_to_submit_transaction::(e)) + } + + async fn submit_signed_extrinsic( + &self, + signer: &AccountKeyPairOf, + prepare_extrinsic: impl FnOnce(HeaderIdOf, NonceOf) -> Result> + + Send + + 'static, + ) -> Result> + where + C: ChainWithTransactions, + AccountIdOf: From< as Pair>::Public>, + { + let _guard = self.submit_signed_extrinsic_lock.lock().await; + let transaction_nonce = self.next_account_index(signer.public().into()).await?; + let best_header = self.best_header().await?; + let signing_data = self.build_sign_params(signer.clone()).await?; + + // By using parent of best block here, we are protecting again best-block reorganizations. + // E.g. transaction may have been submitted when the best block was `A[num=100]`. Then it + // has been changed to `B[num=100]`. Hash of `A` has been included into transaction + // signature payload. So when signature will be checked, the check will fail and transaction + // will be dropped from the pool. + let best_header_id = best_header.parent_id().unwrap_or_else(|| best_header.id()); + + let extrinsic = prepare_extrinsic(best_header_id, transaction_nonce)?; + let signed_extrinsic = C::sign_transaction(signing_data, extrinsic)?.encode(); + self.submit_unsigned_extrinsic(Bytes(signed_extrinsic)).await + } + + async fn submit_and_watch_signed_extrinsic( + &self, + signer: &AccountKeyPairOf, + prepare_extrinsic: impl FnOnce(HeaderIdOf, NonceOf) -> Result> + + Send + + 'static, + ) -> Result> + where + C: ChainWithTransactions, + AccountIdOf: From< as Pair>::Public>, + { + let self_clone = self.clone(); + let signing_data = self.build_sign_params(signer.clone()).await?; + let _guard = self.submit_signed_extrinsic_lock.lock().await; + let transaction_nonce = self.next_account_index(signer.public().into()).await?; + let best_header = self.best_header().await?; + let best_header_id = best_header.id(); + + let extrinsic = prepare_extrinsic(best_header_id, transaction_nonce)?; + let stall_timeout = transaction_stall_timeout( + extrinsic.era.mortality_period(), + C::AVERAGE_BLOCK_INTERVAL, + STALL_TIMEOUT, + ); + let signed_extrinsic = C::sign_transaction(signing_data, extrinsic)?.encode(); + + // one last check that the transaction is valid. Most of checks happen in the relay loop and + // it is the "final" check before submission. + self.validate_transaction(best_header_id.hash(), PreEncoded(signed_extrinsic.clone())) + .await + .map_err(|e| Error::failed_to_submit_transaction::(e))? + .map_err(|e| Error::failed_to_submit_transaction::(Error::TransactionInvalid(e)))?; + + self.jsonrpsee_execute(move |client| async move { + let tx_hash = C::Hasher::hash(&signed_extrinsic); + let subscription: jsonrpsee::core::client::Subscription<_> = + SubstrateAuthorClient::::submit_and_watch_extrinsic( + &*client, + Bytes(signed_extrinsic), + ) + .await + .map_err(|e| { + log::error!(target: "bridge", "Failed to send transaction to {} node: {:?}", C::NAME, e); + e + })?; + log::trace!(target: "bridge", "Sent transaction to {} node: {:?}", C::NAME, tx_hash); + Ok(TransactionTracker::new( + self_clone, + stall_timeout, + tx_hash, + Subscription::new_forwarded( + StreamDescription::new("transaction events".into(), C::NAME.into()), + subscription, + ), + )) + }) + .await + .map_err(|e| Error::failed_to_submit_transaction::(e)) + } + + async fn validate_transaction( + &self, + at: HashOf, + transaction: SignedTransaction, + ) -> Result { + self.state_call( + at, + SUB_API_TXPOOL_VALIDATE_TRANSACTION.into(), + (TransactionSource::External, transaction, at), + ) + .await + } + + async fn estimate_extrinsic_weight( + &self, + at: HashOf, + transaction: SignedTransaction, + ) -> Result { + let transaction_len = transaction.encoded_size() as u32; + let dispatch_info: RuntimeDispatchInfo> = self + .state_call(at, SUB_API_TX_PAYMENT_QUERY_INFO.into(), (transaction, transaction_len)) + .await?; + + Ok(dispatch_info.weight) + } + + async fn raw_state_call( + &self, + at: HashOf, + method: String, + arguments: Args, + ) -> Result { + let arguments = Bytes(arguments.encode()); + let arguments_clone = arguments.clone(); + let method_clone = method.clone(); + self.jsonrpsee_execute(move |client| async move { + SubstrateStateClient::::call(&*client, method, arguments, Some(at)) + .await + .map_err(Into::into) + }) + .await + .map_err(|e| Error::failed_state_call::(at, method_clone, arguments_clone, e)) + } + + async fn prove_storage(&self, at: HashOf, keys: Vec) -> Result { + 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)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{guard::tests::TestEnvironment, test_chain::TestChain}; + use futures::{channel::mpsc::unbounded, FutureExt, SinkExt, StreamExt}; + + async fn run_ensure_correct_runtime_version( + expected: ChainRuntimeVersion, + actual: RuntimeVersion, + ) -> Result<()> { + let ( + (mut runtime_version_tx, runtime_version_rx), + (slept_tx, _slept_rx), + (aborted_tx, mut aborted_rx), + ) = (unbounded(), unbounded(), unbounded()); + runtime_version_tx.send(actual).await.unwrap(); + let mut env = TestEnvironment { runtime_version_rx, slept_tx, aborted_tx }; + + let ensure_correct_runtime_version = + RpcClient::::ensure_correct_runtime_version(&mut env, expected).boxed(); + let aborted = aborted_rx.next().map(|_| Err(Error::Custom("".into()))).boxed(); + futures::pin_mut!(ensure_correct_runtime_version, aborted); + futures::future::select(ensure_correct_runtime_version, aborted) + .await + .into_inner() + .0 + } + + #[async_std::test] + async fn ensure_correct_runtime_version_works() { + // when we are configured to use auto version + assert!(matches!( + run_ensure_correct_runtime_version( + ChainRuntimeVersion::Auto, + RuntimeVersion { + spec_version: 100, + transaction_version: 100, + ..Default::default() + }, + ) + .await, + Ok(()), + )); + // when actual == expected + assert!(matches!( + run_ensure_correct_runtime_version( + ChainRuntimeVersion::Custom(SimpleRuntimeVersion { + spec_version: 100, + transaction_version: 100 + }), + RuntimeVersion { + spec_version: 100, + transaction_version: 100, + ..Default::default() + }, + ) + .await, + Ok(()), + )); + // when actual spec version < expected spec version + assert!(matches!( + run_ensure_correct_runtime_version( + ChainRuntimeVersion::Custom(SimpleRuntimeVersion { + spec_version: 100, + transaction_version: 100 + }), + RuntimeVersion { spec_version: 99, transaction_version: 100, ..Default::default() }, + ) + .await, + Err(Error::WaitingForRuntimeUpgrade { + expected: SimpleRuntimeVersion { spec_version: 100, transaction_version: 100 }, + actual: SimpleRuntimeVersion { spec_version: 99, transaction_version: 100 }, + .. + }), + )); + // when actual spec version > expected spec version + assert!(matches!( + run_ensure_correct_runtime_version( + ChainRuntimeVersion::Custom(SimpleRuntimeVersion { + spec_version: 100, + transaction_version: 100 + }), + RuntimeVersion { + spec_version: 101, + transaction_version: 100, + ..Default::default() + }, + ) + .await, + Err(Error::Custom(_)), + )); + } +} diff --git a/bridges/relays/client-substrate/src/rpc.rs b/bridges/relays/client-substrate/src/client/rpc_api.rs similarity index 80% rename from bridges/relays/client-substrate/src/rpc.rs rename to bridges/relays/client-substrate/src/client/rpc_api.rs index 60c29cdeb5c7707619b65d23800dcd7dfdfd840a..9cac69f7a13d06bf772fb9493520113d8e066681 100644 --- a/bridges/relays/client-substrate/src/rpc.rs +++ b/bridges/relays/client-substrate/src/client/rpc_api.rs @@ -16,15 +16,9 @@ //! The most generic Substrate node RPC interface. -use async_trait::async_trait; - use crate::{Chain, ChainWithGrandpa, TransactionStatusOf}; -use jsonrpsee::{ - core::{client::Subscription, ClientError}, - proc_macros::rpc, - ws_client::WsClient, -}; +use jsonrpsee::proc_macros::rpc; use pallet_transaction_payment_rpc_runtime_api::FeeDetails; use sc_rpc_api::{state::ReadProof, system::Health}; use sp_core::{ @@ -60,6 +54,20 @@ pub(crate) trait SubstrateChain { /// Return signed block (with justifications) by its hash. #[method(name = "getBlock")] async fn block(&self, block_hash: Option) -> RpcResult; + /// Subscribe to best headers. + #[subscription( + name = "subscribeNewHeads" => "newHead", + unsubscribe = "unsubscribeNewHeads", + item = C::Header + )] + async fn subscribe_new_heads(&self); + /// Subscribe to finalized headers. + #[subscription( + name = "subscribeFinalizedHeads" => "finalizedHead", + unsubscribe = "unsubscribeFinalizedHeads", + item = C::Header + )] + async fn subscribe_finalized_heads(&self); } /// RPC methods of Substrate `author` namespace, that we are using. @@ -106,15 +114,6 @@ pub(crate) trait SubstrateState { ) -> RpcResult>; } -/// RPC methods that we are using for a certain finality gadget. -#[async_trait] -pub trait SubstrateFinalityClient { - /// Subscribe to finality justifications. - async fn subscribe_justifications( - client: &WsClient, - ) -> Result, ClientError>; -} - /// RPC methods of Substrate `grandpa` namespace, that we are using. #[rpc(client, client_bounds(C: ChainWithGrandpa), namespace = "grandpa")] pub(crate) trait SubstrateGrandpa { @@ -123,17 +122,6 @@ pub(crate) trait SubstrateGrandpa { async fn subscribe_justifications(&self); } -/// RPC finality methods of Substrate `grandpa` namespace, that we are using. -pub struct SubstrateGrandpaFinalityClient; -#[async_trait] -impl SubstrateFinalityClient for SubstrateGrandpaFinalityClient { - async fn subscribe_justifications( - client: &WsClient, - ) -> Result, ClientError> { - SubstrateGrandpaClient::::subscribe_justifications(client).await - } -} - // TODO: Use `ChainWithBeefy` instead of `Chain` after #1606 is merged /// RPC methods of Substrate `beefy` namespace, that we are using. #[rpc(client, client_bounds(C: Chain), namespace = "beefy")] @@ -143,18 +131,6 @@ pub(crate) trait SubstrateBeefy { async fn subscribe_justifications(&self); } -/// RPC finality methods of Substrate `beefy` namespace, that we are using. -pub struct SubstrateBeefyFinalityClient; -// TODO: Use `ChainWithBeefy` instead of `Chain` after #1606 is merged -#[async_trait] -impl SubstrateFinalityClient for SubstrateBeefyFinalityClient { - async fn subscribe_justifications( - client: &WsClient, - ) -> Result, ClientError> { - SubstrateBeefyClient::::subscribe_justifications(client).await - } -} - /// RPC methods of Substrate `system` frame pallet, that we are using. #[rpc(client, client_bounds(C: Chain), namespace = "system")] pub(crate) trait SubstrateFrameSystem { diff --git a/bridges/relays/client-substrate/src/client/subscription.rs b/bridges/relays/client-substrate/src/client/subscription.rs new file mode 100644 index 0000000000000000000000000000000000000000..9f08097cb583a57a28885a7aa59a1731e997d023 --- /dev/null +++ b/bridges/relays/client-substrate/src/client/subscription.rs @@ -0,0 +1,238 @@ +// 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 . + +use crate::error::Result as ClientResult; + +use async_std::{ + channel::{bounded, Receiver, Sender}, + stream::StreamExt, +}; +use futures::{FutureExt, Stream}; +use sp_runtime::DeserializeOwned; +use std::{ + fmt::Debug, + pin::Pin, + result::Result as StdResult, + task::{Context, Poll}, +}; + +/// Once channel reaches this capacity, the subscription breaks. +const CHANNEL_CAPACITY: usize = 128; + +/// Structure describing a stream. +#[derive(Clone)] +pub struct StreamDescription { + stream_name: String, + chain_name: String, +} + +impl StreamDescription { + /// Create a new instance of `StreamDescription`. + pub fn new(stream_name: String, chain_name: String) -> Self { + Self { stream_name, chain_name } + } + + /// Get a stream description. + fn get(&self) -> String { + format!("{} stream of {}", self.stream_name, self.chain_name) + } +} + +/// Chainable stream that transforms items of type `Result` to items of type `T`. +/// +/// If it encounters an item of type `Err`, it returns `Poll::Ready(None)` +/// and terminates the underlying stream. +struct Unwrap>, T, E> { + desc: StreamDescription, + stream: Option, +} + +impl>, T, E> Unwrap { + /// Create a new instance of `Unwrap`. + pub fn new(desc: StreamDescription, stream: S) -> Self { + Self { desc, stream: Some(stream) } + } +} + +impl> + Unpin, T: DeserializeOwned, E: Debug> Stream + for Unwrap +{ + type Item = T; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Poll::Ready(match self.stream.as_mut() { + Some(subscription) => match futures::ready!(Pin::new(subscription).poll_next(cx)) { + Some(Ok(item)) => Some(item), + Some(Err(e)) => { + self.stream.take(); + log::debug!( + target: "bridge", + "{} has returned error: {:?}. It may need to be restarted", + self.desc.get(), + e, + ); + None + }, + None => { + self.stream.take(); + log::debug!( + target: "bridge", + "{} has returned `None`. It may need to be restarted", + self.desc.get() + ); + None + }, + }, + None => None, + }) + } +} + +/// Subscription factory that produces subscriptions, sharing the same background thread. +#[derive(Clone)] +pub struct SubscriptionBroadcaster { + desc: StreamDescription, + subscribers_sender: Sender>, +} + +impl SubscriptionBroadcaster { + /// Create new subscription factory. + pub fn new(subscription: Subscription) -> StdResult> { + // It doesn't make sense to further broadcast a broadcasted subscription. + if subscription.is_broadcasted { + return Err(subscription) + } + + let desc = subscription.desc().clone(); + let (subscribers_sender, subscribers_receiver) = bounded(CHANNEL_CAPACITY); + async_std::task::spawn(background_worker(subscription, subscribers_receiver)); + Ok(Self { desc, subscribers_sender }) + } + + /// Produce new subscription. + pub async fn subscribe(&self) -> ClientResult> { + let (items_sender, items_receiver) = bounded(CHANNEL_CAPACITY); + self.subscribers_sender.try_send(items_sender)?; + + Ok(Subscription::new_broadcasted(self.desc.clone(), items_receiver)) + } +} + +/// Subscription to some chain events. +pub struct Subscription { + desc: StreamDescription, + subscription: Box + Unpin + Send>, + is_broadcasted: bool, +} + +impl Subscription { + /// Create new forwarded subscription. + pub fn new_forwarded( + desc: StreamDescription, + subscription: impl Stream> + Unpin + Send + 'static, + ) -> Self { + Self { + desc: desc.clone(), + subscription: Box::new(Unwrap::new(desc, subscription)), + is_broadcasted: false, + } + } + + /// Create new broadcasted subscription. + pub fn new_broadcasted( + desc: StreamDescription, + subscription: impl Stream + Unpin + Send + 'static, + ) -> Self { + Self { desc, subscription: Box::new(subscription), is_broadcasted: true } + } + + /// Get the description of the underlying stream + pub fn desc(&self) -> &StreamDescription { + &self.desc + } +} + +impl Stream for Subscription { + type Item = T; + + fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll> { + Poll::Ready(futures::ready!(Pin::new(&mut self.subscription).poll_next(cx))) + } +} + +/// Background worker that is executed in tokio context as `jsonrpsee` requires. +/// +/// This task may exit under some circumstances. It'll send the correspondent +/// message (`Err` or `None`) to all known listeners. Also, when it stops, all +/// subsequent reads and new subscribers will get the connection error (`ChannelError`). +async fn background_worker( + mut subscription: Subscription, + mut subscribers_receiver: Receiver>, +) { + fn log_task_exit(desc: &StreamDescription, reason: &str) { + log::debug!( + target: "bridge", + "Background task of subscription broadcaster for {} has stopped: {}", + desc.get(), + reason, + ); + } + + // wait for first subscriber until actually starting subscription + let subscriber = match subscribers_receiver.next().await { + Some(subscriber) => subscriber, + None => { + // it means that the last subscriber/factory has been dropped, so we need to + // exit too + return log_task_exit(subscription.desc(), "client has stopped") + }, + }; + + // actually subscribe + let mut subscribers = vec![subscriber]; + + // start listening for new items and receivers + loop { + futures::select! { + subscriber = subscribers_receiver.next().fuse() => { + match subscriber { + Some(subscriber) => subscribers.push(subscriber), + None => { + // it means that the last subscriber/factory has been dropped, so we need to + // exit too + return log_task_exit(subscription.desc(), "client has stopped") + }, + } + }, + maybe_item = subscription.subscription.next().fuse() => { + match maybe_item { + Some(item) => { + // notify subscribers + subscribers.retain(|subscriber| { + let send_result = subscriber.try_send(item.clone()); + send_result.is_ok() + }); + } + None => { + // The underlying client has dropped, so we can't do anything here + // and need to stop the task. + return log_task_exit(subscription.desc(), "stream has finished"); + } + } + }, + } + } +} diff --git a/bridges/relays/client-substrate/src/client/traits.rs b/bridges/relays/client-substrate/src/client/traits.rs new file mode 100644 index 0000000000000000000000000000000000000000..49f5c001c3f7d80fd51892c8de73f41960557cba --- /dev/null +++ b/bridges/relays/client-substrate/src/client/traits.rs @@ -0,0 +1,230 @@ +// 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 . + +use crate::{ + error::{Error, Result}, + AccountIdOf, AccountKeyPairOf, BlockNumberOf, Chain, ChainWithGrandpa, ChainWithTransactions, + HashOf, HeaderIdOf, HeaderOf, NonceOf, SignedBlockOf, SimpleRuntimeVersion, Subscription, + TransactionTracker, UnsignedTransaction, +}; + +use async_trait::async_trait; +use bp_runtime::{StorageDoubleMapKeyProvider, StorageMapKeyProvider}; +use codec::{Decode, Encode}; +use frame_support::weights::Weight; +use sp_core::{ + storage::{StorageData, StorageKey}, + Bytes, Pair, +}; +use sp_runtime::{traits::Header as _, transaction_validity::TransactionValidity}; +use sp_trie::StorageProof; +use sp_version::RuntimeVersion; +use std::fmt::Debug; + +/// Relay uses the `Client` to communicate with the node, connected to Substrate +/// chain `C`. +#[async_trait] +pub trait Client: 'static + Send + Sync + Clone + Debug { + /// Returns error if client has no connected peers or it believes it is far + /// behind the chain tip. + async fn ensure_synced(&self) -> Result<()>; + /// Reconnects the client. + async fn reconnect(&self) -> Result<()>; + + /// Return hash of the genesis block. + fn genesis_hash(&self) -> HashOf; + /// Get header hash by number. + async fn header_hash_by_number(&self, number: BlockNumberOf) -> Result>; + /// Get header by hash. + async fn header_by_hash(&self, hash: HashOf) -> Result>; + /// Get header by number. + async fn header_by_number(&self, number: BlockNumberOf) -> Result> { + self.header_by_hash(self.header_hash_by_number(number).await?).await + } + /// Get block by hash. + async fn block_by_hash(&self, hash: HashOf) -> Result>; + + /// Get best finalized header hash. + async fn best_finalized_header_hash(&self) -> Result>; + /// Get best finalized header number. + async fn best_finalized_header_number(&self) -> Result> { + Ok(*self.best_finalized_header().await?.number()) + } + /// Get best finalized header. + async fn best_finalized_header(&self) -> Result> { + self.header_by_hash(self.best_finalized_header_hash().await?).await + } + + /// Get best header. + async fn best_header(&self) -> Result>; + /// Get best header hash. + async fn best_header_hash(&self) -> Result> { + Ok(self.best_header().await?.hash()) + } + + /// Subscribe to new best headers. + async fn subscribe_best_headers(&self) -> Result>>; + /// Subscribe to new finalized headers. + async fn subscribe_finalized_headers(&self) -> Result>>; + + /// Subscribe to GRANDPA finality justifications. + async fn subscribe_grandpa_finality_justifications(&self) -> Result> + where + C: ChainWithGrandpa; + /// Generates a proof of key ownership for the given authority in the given set. + async fn generate_grandpa_key_ownership_proof( + &self, + at: HashOf, + set_id: sp_consensus_grandpa::SetId, + authority_id: sp_consensus_grandpa::AuthorityId, + ) -> Result>; + + /// Subscribe to BEEFY finality justifications. + async fn subscribe_beefy_finality_justifications(&self) -> Result>; + + /// Return `tokenDecimals` property from the set of chain properties. + async fn token_decimals(&self) -> Result>; + /// Get runtime version of the connected chain. + async fn runtime_version(&self) -> Result; + /// Get partial runtime version, to use when signing transactions. + async fn simple_runtime_version(&self) -> Result; + /// Returns `true` if version guard can be started. + /// + /// There's no reason to run version guard when version mode is set to `Auto`. It can + /// lead to relay shutdown when chain is upgraded, even though we have explicitly + /// said that we don't want to shutdown. + fn can_start_version_guard(&self) -> bool; + + /// Read raw value from runtime storage. + async fn raw_storage_value( + &self, + at: HashOf, + storage_key: StorageKey, + ) -> Result>; + /// Read and decode value from runtime storage. + async fn storage_value( + &self, + at: HashOf, + storage_key: StorageKey, + ) -> Result> { + self.raw_storage_value(at, storage_key.clone()) + .await? + .map(|encoded_value| { + T::decode(&mut &encoded_value.0[..]).map_err(|e| { + Error::failed_to_read_storage_value::(at, storage_key, e.into()) + }) + }) + .transpose() + } + /// Read and decode value from runtime storage map. + /// + /// `pallet_prefix` is the name of the pallet (used in `construct_runtime`), which + /// "contains" the storage map. + async fn storage_map_value( + &self, + at: HashOf, + pallet_prefix: &str, + storage_key: &T::Key, + ) -> Result> { + self.storage_value(at, T::final_key(pallet_prefix, storage_key)).await + } + /// Read and decode value from runtime storage double map. + /// + /// `pallet_prefix` is the name of the pallet (used in `construct_runtime`), which + /// "contains" the storage double map. + async fn storage_double_map_value( + &self, + at: HashOf, + pallet_prefix: &str, + key1: &T::Key1, + key2: &T::Key2, + ) -> Result> { + self.storage_value(at, T::final_key(pallet_prefix, key1, key2)).await + } + + /// Returns pending extrinsics from transaction pool. + async fn pending_extrinsics(&self) -> Result>; + /// Submit unsigned extrinsic for inclusion in a block. + /// + /// Note: The given transaction needs to be SCALE encoded beforehand. + async fn submit_unsigned_extrinsic(&self, transaction: Bytes) -> Result>; + /// Submit an extrinsic signed by given account. + /// + /// All calls of this method are synchronized, so there can't be more than one active + /// `submit_signed_extrinsic()` call. This guarantees that no nonces collision may happen + /// if all client instances are clones of the same initial `Client`. + /// + /// Note: The given transaction needs to be SCALE encoded beforehand. + async fn submit_signed_extrinsic( + &self, + signer: &AccountKeyPairOf, + prepare_extrinsic: impl FnOnce(HeaderIdOf, NonceOf) -> Result> + + Send + + 'static, + ) -> Result> + where + C: ChainWithTransactions, + AccountIdOf: From< as Pair>::Public>; + /// Does exactly the same as `submit_signed_extrinsic`, but keeps watching for extrinsic status + /// after submission. + async fn submit_and_watch_signed_extrinsic( + &self, + signer: &AccountKeyPairOf, + prepare_extrinsic: impl FnOnce(HeaderIdOf, NonceOf) -> Result> + + Send + + 'static, + ) -> Result> + where + C: ChainWithTransactions, + AccountIdOf: From< as Pair>::Public>; + /// Validate transaction at given block. + async fn validate_transaction( + &self, + at: HashOf, + transaction: SignedTransaction, + ) -> Result; + /// Returns weight of the given transaction. + async fn estimate_extrinsic_weight( + &self, + at: HashOf, + transaction: SignedTransaction, + ) -> Result; + + /// Execute runtime call at given block. + async fn raw_state_call( + &self, + at: HashOf, + method: String, + arguments: Args, + ) -> Result; + /// Execute runtime call at given block, provided the input and output types. + /// It also performs the input encode and output decode. + async fn state_call( + &self, + at: HashOf, + method: String, + arguments: Args, + ) -> Result { + let encoded_arguments = arguments.encode(); + let encoded_output = self.raw_state_call(at, method.clone(), arguments).await?; + Ret::decode(&mut &encoded_output.0[..]).map_err(|e| { + Error::failed_state_call::(at, method, Bytes(encoded_arguments), e.into()) + }) + } + + /// Returns storage proof of given storage keys. + async fn prove_storage(&self, at: HashOf, keys: Vec) -> Result; +} diff --git a/bridges/relays/client-substrate/src/error.rs b/bridges/relays/client-substrate/src/error.rs index 2133c18887846b4f4360bdb6baa34799a24e6164..b09e2c7abdc666735d7481d3f39c9492d851f76a 100644 --- a/bridges/relays/client-substrate/src/error.rs +++ b/bridges/relays/client-substrate/src/error.rs @@ -16,13 +16,13 @@ //! Substrate node RPC errors. -use crate::SimpleRuntimeVersion; +use crate::{BlockNumberOf, Chain, HashOf, SimpleRuntimeVersion}; use bp_header_chain::SubmitFinalityProofCallExtras; use bp_polkadot_core::parachains::ParaId; use jsonrpsee::core::ClientError as RpcError; use relay_utils::MaybeConnectionError; use sc_rpc_api::system::Health; -use sp_core::storage::StorageKey; +use sp_core::{storage::StorageKey, Bytes}; use sp_runtime::transaction_validity::TransactionValidityError; use thiserror::Error; @@ -43,12 +43,10 @@ pub enum Error { /// The response from the server could not be SCALE decoded. #[error("Response parse failed: {0}")] ResponseParseFailed(#[from] codec::Error), - /// Account does not exist on the chain. - #[error("Account does not exist on the chain.")] - AccountDoesNotExist, - /// Runtime storage is missing some mandatory value. - #[error("Mandatory storage value is missing from the runtime storage.")] - MissingMandatoryStorageValue, + /// Internal channel error - communication channel is either closed, or full. + /// It can be solved with reconnect. + #[error("Internal communication channel error: {0:?}.")] + ChannelError(String), /// Required parachain head is not present at the relay chain. #[error("Parachain {0:?} head {1} is missing from the relay chain storage.")] MissingRequiredParachainHead(ParaId, u64), @@ -58,6 +56,14 @@ pub enum Error { /// The client we're connected to is not synced, so we can't rely on its state. #[error("Substrate client is not synced {0}.")] ClientNotSynced(Health), + /// Failed to get system health. + #[error("Failed to get system health of {chain} node: {error:?}.")] + FailedToGetSystemHealth { + /// Name of the chain where the error has happened. + chain: String, + /// Underlying error. + error: Box, + }, /// Failed to read best finalized header hash from given chain. #[error("Failed to read best finalized header hash of {chain}: {error:?}.")] FailedToReadBestFinalizedHeaderHash { @@ -74,6 +80,16 @@ pub enum Error { /// Underlying error. error: Box, }, + /// Failed to read header hash by number from given chain. + #[error("Failed to read header hash by number {number} of {chain}: {error:?}.")] + FailedToReadHeaderHashByNumber { + /// Name of the chain where the error has happened. + chain: String, + /// Number of the header we've tried to read. + number: String, + /// Underlying error. + error: Box, + }, /// Failed to read header by hash from given chain. #[error("Failed to read header {hash} of {chain}: {error:?}.")] FailedToReadHeaderByHash { @@ -84,35 +100,119 @@ pub enum Error { /// Underlying error. error: Box, }, - /// Failed to execute runtime call at given chain. - #[error("Failed to execute runtime call {method} at {chain}: {error:?}.")] - ErrorExecutingRuntimeCall { + /// Failed to read block by hash from given chain. + #[error("Failed to read block {hash} of {chain}: {error:?}.")] + FailedToReadBlockByHash { /// Name of the chain where the error has happened. chain: String, - /// Runtime method name. - method: String, + /// Hash of the header we've tried to read. + hash: String, /// Underlying error. error: Box, }, /// Failed to read sotrage value at given chain. #[error("Failed to read storage value {key:?} at {chain}: {error:?}.")] - FailedToReadRuntimeStorageValue { + FailedToReadStorageValue { /// Name of the chain where the error has happened. chain: String, + /// Hash of the block we've tried to read value from. + hash: String, /// Runtime storage key key: StorageKey, /// Underlying error. error: Box, }, + /// Failed to read runtime version of given chain. + #[error("Failed to read runtime version of {chain}: {error:?}.")] + FailedToReadRuntimeVersion { + /// Name of the chain where the error has happened. + chain: String, + /// Underlying error. + error: Box, + }, + /// Failed to get pending extrinsics. + #[error("Failed to get pending extrinsics of {chain}: {error:?}.")] + FailedToGetPendingExtrinsics { + /// Name of the chain where the error has happened. + chain: String, + /// Underlying error. + error: Box, + }, + /// Failed to submit transaction. + #[error("Failed to submit {chain} transaction: {error:?}.")] + FailedToSubmitTransaction { + /// Name of the chain where the error has happened. + chain: String, + /// Underlying error. + error: Box, + }, + /// Runtime call has failed. + #[error("Runtime call {method} with arguments {arguments:?} of chain {chain} at {hash} has failed: {error:?}.")] + FailedStateCall { + /// Name of the chain where the error has happened. + chain: String, + /// Hash of the block we've tried to call at. + hash: String, + /// Runtime API method. + method: String, + /// Encoded method arguments. + arguments: Bytes, + /// Underlying error. + error: Box, + }, + /// Failed to prove storage keys. + #[error("Failed to prove storage keys {storage_keys:?} of {chain} at {hash}: {error:?}.")] + FailedToProveStorage { + /// Name of the chain where the error has happened. + chain: String, + /// Hash of the block we've tried to prove keys at. + hash: String, + /// Storage keys we have tried to prove. + storage_keys: Vec, + /// Underlying error. + error: Box, + }, + /// Failed to subscribe to GRANDPA justifications stream. + #[error("Failed to subscribe to {chain} best headers: {error:?}.")] + FailedToSubscribeBestHeaders { + /// Name of the chain where the error has happened. + chain: String, + /// Underlying error. + error: Box, + }, + /// Failed to subscribe to GRANDPA justifications stream. + #[error("Failed to subscribe to {chain} finalized headers: {error:?}.")] + FailedToSubscribeFinalizedHeaders { + /// Name of the chain where the error has happened. + chain: String, + /// Underlying error. + error: Box, + }, + /// Failed to subscribe to GRANDPA justifications stream. + #[error("Failed to subscribe to {chain} justifications: {error:?}.")] + FailedToSubscribeJustifications { + /// Name of the chain where the error has happened. + chain: String, + /// Underlying error. + error: Box, + }, + /// Headers of the chain are finalized out of order. Maybe chain has been + /// restarted? + #[error("Finalized headers of {chain} are unordered: previously finalized {prev_number} vs new {next_number}")] + UnorderedFinalizedHeaders { + /// Name of the chain where the error has happened. + chain: String, + /// Previously finalized header number. + prev_number: String, + /// New finalized header number. + next_number: String, + }, /// The bridge pallet is halted and all transactions will be rejected. #[error("Bridge pallet is halted.")] BridgePalletIsHalted, /// The bridge pallet is not yet initialized and all transactions will be rejected. #[error("Bridge pallet is not initialized.")] BridgePalletIsNotInitialized, - /// There's no best head of the parachain at the `pallet-bridge-parachains` at the target side. - #[error("No head of the ParaId({0}) at the bridge parachains pallet at {1}.")] - NoParachainHeadAtTarget(u32, String), /// An error has happened when we have tried to parse storage proof. #[error("Error when parsing storage proof: {0:?}.")] StorageProofError(bp_runtime::StorageProofError), @@ -143,7 +243,19 @@ pub enum Error { impl From for Error { fn from(error: tokio::task::JoinError) -> Self { - Error::Custom(format!("Failed to wait tokio task: {error}")) + Error::ChannelError(format!("failed to wait tokio task: {error}")) + } +} + +impl From> for Error { + fn from(error: async_std::channel::TrySendError) -> Self { + Error::ChannelError(format!("`try_send` has failed: {error:?}")) + } +} + +impl From for Error { + fn from(error: async_std::channel::RecvError) -> Self { + Error::ChannelError(format!("`recv` has failed: {error:?}")) } } @@ -152,21 +264,170 @@ impl Error { pub fn boxed(self) -> Box { Box::new(self) } + + /// Returns nested error reference. + pub fn nested(&self) -> Option<&Self> { + match *self { + Self::FailedToReadBestFinalizedHeaderHash { ref error, .. } => Some(&**error), + Self::FailedToReadBestHeader { ref error, .. } => Some(&**error), + Self::FailedToReadHeaderHashByNumber { ref error, .. } => Some(&**error), + Self::FailedToReadHeaderByHash { ref error, .. } => Some(&**error), + Self::FailedToReadBlockByHash { ref error, .. } => Some(&**error), + Self::FailedToReadStorageValue { ref error, .. } => Some(&**error), + Self::FailedToReadRuntimeVersion { ref error, .. } => Some(&**error), + Self::FailedToGetPendingExtrinsics { ref error, .. } => Some(&**error), + Self::FailedToSubmitTransaction { ref error, .. } => Some(&**error), + Self::FailedStateCall { ref error, .. } => Some(&**error), + Self::FailedToProveStorage { ref error, .. } => Some(&**error), + Self::FailedToGetSystemHealth { ref error, .. } => Some(&**error), + Self::FailedToSubscribeBestHeaders { ref error, .. } => Some(&**error), + Self::FailedToSubscribeFinalizedHeaders { ref error, .. } => Some(&**error), + Self::FailedToSubscribeJustifications { ref error, .. } => Some(&**error), + _ => None, + } + } + + /// Constructs `FailedToReadHeaderHashByNumber` variant. + pub fn failed_to_read_header_hash_by_number( + number: BlockNumberOf, + e: Error, + ) -> Self { + Error::FailedToReadHeaderHashByNumber { + chain: C::NAME.into(), + number: format!("{number}"), + error: e.boxed(), + } + } + + /// Constructs `FailedToReadHeaderByHash` variant. + pub fn failed_to_read_header_by_hash(hash: HashOf, e: Error) -> Self { + Error::FailedToReadHeaderByHash { + chain: C::NAME.into(), + hash: format!("{hash}"), + error: e.boxed(), + } + } + + /// Constructs `FailedToReadBlockByHash` variant. + pub fn failed_to_read_block_by_hash(hash: HashOf, e: Error) -> Self { + Error::FailedToReadHeaderByHash { + chain: C::NAME.into(), + hash: format!("{hash}"), + error: e.boxed(), + } + } + + /// Constructs `FailedToReadBestFinalizedHeaderHash` variant. + pub fn failed_to_read_best_finalized_header_hash(e: Error) -> Self { + Error::FailedToReadBestFinalizedHeaderHash { chain: C::NAME.into(), error: e.boxed() } + } + + /// Constructs `FailedToReadBestHeader` variant. + pub fn failed_to_read_best_header(e: Error) -> Self { + Error::FailedToReadBestHeader { chain: C::NAME.into(), error: e.boxed() } + } + + /// Constructs `FailedToReadRuntimeVersion` variant. + pub fn failed_to_read_runtime_version(e: Error) -> Self { + Error::FailedToReadRuntimeVersion { chain: C::NAME.into(), error: e.boxed() } + } + + /// Constructs `FailedToReadStorageValue` variant. + pub fn failed_to_read_storage_value( + at: HashOf, + key: StorageKey, + e: Error, + ) -> Self { + Error::FailedToReadStorageValue { + chain: C::NAME.into(), + hash: format!("{at}"), + key, + error: e.boxed(), + } + } + + /// Constructs `FailedToGetPendingExtrinsics` variant. + pub fn failed_to_get_pending_extrinsics(e: Error) -> Self { + Error::FailedToGetPendingExtrinsics { chain: C::NAME.into(), error: e.boxed() } + } + + /// Constructs `FailedToSubmitTransaction` variant. + pub fn failed_to_submit_transaction(e: Error) -> Self { + Error::FailedToSubmitTransaction { chain: C::NAME.into(), error: e.boxed() } + } + + /// Constructs `FailedStateCall` variant. + pub fn failed_state_call( + at: HashOf, + method: String, + arguments: Bytes, + e: Error, + ) -> Self { + Error::FailedStateCall { + chain: C::NAME.into(), + hash: format!("{at}"), + method, + arguments, + error: e.boxed(), + } + } + + /// Constructs `FailedToProveStorage` variant. + pub fn failed_to_prove_storage( + at: HashOf, + storage_keys: Vec, + e: Error, + ) -> Self { + Error::FailedToProveStorage { + chain: C::NAME.into(), + hash: format!("{at}"), + storage_keys, + error: e.boxed(), + } + } + + /// Constructs `FailedToGetSystemHealth` variant. + pub fn failed_to_get_system_health(e: Error) -> Self { + Error::FailedToGetSystemHealth { chain: C::NAME.into(), error: e.boxed() } + } + + /// Constructs `FailedToSubscribeBestHeaders` variant. + pub fn failed_to_subscribe_best_headers(e: Error) -> Self { + Error::FailedToSubscribeBestHeaders { chain: C::NAME.into(), error: e.boxed() } + } + + /// Constructs `FailedToSubscribeFinalizedHeaders` variant. + pub fn failed_to_subscribe_finalized_headers(e: Error) -> Self { + Error::FailedToSubscribeFinalizedHeaders { chain: C::NAME.into(), error: e.boxed() } + } + + /// Constructs `FailedToSubscribeJustifications` variant. + pub fn failed_to_subscribe_justification(e: Error) -> Self { + Error::FailedToSubscribeJustifications { chain: C::NAME.into(), error: e.boxed() } + } + + /// Constructs `Un` + pub fn unordered_finalized_headers( + prev_number: BlockNumberOf, + next_number: BlockNumberOf, + ) -> Self { + Error::UnorderedFinalizedHeaders { + chain: C::NAME.into(), + prev_number: format!("{}", prev_number), + next_number: format!("{}", next_number), + } + } } impl MaybeConnectionError for Error { fn is_connection_error(&self) -> bool { match *self { - Error::RpcError(RpcError::Transport(_)) | - Error::RpcError(RpcError::RestartNeeded(_)) | + Error::ChannelError(_) => true, + Error::RpcError(ref e) => + matches!(*e, RpcError::Transport(_) | RpcError::RestartNeeded(_),), Error::ClientNotSynced(_) => true, - Error::FailedToReadBestFinalizedHeaderHash { ref error, .. } => - error.is_connection_error(), - Error::FailedToReadBestHeader { ref error, .. } => error.is_connection_error(), - Error::FailedToReadHeaderByHash { ref error, .. } => error.is_connection_error(), - Error::ErrorExecutingRuntimeCall { ref error, .. } => error.is_connection_error(), - Error::FailedToReadRuntimeStorageValue { ref error, .. } => error.is_connection_error(), - _ => false, + Error::UnorderedFinalizedHeaders { .. } => true, + _ => self.nested().map(|e| e.is_connection_error()).unwrap_or(false), } } } diff --git a/bridges/relays/client-substrate/src/guard.rs b/bridges/relays/client-substrate/src/guard.rs index 47454892cd039f40e92a8f25db435698360bde9b..3dbf95bff8e10de452992a0f3d42befbe058dd74 100644 --- a/bridges/relays/client-substrate/src/guard.rs +++ b/bridges/relays/client-substrate/src/guard.rs @@ -98,7 +98,7 @@ fn conditions_check_delay() -> Duration { } #[async_trait] -impl Environment for Client { +impl> Environment for Clnt { type Error = Error; async fn runtime_version(&mut self) -> Result { diff --git a/bridges/relays/client-substrate/src/lib.rs b/bridges/relays/client-substrate/src/lib.rs index d5b8d4dcced2d8b2e1883b6779905c536eec49f1..12a1c48c09c7ad59d05c0e40a578bc71f7575b35 100644 --- a/bridges/relays/client-substrate/src/lib.rs +++ b/bridges/relays/client-substrate/src/lib.rs @@ -21,7 +21,6 @@ mod chain; mod client; mod error; -mod rpc; mod sync_header; mod transaction_tracker; @@ -37,14 +36,15 @@ pub use crate::{ AccountKeyPairOf, BlockWithJustification, CallOf, Chain, ChainWithBalances, ChainWithGrandpa, ChainWithMessages, ChainWithRuntimeVersion, ChainWithTransactions, ChainWithUtilityPallet, FullRuntimeUtilityPallet, MockedRuntimeUtilityPallet, Parachain, - RelayChain, SignParam, TransactionStatusOf, UnsignedTransaction, UtilityPallet, + RelayChain, SignParam, SignedBlockOf, TransactionStatusOf, UnsignedTransaction, + UtilityPallet, }, client::{ - is_ancient_block, ChainRuntimeVersion, Client, OpaqueGrandpaAuthoritiesSet, - SimpleRuntimeVersion, Subscription, ANCIENT_BLOCK_THRESHOLD, + is_ancient_block, rpc_with_caching as new, ChainRuntimeVersion, Client, + OpaqueGrandpaAuthoritiesSet, RpcWithCachingClient, SimpleRuntimeVersion, StreamDescription, + Subscription, ANCIENT_BLOCK_THRESHOLD, }, error::{Error, Result}, - rpc::{SubstrateBeefyFinalityClient, SubstrateFinalityClient, SubstrateGrandpaFinalityClient}, sync_header::SyncHeader, transaction_tracker::TransactionTracker, }; diff --git a/bridges/relays/client-substrate/src/metrics/float_storage_value.rs b/bridges/relays/client-substrate/src/metrics/float_storage_value.rs index 7bb92693b38d27f42b623d323ba3e7ced8ebbda2..27c9d8cd7a8b68d4ad04ff4ab00f89f408f96a28 100644 --- a/bridges/relays/client-substrate/src/metrics/float_storage_value.rs +++ b/bridges/relays/client-substrate/src/metrics/float_storage_value.rs @@ -14,7 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Parity Bridges Common. If not, see . -use crate::{chain::Chain, client::Client, Error as SubstrateError}; +use crate::{Chain, Client, Error as SubstrateError}; use async_std::sync::{Arc, RwLock}; use async_trait::async_trait; @@ -66,20 +66,20 @@ impl FloatStorageValue for FixedU128OrOne { /// Metric that represents fixed-point runtime storage value as float gauge. #[derive(Clone, Debug)] -pub struct FloatStorageValueMetric { +pub struct FloatStorageValueMetric { value_converter: V, - client: Client, + client: Clnt, storage_key: StorageKey, metric: Gauge, shared_value_ref: F64SharedRef, - _phantom: PhantomData, + _phantom: PhantomData<(C, V)>, } -impl FloatStorageValueMetric { +impl FloatStorageValueMetric { /// Create new metric. pub fn new( value_converter: V, - client: Client, + client: Clnt, storage_key: StorageKey, name: String, help: String, @@ -101,32 +101,39 @@ impl FloatStorageValueMetric { } } -impl Metric for FloatStorageValueMetric { +impl, V: FloatStorageValue> Metric + for FloatStorageValueMetric +{ fn register(&self, registry: &Registry) -> Result<(), PrometheusError> { register(self.metric.clone(), registry).map(drop) } } #[async_trait] -impl StandaloneMetric for FloatStorageValueMetric { +impl, V: FloatStorageValue> StandaloneMetric + for FloatStorageValueMetric +{ fn update_interval(&self) -> Duration { C::AVERAGE_BLOCK_INTERVAL * UPDATE_INTERVAL_IN_BLOCKS } async fn update(&self) { - let value = self - .client - .raw_storage_value(self.storage_key.clone(), None) - .await - .and_then(|maybe_storage_value| { - self.value_converter.decode(maybe_storage_value).map(|maybe_fixed_point_value| { - maybe_fixed_point_value.map(|fixed_point_value| { - fixed_point_value.into_inner().unique_saturated_into() as f64 / - V::Value::DIV.unique_saturated_into() as f64 - }) + let value = async move { + let best_header_hash = self.client.best_header_hash().await?; + let maybe_storage_value = self + .client + .raw_storage_value(best_header_hash, self.storage_key.clone()) + .await?; + self.value_converter.decode(maybe_storage_value).map(|maybe_fixed_point_value| { + maybe_fixed_point_value.map(|fixed_point_value| { + fixed_point_value.into_inner().unique_saturated_into() as f64 / + V::Value::DIV.unique_saturated_into() as f64 }) }) - .map_err(|e| e.to_string()); + } + .await + .map_err(|e| e.to_string()); + relay_utils::metrics::set_gauge_value(&self.metric, value.clone()); *self.shared_value_ref.write().await = value.ok().and_then(|x| x); } diff --git a/bridges/relays/client-substrate/src/transaction_tracker.rs b/bridges/relays/client-substrate/src/transaction_tracker.rs index b181a945c2c15393daf821901b298e81214f85e3..b4801c89f51e1b1d9fd31373cdafb5b4770037cc 100644 --- a/bridges/relays/client-substrate/src/transaction_tracker.rs +++ b/bridges/relays/client-substrate/src/transaction_tracker.rs @@ -16,7 +16,7 @@ //! Helper for tracking transaction invalidation events. -use crate::{Chain, Client, Error, HashOf, HeaderIdOf, Subscription, TransactionStatusOf}; +use crate::{Chain, Error, HashOf, HeaderIdOf, Subscription, TransactionStatusOf}; use async_trait::async_trait; use futures::{future::Either, Future, FutureExt, Stream, StreamExt}; @@ -31,8 +31,10 @@ pub trait Environment: Send + Sync { async fn header_id_by_hash(&self, hash: HashOf) -> Result, Error>; } +// TODO (https://github.com/paritytech/parity-bridges-common/issues/2133): remove `Environment` trait +// after test client is implemented #[async_trait] -impl Environment for Client { +impl> Environment for T { async fn header_id_by_hash(&self, hash: HashOf) -> Result, Error> { self.header_by_hash(hash).await.map(|h| HeaderId(*h.number(), hash)) } @@ -76,6 +78,21 @@ impl> TransactionTracker { Self { environment, stall_timeout, transaction_hash, subscription } } + // TODO (https://github.com/paritytech/parity-bridges-common/issues/2133): remove me after + // test client is implemented + /// Converts self into tracker with different environment. + pub fn switch_environment>( + self, + environment: NewE, + ) -> TransactionTracker { + TransactionTracker { + environment, + stall_timeout: self.stall_timeout, + transaction_hash: self.transaction_hash, + subscription: self.subscription, + } + } + /// Wait for final transaction status and return it along with last known internal invalidation /// status. async fn do_wait( @@ -88,7 +105,7 @@ impl> TransactionTracker { let wait_for_invalidation = watch_transaction_status::<_, C, _>( self.environment, self.transaction_hash, - self.subscription.into_stream(), + self.subscription, ); futures::pin_mut!(wait_for_stall_timeout, wait_for_invalidation); @@ -284,7 +301,7 @@ async fn watch_transaction_status< #[cfg(test)] mod tests { use super::*; - use crate::test_chain::TestChain; + use crate::{test_chain::TestChain, StreamDescription}; use futures::{FutureExt, SinkExt}; use sc_transaction_pool_api::TransactionStatus; @@ -306,22 +323,27 @@ mod tests { TrackedTransactionStatus>, InvalidationStatus>, )> { - let (cancel_sender, _cancel_receiver) = futures::channel::oneshot::channel(); let (mut sender, receiver) = futures::channel::mpsc::channel(1); let tx_tracker = TransactionTracker::::new( TestEnvironment(Ok(HeaderId(0, Default::default()))), Duration::from_secs(0), Default::default(), - Subscription(async_std::sync::Mutex::new(receiver), cancel_sender), + Subscription::new_forwarded( + StreamDescription::new("test".into(), "test".into()), + receiver, + ), ); - let wait_for_stall_timeout = futures::future::pending(); + // we can't do `.now_or_never()` on `do_wait()` call, because `Subscription` has its own + // background thread, which may cause additional async task switches => let's leave some + // relatively small timeout here + let wait_for_stall_timeout = async_std::task::sleep(std::time::Duration::from_millis(100)); let wait_for_stall_timeout_rest = futures::future::ready(()); - sender.send(Some(status)).await.unwrap(); - tx_tracker - .do_wait(wait_for_stall_timeout, wait_for_stall_timeout_rest) - .now_or_never() - .map(|(ts, is)| (ts, is.unwrap())) + sender.send(Ok(status)).await.unwrap(); + + let (ts, is) = + tx_tracker.do_wait(wait_for_stall_timeout, wait_for_stall_timeout_rest).await; + is.map(|is| (ts, is)) } #[async_std::test] @@ -429,13 +451,15 @@ mod tests { #[async_std::test] async fn lost_on_timeout_when_waiting_for_invalidation_status() { - let (cancel_sender, _cancel_receiver) = futures::channel::oneshot::channel(); let (_sender, receiver) = futures::channel::mpsc::channel(1); let tx_tracker = TransactionTracker::::new( TestEnvironment(Ok(HeaderId(0, Default::default()))), Duration::from_secs(0), Default::default(), - Subscription(async_std::sync::Mutex::new(receiver), cancel_sender), + Subscription::new_forwarded( + StreamDescription::new("test".into(), "test".into()), + receiver, + ), ); let wait_for_stall_timeout = futures::future::ready(()).shared(); diff --git a/bridges/relays/equivocation/Cargo.toml b/bridges/relays/equivocation/Cargo.toml index 5a067b62e0774ffb93e8b935ed287696e1fefd7c..09bdda23f2c25edabc5c4adbf6fa6739b99ddeef 100644 --- a/bridges/relays/equivocation/Cargo.toml +++ b/bridges/relays/equivocation/Cargo.toml @@ -12,12 +12,12 @@ publish = false workspace = true [dependencies] -async-std = { version = "1.9.0", features = ["attributes"] } -async-trait = "0.1.79" -bp-header-chain = { path = "../../primitives/header-chain" } -finality-relay = { path = "../finality" } -frame-support = { path = "../../../substrate/frame/support" } -futures = "0.3.30" +async-std = { features = ["attributes"], workspace = true } +async-trait = { workspace = true } +bp-header-chain = { workspace = true, default-features = true } +finality-relay = { workspace = true } +frame-support = { workspace = true, default-features = true } +futures = { workspace = true } log = { workspace = true } -num-traits = "0.2" -relay-utils = { path = "../utils" } +num-traits = { workspace = true, default-features = true } +relay-utils = { workspace = true } diff --git a/bridges/relays/finality/Cargo.toml b/bridges/relays/finality/Cargo.toml index 5ee4b10fa638f5ec226df14beca1e0c79d0055df..06c4a5dcc43e0d54410424a85e2ff72dbbf24729 100644 --- a/bridges/relays/finality/Cargo.toml +++ b/bridges/relays/finality/Cargo.toml @@ -12,14 +12,14 @@ publish = false workspace = true [dependencies] -async-std = "1.9.0" -async-trait = "0.1.79" -backoff = "0.4" -bp-header-chain = { path = "../../primitives/header-chain" } -futures = "0.3.30" +async-std = { workspace = true } +async-trait = { workspace = true } +backoff = { workspace = true } +bp-header-chain = { workspace = true, default-features = true } +futures = { workspace = true } log = { workspace = true } -num-traits = "0.2" -relay-utils = { path = "../utils" } +num-traits = { workspace = true, default-features = true } +relay-utils = { workspace = true } [dev-dependencies] -parking_lot = "0.12.1" +parking_lot = { workspace = true, default-features = true } diff --git a/bridges/relays/lib-substrate-relay/Cargo.toml b/bridges/relays/lib-substrate-relay/Cargo.toml index 077d1b1ff356a871364d45c1251aec0af7680cdd..28fee5b167ffab3249a5feb96ff04c991e2fc311 100644 --- a/bridges/relays/lib-substrate-relay/Cargo.toml +++ b/bridges/relays/lib-substrate-relay/Cargo.toml @@ -11,52 +11,52 @@ publish = false workspace = true [dependencies] -anyhow = "1.0" -async-std = "1.9.0" -async-trait = "0.1.79" -codec = { package = "parity-scale-codec", version = "3.6.12" } -futures = "0.3.30" -hex = "0.4" +anyhow = { workspace = true } +async-std = { workspace = true } +async-trait = { workspace = true } +codec = { workspace = true, default-features = true } +futures = { workspace = true } +hex = { workspace = true, default-features = true } log = { workspace = true } -num-traits = "0.2" -rbtag = "0.3" -structopt = "0.3" -strum = { version = "0.26.2", features = ["derive"] } +num-traits = { workspace = true, default-features = true } +rbtag = { workspace = true } +structopt = { workspace = true } +strum = { features = ["derive"], workspace = true, default-features = true } thiserror = { workspace = true } # Bridge dependencies -bp-header-chain = { path = "../../primitives/header-chain" } -bp-parachains = { path = "../../primitives/parachains" } -bp-polkadot-core = { path = "../../primitives/polkadot-core" } -bp-relayers = { path = "../../primitives/relayers" } -bridge-runtime-common = { path = "../../bin/runtime-common" } +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 = { path = "../equivocation" } -finality-grandpa = { version = "0.16.2" } -finality-relay = { path = "../finality" } -parachains-relay = { path = "../parachains" } -relay-utils = { path = "../utils" } -messages-relay = { path = "../messages" } -relay-substrate-client = { path = "../client-substrate" } +equivocation-detector = { workspace = true } +finality-grandpa = { workspace = true, default-features = true } +finality-relay = { workspace = true } +parachains-relay = { workspace = true } +relay-utils = { workspace = true } +messages-relay = { workspace = true } +relay-substrate-client = { workspace = true } -pallet-bridge-grandpa = { path = "../../modules/grandpa" } -pallet-bridge-messages = { path = "../../modules/messages" } -pallet-bridge-parachains = { path = "../../modules/parachains" } +pallet-bridge-grandpa = { workspace = true, default-features = true } +pallet-bridge-messages = { workspace = true, default-features = true } +pallet-bridge-parachains = { workspace = true, default-features = true } -bp-runtime = { path = "../../primitives/runtime" } -bp-messages = { path = "../../primitives/messages" } +bp-runtime = { workspace = true, default-features = true } +bp-messages = { workspace = true, default-features = true } # Substrate Dependencies -frame-support = { path = "../../../substrate/frame/support" } -frame-system = { path = "../../../substrate/frame/system" } -pallet-balances = { path = "../../../substrate/frame/balances" } -pallet-grandpa = { path = "../../../substrate/frame/grandpa" } -sp-core = { path = "../../../substrate/primitives/core" } -sp-consensus-grandpa = { path = "../../../substrate/primitives/consensus/grandpa" } -sp-runtime = { path = "../../../substrate/primitives/runtime" } +frame-support = { workspace = true, default-features = true } +frame-system = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +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 } [dev-dependencies] -pallet-transaction-payment = { path = "../../../substrate/frame/transaction-payment" } -relay-substrate-client = { path = "../client-substrate", features = ["test-helpers"] } +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/chain_schema.rs b/bridges/relays/lib-substrate-relay/src/cli/chain_schema.rs index 6246bdbf015152fe0e82ac0a8287692df6a1ace9..d985d35c9e802e694e74264ed3f611f14e8bc0d2 100644 --- a/bridges/relays/lib-substrate-relay/src/cli/chain_schema.rs +++ b/bridges/relays/lib-substrate-relay/src/cli/chain_schema.rs @@ -123,11 +123,11 @@ macro_rules! declare_chain_connection_params_cli_schema { #[allow(dead_code)] pub async fn into_client( self, - ) -> anyhow::Result> { + ) -> anyhow::Result<$crate::cli::DefaultClient> { let chain_runtime_version = self .[<$chain_prefix _runtime_version>] .into_runtime_version(Chain::RUNTIME_VERSION)?; - Ok(relay_substrate_client::Client::new(relay_substrate_client::ConnectionParams { + Ok(relay_substrate_client::new(relay_substrate_client::ConnectionParams { uri: self.[<$chain_prefix _uri>], host: self.[<$chain_prefix _host>], port: self.[<$chain_prefix _port>], diff --git a/bridges/relays/lib-substrate-relay/src/cli/detect_equivocations.rs b/bridges/relays/lib-substrate-relay/src/cli/detect_equivocations.rs index b98e41b2a43e4f88670ac8ed1d7129a0187fecfe..3921685d9e8ad70a9173a87ef19fb567c9263a63 100644 --- a/bridges/relays/lib-substrate-relay/src/cli/detect_equivocations.rs +++ b/bridges/relays/lib-substrate-relay/src/cli/detect_equivocations.rs @@ -23,7 +23,7 @@ use crate::{ }; use async_trait::async_trait; -use relay_substrate_client::ChainWithTransactions; +use relay_substrate_client::{ChainWithTransactions, Client}; use structopt::StructOpt; /// Start equivocation detection loop. diff --git a/bridges/relays/lib-substrate-relay/src/cli/mod.rs b/bridges/relays/lib-substrate-relay/src/cli/mod.rs index 270608bf6ed8e1500d10000173bd7945a31c8135..ddb3e416dc32628b5a85f27f322d0568cbee1c10 100644 --- a/bridges/relays/lib-substrate-relay/src/cli/mod.rs +++ b/bridges/relays/lib-substrate-relay/src/cli/mod.rs @@ -35,6 +35,11 @@ pub mod relay_parachains; /// The target that will be used when publishing logs related to this pallet. pub const LOG_TARGET: &str = "bridge"; +/// Default Substrate client type that we are using. We'll use it all over the glue CLI code +/// to avoid multiple level generic arguments and constraints. We still allow usage of other +/// clients in the **core logic code**. +pub type DefaultClient = relay_substrate_client::RpcWithCachingClient; + /// Lane id. #[derive(Debug, Clone, PartialEq, Eq)] pub struct HexLaneId(pub [u8; 4]); diff --git a/bridges/relays/lib-substrate-relay/src/cli/relay_headers.rs b/bridges/relays/lib-substrate-relay/src/cli/relay_headers.rs index 093f98ef21ed24b40a0c2d8f217d84b841137a69..ea92a0c9acce15a7f5000d0dd7e0253bbafc7844 100644 --- a/bridges/relays/lib-substrate-relay/src/cli/relay_headers.rs +++ b/bridges/relays/lib-substrate-relay/src/cli/relay_headers.rs @@ -29,6 +29,7 @@ use crate::{ finality::SubstrateFinalitySyncPipeline, HeadersToRelay, }; +use relay_substrate_client::Client; /// Chain headers relaying params. #[derive(StructOpt)] 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 a796df6721b8c8afd7f401f92e2fca6afcb41b02..05a061c2ea606b79464908a6af46ed75af7d80ee 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 @@ -37,7 +37,7 @@ use structopt::StructOpt; use futures::{FutureExt, TryFutureExt}; use crate::{ - cli::{bridge::MessagesCliBridge, HexLaneId, PrometheusParams}, + cli::{bridge::MessagesCliBridge, DefaultClient, HexLaneId, PrometheusParams}, messages_lane::{MessagesRelayLimits, MessagesRelayParams}, on_demand::OnDemandRelay, HeadersToRelay, TaggedAccount, TransactionParams, @@ -46,7 +46,7 @@ use bp_messages::LaneId; use bp_runtime::BalanceOf; use relay_substrate_client::{ AccountIdOf, AccountKeyPairOf, Chain, ChainWithBalances, ChainWithMessages, - ChainWithRuntimeVersion, ChainWithTransactions, Client, + ChainWithRuntimeVersion, ChainWithTransactions, }; use relay_utils::metrics::MetricsParams; use sp_core::Pair; @@ -118,7 +118,7 @@ impl< /// Parameters that are associated with one side of the bridge. pub struct BridgeEndCommonParams { /// Chain client. - pub client: Client, + pub client: DefaultClient, /// Params used for sending transactions to the chain. pub tx_params: TransactionParams>, /// Accounts, which balances are exposed as metrics by the relay process. @@ -165,7 +165,7 @@ where target_to_source_headers_relay: Arc>, lane_id: LaneId, maybe_limits: Option, - ) -> MessagesRelayParams { + ) -> MessagesRelayParams, DefaultClient> { MessagesRelayParams { source_client: self.source.client.clone(), source_transaction_params: self.source.tx_params.clone(), @@ -317,28 +317,30 @@ where // Need 2x capacity since we consider both directions for each lane let mut message_relays = Vec::with_capacity(lanes.len() * 2); for lane in lanes { - let left_to_right_messages = crate::messages_lane::run::< - ::MessagesLane, - >(self.left_to_right().messages_relay_params( - left_to_right_on_demand_headers.clone(), - right_to_left_on_demand_headers.clone(), - lane, - Self::L2R::maybe_messages_limits(), - )) - .map_err(|e| anyhow::format_err!("{}", e)) - .boxed(); + let left_to_right_messages = + crate::messages_lane::run::<::MessagesLane, _, _>( + self.left_to_right().messages_relay_params( + left_to_right_on_demand_headers.clone(), + right_to_left_on_demand_headers.clone(), + lane, + Self::L2R::maybe_messages_limits(), + ), + ) + .map_err(|e| anyhow::format_err!("{}", e)) + .boxed(); message_relays.push(left_to_right_messages); - let right_to_left_messages = crate::messages_lane::run::< - ::MessagesLane, - >(self.right_to_left().messages_relay_params( - right_to_left_on_demand_headers.clone(), - left_to_right_on_demand_headers.clone(), - lane, - Self::R2L::maybe_messages_limits(), - )) - .map_err(|e| anyhow::format_err!("{}", e)) - .boxed(); + let right_to_left_messages = + crate::messages_lane::run::<::MessagesLane, _, _>( + self.right_to_left().messages_relay_params( + right_to_left_on_demand_headers.clone(), + left_to_right_on_demand_headers.clone(), + lane, + Self::R2L::maybe_messages_limits(), + ), + ) + .map_err(|e| anyhow::format_err!("{}", e)) + .boxed(); message_relays.push(right_to_left_messages); } diff --git a/bridges/relays/lib-substrate-relay/src/cli/relay_headers_and_messages/parachain_to_parachain.rs b/bridges/relays/lib-substrate-relay/src/cli/relay_headers_and_messages/parachain_to_parachain.rs index 7f6f40777823679c97577f1244eb9a860948d267..8104be7af807a67bbc001e70e24565c81b6beb17 100644 --- a/bridges/relays/lib-substrate-relay/src/cli/relay_headers_and_messages/parachain_to_parachain.rs +++ b/bridges/relays/lib-substrate-relay/src/cli/relay_headers_and_messages/parachain_to_parachain.rs @@ -23,6 +23,7 @@ use crate::{ cli::{ bridge::{CliBridgeBase, MessagesCliBridge, ParachainToRelayHeadersCliBridge}, relay_headers_and_messages::{Full2WayBridgeBase, Full2WayBridgeCommonParams}, + DefaultClient, }, finality::SubstrateFinalitySyncPipeline, on_demand::{ @@ -52,9 +53,9 @@ pub struct ParachainToParachainBridge< pub common: Full2WayBridgeCommonParams<::Target, ::Target>, /// Client of the left relay chain. - pub left_relay: Client<::SourceRelay>, + pub left_relay: DefaultClient<::SourceRelay>, /// Client of the right relay chain. - pub right_relay: Client<::SourceRelay>, + pub right_relay: DefaultClient<::SourceRelay>, } /// Create set of configuration objects specific to parachain-to-parachain relayer. @@ -175,25 +176,33 @@ where ) .await?; - let left_relay_to_right_on_demand_headers = - OnDemandHeadersRelay::<::RelayFinality>::new( - self.left_relay.clone(), - self.common.right.client.clone(), - self.common.right.tx_params.clone(), - self.common.shared.headers_to_relay(), - Some(self.common.metrics_params.clone()), - ); - let right_relay_to_left_on_demand_headers = - OnDemandHeadersRelay::<::RelayFinality>::new( - self.right_relay.clone(), - self.common.left.client.clone(), - self.common.left.tx_params.clone(), - self.common.shared.headers_to_relay(), - Some(self.common.metrics_params.clone()), - ); + let left_relay_to_right_on_demand_headers = OnDemandHeadersRelay::< + ::RelayFinality, + _, + _, + >::new( + self.left_relay.clone(), + self.common.right.client.clone(), + self.common.right.tx_params.clone(), + self.common.shared.headers_to_relay(), + Some(self.common.metrics_params.clone()), + ); + let right_relay_to_left_on_demand_headers = OnDemandHeadersRelay::< + ::RelayFinality, + _, + _, + >::new( + self.right_relay.clone(), + self.common.left.client.clone(), + self.common.left.tx_params.clone(), + self.common.shared.headers_to_relay(), + Some(self.common.metrics_params.clone()), + ); let left_to_right_on_demand_parachains = OnDemandParachainsRelay::< ::ParachainFinality, + _, + _, >::new( self.left_relay.clone(), self.common.right.client.clone(), @@ -202,6 +211,8 @@ where ); let right_to_left_on_demand_parachains = OnDemandParachainsRelay::< ::ParachainFinality, + _, + _, >::new( self.right_relay.clone(), self.common.left.client.clone(), diff --git a/bridges/relays/lib-substrate-relay/src/cli/relay_headers_and_messages/relay_to_parachain.rs b/bridges/relays/lib-substrate-relay/src/cli/relay_headers_and_messages/relay_to_parachain.rs index 5911fe49df4adfc955cbab4d142998fbc7ed4d22..6c078973fedc08a724e51808f2cb47f3a64ca1a1 100644 --- a/bridges/relays/lib-substrate-relay/src/cli/relay_headers_and_messages/relay_to_parachain.rs +++ b/bridges/relays/lib-substrate-relay/src/cli/relay_headers_and_messages/relay_to_parachain.rs @@ -26,6 +26,7 @@ use crate::{ RelayToRelayHeadersCliBridge, }, relay_headers_and_messages::{Full2WayBridgeBase, Full2WayBridgeCommonParams}, + DefaultClient, }, finality::SubstrateFinalitySyncPipeline, on_demand::{ @@ -54,7 +55,7 @@ pub struct RelayToParachainBridge< pub common: Full2WayBridgeCommonParams<::Target, ::Target>, /// Client of the right relay chain. - pub right_relay: Client<::SourceRelay>, + pub right_relay: DefaultClient<::SourceRelay>, } /// Create set of configuration objects specific to relay-to-parachain relayer. @@ -167,23 +168,28 @@ where .await?; let left_to_right_on_demand_headers = - OnDemandHeadersRelay::<::Finality>::new( + OnDemandHeadersRelay::<::Finality, _, _>::new( self.common.left.client.clone(), self.common.right.client.clone(), self.common.right.tx_params.clone(), self.common.shared.headers_to_relay(), None, ); - let right_relay_to_left_on_demand_headers = - OnDemandHeadersRelay::<::RelayFinality>::new( - self.right_relay.clone(), - self.common.left.client.clone(), - self.common.left.tx_params.clone(), - self.common.shared.headers_to_relay(), - Some(self.common.metrics_params.clone()), - ); + let right_relay_to_left_on_demand_headers = OnDemandHeadersRelay::< + ::RelayFinality, + _, + _, + >::new( + self.right_relay.clone(), + self.common.left.client.clone(), + self.common.left.tx_params.clone(), + self.common.shared.headers_to_relay(), + Some(self.common.metrics_params.clone()), + ); let right_to_left_on_demand_parachains = OnDemandParachainsRelay::< ::ParachainFinality, + _, + _, >::new( self.right_relay.clone(), self.common.left.client.clone(), diff --git a/bridges/relays/lib-substrate-relay/src/cli/relay_headers_and_messages/relay_to_relay.rs b/bridges/relays/lib-substrate-relay/src/cli/relay_headers_and_messages/relay_to_relay.rs index 832df4ae4003ced1715d7b9d495989d9163417d5..3f8c8bb40c99c7218cdc69a2524ec5dd113e621f 100644 --- a/bridges/relays/lib-substrate-relay/src/cli/relay_headers_and_messages/relay_to_relay.rs +++ b/bridges/relays/lib-substrate-relay/src/cli/relay_headers_and_messages/relay_to_relay.rs @@ -32,7 +32,7 @@ use crate::{ on_demand::{headers::OnDemandHeadersRelay, OnDemandRelay}, }; use relay_substrate_client::{ - AccountIdOf, AccountKeyPairOf, ChainWithRuntimeVersion, ChainWithTransactions, + AccountIdOf, AccountKeyPairOf, ChainWithRuntimeVersion, ChainWithTransactions, Client, }; use sp_core::Pair; @@ -148,7 +148,7 @@ where .await?; let left_to_right_on_demand_headers = - OnDemandHeadersRelay::<::Finality>::new( + OnDemandHeadersRelay::<::Finality, _, _>::new( self.common.left.client.clone(), self.common.right.client.clone(), self.common.right.tx_params.clone(), @@ -156,7 +156,7 @@ where None, ); let right_to_left_on_demand_headers = - OnDemandHeadersRelay::<::Finality>::new( + OnDemandHeadersRelay::<::Finality, _, _>::new( self.common.right.client.clone(), self.common.left.client.clone(), self.common.left.tx_params.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 943feba072e408d98360ece228fe8c5558181b69..a17ae7c0c01f9b828d8a534da8143a1d983892c2 100644 --- a/bridges/relays/lib-substrate-relay/src/cli/relay_messages.rs +++ b/bridges/relays/lib-substrate-relay/src/cli/relay_messages.rs @@ -29,7 +29,8 @@ use structopt::StructOpt; use bp_messages::MessageNonce; use bp_runtime::HeaderIdProvider; use relay_substrate_client::{ - AccountIdOf, AccountKeyPairOf, BalanceOf, Chain, ChainWithRuntimeVersion, ChainWithTransactions, + AccountIdOf, AccountKeyPairOf, BalanceOf, Chain, ChainWithRuntimeVersion, + ChainWithTransactions, Client, }; use relay_utils::UniqueSaturatedInto; @@ -116,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_lane::run::(MessagesRelayParams { source_client, source_transaction_params: TransactionParams { signer: source_sign, diff --git a/bridges/relays/lib-substrate-relay/src/cli/relay_parachains.rs b/bridges/relays/lib-substrate-relay/src/cli/relay_parachains.rs index 00f8cf79ef1fb54577954cf198e7296819591a43..77cd395ff7225e9a0d088cc35cf0f86ab78caf46 100644 --- a/bridges/relays/lib-substrate-relay/src/cli/relay_parachains.rs +++ b/bridges/relays/lib-substrate-relay/src/cli/relay_parachains.rs @@ -21,7 +21,7 @@ use async_trait::async_trait; use bp_polkadot_core::BlockNumber as RelayBlockNumber; use bp_runtime::HeaderIdProvider; use parachains_relay::parachains_loop::{AvailableHeader, SourceClient, TargetClient}; -use relay_substrate_client::Parachain; +use relay_substrate_client::{Client, Parachain}; use relay_utils::metrics::{GlobalMetrics, StandaloneMetric}; use std::sync::Arc; use structopt::StructOpt; @@ -30,7 +30,7 @@ use crate::{ cli::{ bridge::{CliBridgeBase, ParachainToRelayHeadersCliBridge}, chain_schema::*, - PrometheusParams, + DefaultClient, PrometheusParams, }, parachains::{source::ParachainsSource, target::ParachainsTarget, ParachainsPipelineAdapter}, TransactionParams, @@ -72,16 +72,19 @@ pub struct RelayParachainHeadParams { #[async_trait] pub trait ParachainsRelayer: ParachainToRelayHeadersCliBridge where - ParachainsSource: + ParachainsSource>: SourceClient>, - ParachainsTarget: - TargetClient>, + ParachainsTarget< + Self::ParachainFinality, + DefaultClient, + DefaultClient, + >: TargetClient>, ::Source: Parachain, { /// Start relaying parachains finality. async fn relay_parachains(data: RelayParachainsParams) -> anyhow::Result<()> { let source_chain_client = data.source.into_client::().await?; - let source_client = ParachainsSource::::new( + let source_client = ParachainsSource::::new( source_chain_client.clone(), Arc::new(Mutex::new(AvailableHeader::Missing)), ); @@ -91,7 +94,7 @@ where mortality: data.target_sign.target_transactions_mortality, }; let target_chain_client = data.target.into_client::().await?; - let target_client = ParachainsTarget::::new( + let target_client = ParachainsTarget::::new( source_chain_client, target_chain_client, target_transaction_params, @@ -121,7 +124,7 @@ where .map_err(|e| anyhow::format_err!("{}", e))? .id(); - let source_client = ParachainsSource::::new( + let source_client = ParachainsSource::::new( source_chain_client.clone(), Arc::new(Mutex::new(AvailableHeader::Missing)), ); @@ -131,7 +134,7 @@ where mortality: data.target_sign.target_transactions_mortality, }; let target_chain_client = data.target.into_client::().await?; - let target_client = ParachainsTarget::::new( + let target_client = ParachainsTarget::::new( source_chain_client, target_chain_client, target_transaction_params, diff --git a/bridges/relays/lib-substrate-relay/src/equivocation/mod.rs b/bridges/relays/lib-substrate-relay/src/equivocation/mod.rs index f6d58cbaa4ab4c4d7f489de5a80ab226b3b475b4..f8077923b82023cc640ddcf131f248ef141853a0 100644 --- a/bridges/relays/lib-substrate-relay/src/equivocation/mod.rs +++ b/bridges/relays/lib-substrate-relay/src/equivocation/mod.rs @@ -69,7 +69,7 @@ pub trait SubstrateEquivocationDetectionPipeline: /// Add relay guards if required. async fn start_relay_guards( - source_client: &Client, + source_client: &impl Client, enable_version_guard: bool, ) -> relay_substrate_client::Result<()> { if enable_version_guard { @@ -199,8 +199,8 @@ macro_rules! generate_report_equivocation_call_builder { /// Run Substrate-to-Substrate equivocations detection loop. pub async fn run( - source_client: Client, - target_client: Client, + source_client: impl Client, + target_client: impl Client, source_transaction_params: TransactionParams>, metrics_params: MetricsParams, ) -> anyhow::Result<()> { @@ -212,8 +212,8 @@ pub async fn run( ); equivocation_detector::run( - SubstrateEquivocationSource::

::new(source_client, source_transaction_params), - SubstrateEquivocationTarget::

::new(target_client), + SubstrateEquivocationSource::::new(source_client, source_transaction_params), + SubstrateEquivocationTarget::::new(target_client), P::TargetChain::AVERAGE_BLOCK_INTERVAL, metrics_params, futures::future::pending(), diff --git a/bridges/relays/lib-substrate-relay/src/equivocation/source.rs b/bridges/relays/lib-substrate-relay/src/equivocation/source.rs index a0c7dcf5cbc32c7e5a39de5acd53d92def24a22f..66d651600a1ec72943cb4d13c3e094c5be0a33e3 100644 --- a/bridges/relays/lib-substrate-relay/src/equivocation/source.rs +++ b/bridges/relays/lib-substrate-relay/src/equivocation/source.rs @@ -35,29 +35,35 @@ use relay_substrate_client::{ use relay_utils::relay_loop::Client as RelayClient; /// Substrate node as equivocation source. -pub struct SubstrateEquivocationSource { - client: Client, +pub struct SubstrateEquivocationSource { + client: SourceClnt, transaction_params: TransactionParams>, } -impl SubstrateEquivocationSource

{ +impl> + SubstrateEquivocationSource +{ /// Create new instance of `SubstrateEquivocationSource`. pub fn new( - client: Client, + client: SourceClnt, transaction_params: TransactionParams>, ) -> Self { Self { client, transaction_params } } } -impl Clone for SubstrateEquivocationSource

{ +impl> Clone + for SubstrateEquivocationSource +{ fn clone(&self) -> Self { Self { client: self.client.clone(), transaction_params: self.transaction_params.clone() } } } #[async_trait] -impl RelayClient for SubstrateEquivocationSource

{ +impl> RelayClient + for SubstrateEquivocationSource +{ type Error = Error; async fn reconnect(&mut self) -> Result<(), Error> { @@ -66,8 +72,9 @@ impl RelayClient for SubstrateEquivoc } #[async_trait] -impl - SourceClientBase> for SubstrateEquivocationSource

+impl> + SourceClientBase> + for SubstrateEquivocationSource { type FinalityProofsStream = SubstrateFinalityProofsStream

; @@ -77,10 +84,11 @@ impl } #[async_trait] -impl - SourceClient> for SubstrateEquivocationSource

+impl> + SourceClient> + for SubstrateEquivocationSource { - type TransactionTracker = TransactionTracker>; + type TransactionTracker = TransactionTracker; async fn report_equivocation( &self, diff --git a/bridges/relays/lib-substrate-relay/src/equivocation/target.rs b/bridges/relays/lib-substrate-relay/src/equivocation/target.rs index 6eee2ab91d45b033a77e30b7d05ae28b246b9735..7d054e843d0db6c09b5baec551c46bb9fbe0fc34 100644 --- a/bridges/relays/lib-substrate-relay/src/equivocation/target.rs +++ b/bridges/relays/lib-substrate-relay/src/equivocation/target.rs @@ -34,27 +34,33 @@ use sp_runtime::traits::Header; use std::marker::PhantomData; /// Substrate node as equivocation source. -pub struct SubstrateEquivocationTarget { - client: Client, +pub struct SubstrateEquivocationTarget { + client: TargetClnt, _phantom: PhantomData

, } -impl SubstrateEquivocationTarget

{ +impl> + SubstrateEquivocationTarget +{ /// Create new instance of `SubstrateEquivocationTarget`. - pub fn new(client: Client) -> Self { + pub fn new(client: TargetClnt) -> Self { Self { client, _phantom: Default::default() } } } -impl Clone for SubstrateEquivocationTarget

{ +impl> Clone + for SubstrateEquivocationTarget +{ fn clone(&self) -> Self { Self { client: self.client.clone(), _phantom: Default::default() } } } #[async_trait] -impl RelayClient for SubstrateEquivocationTarget

{ +impl> RelayClient + for SubstrateEquivocationTarget +{ type Error = Error; async fn reconnect(&mut self) -> Result<(), Error> { @@ -63,8 +69,9 @@ impl RelayClient for SubstrateEquivoc } #[async_trait] -impl - TargetClient> for SubstrateEquivocationTarget

+impl> + TargetClient> + for SubstrateEquivocationTarget { async fn best_finalized_header_number( &self, diff --git a/bridges/relays/lib-substrate-relay/src/finality/initialize.rs b/bridges/relays/lib-substrate-relay/src/finality/initialize.rs index 5dde46c39dd674e7c01eebba4b014bc999611eb5..a972f743e117ce280fb2dd5a950581713766a3b6 100644 --- a/bridges/relays/lib-substrate-relay/src/finality/initialize.rs +++ b/bridges/relays/lib-substrate-relay/src/finality/initialize.rs @@ -39,8 +39,8 @@ pub async fn initialize< TargetChain: ChainWithTransactions, F, >( - source_client: Client, - target_client: Client, + source_client: impl Client, + target_client: impl Client, target_signer: AccountKeyPairOf, prepare_initialize_transaction: F, dry_run: bool, @@ -101,8 +101,8 @@ async fn do_initialize< TargetChain: ChainWithTransactions, F, >( - source_client: Client, - target_client: Client, + source_client: impl Client, + target_client: impl Client, target_signer: AccountKeyPairOf, prepare_initialize_transaction: F, dry_run: bool, diff --git a/bridges/relays/lib-substrate-relay/src/finality/mod.rs b/bridges/relays/lib-substrate-relay/src/finality/mod.rs index 0293e1da224a6323fed59f7f727b5d5263391bb8..a2379eb4812e2ab7d904eff0ce9b082ac474d36e 100644 --- a/bridges/relays/lib-substrate-relay/src/finality/mod.rs +++ b/bridges/relays/lib-substrate-relay/src/finality/mod.rs @@ -77,7 +77,7 @@ pub trait SubstrateFinalitySyncPipeline: BaseSubstrateFinalitySyncPipeline { /// Add relay guards if required. async fn start_relay_guards( - target_client: &Client, + target_client: &impl Client, enable_version_guard: bool, ) -> relay_substrate_client::Result<()> { if enable_version_guard { @@ -240,8 +240,8 @@ macro_rules! generate_submit_finality_proof_ex_call_builder { /// Run Substrate-to-Substrate finality sync loop. pub async fn run( - source_client: Client, - target_client: Client, + source_client: impl Client, + target_client: impl Client, headers_to_relay: HeadersToRelay, transaction_params: TransactionParams>, metrics_params: MetricsParams, @@ -255,8 +255,8 @@ pub async fn run( ); finality_relay::run( - SubstrateFinalitySource::

::new(source_client, None), - SubstrateFinalityTarget::

::new(target_client, transaction_params.clone()), + SubstrateFinalitySource::::new(source_client, None), + SubstrateFinalityTarget::::new(target_client, transaction_params.clone()), finality_relay::FinalitySyncParams { tick: std::cmp::max( P::SourceChain::AVERAGE_BLOCK_INTERVAL, @@ -279,12 +279,12 @@ pub async fn run( /// Relay single header. No checks are made to ensure that transaction will succeed. pub async fn relay_single_header( - source_client: Client, - target_client: Client, + source_client: impl Client, + target_client: impl Client, transaction_params: TransactionParams>, header_number: BlockNumberOf, ) -> anyhow::Result<()> { - let finality_source = SubstrateFinalitySource::

::new(source_client, None); + let finality_source = SubstrateFinalitySource::::new(source_client, None); let (header, proof) = finality_source.header_and_finality_proof(header_number).await?; let Some(proof) = proof else { return Err(anyhow::format_err!( @@ -295,7 +295,7 @@ pub async fn relay_single_header( )); }; - let finality_target = SubstrateFinalityTarget::

::new(target_client, transaction_params); + let finality_target = SubstrateFinalityTarget::::new(target_client, transaction_params); let tx_tracker = finality_target.submit_finality_proof(header, proof, false).await?; match tx_tracker.wait().await { TrackedTransactionStatus::Finalized(_) => Ok(()), diff --git a/bridges/relays/lib-substrate-relay/src/finality/source.rs b/bridges/relays/lib-substrate-relay/src/finality/source.rs index c94af6108957a0d2d4b0b4079220be9c11a5a470..f6fa5c24add5066ab0c062a6966844b48be17ce8 100644 --- a/bridges/relays/lib-substrate-relay/src/finality/source.rs +++ b/bridges/relays/lib-substrate-relay/src/finality/source.rs @@ -40,22 +40,24 @@ use relay_utils::{relay_loop::Client as RelayClient, UniqueSaturatedInto}; pub type RequiredHeaderNumberRef = Arc::BlockNumber>>; /// Substrate node as finality source. -pub struct SubstrateFinalitySource { - client: Client, +pub struct SubstrateFinalitySource { + client: SourceClnt, maximal_header_number: Option>, } -impl SubstrateFinalitySource

{ +impl> + SubstrateFinalitySource +{ /// Create new headers source using given client. pub fn new( - client: Client, + client: SourceClnt, maximal_header_number: Option>, ) -> Self { SubstrateFinalitySource { client, maximal_header_number } } /// Returns reference to the underlying RPC client. - pub fn client(&self) -> &Client { + pub fn client(&self) -> &SourceClnt { &self.client } @@ -174,7 +176,9 @@ impl SubstrateFinalitySource

{ } } -impl Clone for SubstrateFinalitySource

{ +impl Clone + for SubstrateFinalitySource +{ fn clone(&self) -> Self { SubstrateFinalitySource { client: self.client.clone(), @@ -184,7 +188,9 @@ impl Clone for SubstrateFinalitySource

{ } #[async_trait] -impl RelayClient for SubstrateFinalitySource

{ +impl> RelayClient + for SubstrateFinalitySource +{ type Error = Error; async fn reconnect(&mut self) -> Result<(), Error> { @@ -193,8 +199,8 @@ impl RelayClient for SubstrateFinalitySource

SourceClientBase> - for SubstrateFinalitySource

+impl> + SourceClientBase> for SubstrateFinalitySource { type FinalityProofsStream = SubstrateFinalityProofsStream

; @@ -204,8 +210,8 @@ impl SourceClientBase SourceClient> - for SubstrateFinalitySource

+impl> + SourceClient> for SubstrateFinalitySource { async fn best_finalized_block_number(&self) -> Result, Error> { let mut finalized_header_number = self.on_chain_best_finalized_block_number().await?; @@ -235,7 +241,7 @@ impl SourceClient( - client: &Client, + client: &impl Client, number: BlockNumberOf, ) -> Result< ( @@ -244,8 +250,8 @@ async fn header_and_finality_proof( ), Error, > { - let header_hash = client.block_hash_by_number(number).await?; - let signed_block = client.get_block(Some(header_hash)).await?; + let header_hash = client.header_hash_by_number(number).await?; + let signed_block = client.block_by_hash(header_hash).await?; let justification = signed_block .justification(P::FinalityEngine::ID) diff --git a/bridges/relays/lib-substrate-relay/src/finality/target.rs b/bridges/relays/lib-substrate-relay/src/finality/target.rs index 52ab2462c62c4784b80bfbd128c11194a4f2edd4..18b696685dd4e7122a7ff6a9f7d7cb2afd333f5f 100644 --- a/bridges/relays/lib-substrate-relay/src/finality/target.rs +++ b/bridges/relays/lib-substrate-relay/src/finality/target.rs @@ -28,22 +28,25 @@ use async_trait::async_trait; use bp_runtime::BlockNumberOf; use finality_relay::TargetClient; use relay_substrate_client::{ - AccountKeyPairOf, Chain, Client, Error, HeaderIdOf, HeaderOf, SyncHeader, TransactionEra, - TransactionTracker, UnsignedTransaction, + AccountIdOf, AccountKeyPairOf, Chain, Client, Error, HeaderIdOf, HeaderOf, SyncHeader, + TransactionEra, TransactionTracker, UnsignedTransaction, }; use relay_utils::relay_loop::Client as RelayClient; +use sp_core::Pair; use sp_runtime::traits::Header; /// Substrate client as Substrate finality target. -pub struct SubstrateFinalityTarget { - client: Client, +pub struct SubstrateFinalityTarget { + client: TargetClnt, transaction_params: TransactionParams>, } -impl SubstrateFinalityTarget

{ +impl> + SubstrateFinalityTarget +{ /// Create new Substrate headers target. pub fn new( - client: Client, + client: TargetClnt, transaction_params: TransactionParams>, ) -> Self { SubstrateFinalityTarget { client, transaction_params } @@ -65,7 +68,9 @@ impl SubstrateFinalityTarget

{ } } -impl Clone for SubstrateFinalityTarget

{ +impl Clone + for SubstrateFinalityTarget +{ fn clone(&self) -> Self { SubstrateFinalityTarget { client: self.client.clone(), @@ -75,7 +80,9 @@ impl Clone for SubstrateFinalityTarget

{ } #[async_trait] -impl RelayClient for SubstrateFinalityTarget

{ +impl> RelayClient + for SubstrateFinalityTarget +{ type Error = Error; async fn reconnect(&mut self) -> Result<(), Error> { @@ -84,10 +91,12 @@ impl RelayClient for SubstrateFinalityTarget

TargetClient> - for SubstrateFinalityTarget

+impl> + TargetClient> for SubstrateFinalityTarget +where + AccountIdOf: From< as Pair>::Public>, { - type TransactionTracker = TransactionTracker>; + type TransactionTracker = TransactionTracker; async fn best_finalized_source_block_id(&self) -> Result, Error> { // we can't continue to relay finality if target node is out of sync, because @@ -109,10 +118,10 @@ impl TargetClient Result>, Self::Error> { Ok(self .client - .typed_state_call( + .state_call( + self.client.best_header().await?.hash(), P::SourceChain::FREE_HEADERS_INTERVAL_METHOD.into(), (), - Some(self.client.best_header().await?.hash()), ) .await .unwrap_or_else(|e| { diff --git a/bridges/relays/lib-substrate-relay/src/finality_base/engine.rs b/bridges/relays/lib-substrate-relay/src/finality_base/engine.rs index 5a9ec42fde5a38450def1a62935852fe77801df5..4f15d68771940812d8a2f05c5656440100033dab 100644 --- a/bridges/relays/lib-substrate-relay/src/finality_base/engine.rs +++ b/bridges/relays/lib-substrate-relay/src/finality_base/engine.rs @@ -28,10 +28,11 @@ use bp_header_chain::{ }; use bp_runtime::{BasicOperatingMode, HeaderIdProvider, OperatingMode}; use codec::{Decode, Encode}; +use futures::stream::StreamExt; use num_traits::{One, Zero}; use relay_substrate_client::{ BlockNumberOf, Chain, ChainWithGrandpa, Client, Error as SubstrateError, HashOf, HeaderOf, - Subscription, SubstrateFinalityClient, SubstrateGrandpaFinalityClient, + Subscription, }; use sp_consensus_grandpa::{AuthorityList as GrandpaAuthoritiesSet, GRANDPA_ENGINE_ID}; use sp_core::{storage::StorageKey, Bytes}; @@ -45,8 +46,6 @@ pub trait Engine: Send { const ID: ConsensusEngineId; /// A reader that can extract the consensus log from the header digest and interpret it. type ConsensusLogReader: ConsensusLogReader; - /// Type of Finality RPC client used by this engine. - type FinalityClient: SubstrateFinalityClient; /// Type of finality proofs, used by consensus engine. type FinalityProof: FinalityProof, BlockNumberOf> + Decode + Encode; /// The context needed for verifying finality proofs. @@ -74,10 +73,10 @@ pub trait Engine: Send { /// Returns `Ok(true)` if finality pallet at the bridged chain has already been initialized. async fn is_initialized( - target_client: &Client, + target_client: &impl Client, ) -> Result { Ok(target_client - .raw_storage_value(Self::is_initialized_key(), None) + .raw_storage_value(target_client.best_header_hash().await?, Self::is_initialized_key()) .await? .is_some()) } @@ -88,10 +87,13 @@ pub trait Engine: Send { /// Returns `Ok(true)` if finality pallet at the bridged chain is halted. async fn is_halted( - target_client: &Client, + target_client: &impl Client, ) -> Result { Ok(target_client - .storage_value::(Self::pallet_operating_mode_key(), None) + .storage_value::( + target_client.best_header_hash().await?, + Self::pallet_operating_mode_key(), + ) .await? .map(|operating_mode| operating_mode.is_halted()) .unwrap_or(false)) @@ -99,17 +101,15 @@ pub trait Engine: Send { /// A method to subscribe to encoded finality proofs, given source client. async fn source_finality_proofs( - source_client: &Client, - ) -> Result, SubstrateError> { - source_client.subscribe_finality_justifications::().await - } + source_client: &impl Client, + ) -> Result, SubstrateError>; /// Verify and optimize finality proof before sending it to the target node. /// /// Apart from optimization, we expect this method to perform all required checks /// that the `header` and `proof` are valid at the current state of the target chain. async fn verify_and_optimize_proof( - target_client: &Client, + target_client: &impl Client, header: &C::Header, proof: &mut Self::FinalityProof, ) -> Result; @@ -123,19 +123,19 @@ pub trait Engine: Send { /// Prepare initialization data for the finality bridge pallet. async fn prepare_initialization_data( - client: Client, + client: impl Client, ) -> Result, BlockNumberOf>>; /// Get the context needed for validating a finality proof. async fn finality_verification_context( - target_client: &Client, + target_client: &impl Client, at: HashOf, ) -> Result; /// Returns the finality info associated to the source headers synced with the target /// at the provided block. async fn synced_headers_finality_info( - target_client: &Client, + target_client: &impl Client, at: TargetChain::Hash, ) -> Result< Vec>, @@ -144,7 +144,7 @@ pub trait Engine: Send { /// Generate key ownership proof for the provided equivocation. async fn generate_source_key_ownership_proof( - source_client: &Client, + source_client: &impl Client, at: C::Hash, equivocation: &Self::EquivocationProof, ) -> Result; @@ -156,7 +156,7 @@ pub struct Grandpa(PhantomData); impl Grandpa { /// Read header by hash from the source client. async fn source_header( - source_client: &Client, + source_client: &impl Client, header_hash: C::Hash, ) -> Result, BlockNumberOf>> { source_client @@ -167,15 +167,15 @@ impl Grandpa { /// Read GRANDPA authorities set at given header. async fn source_authorities_set( - source_client: &Client, + source_client: &impl Client, header_hash: C::Hash, ) -> Result, BlockNumberOf>> { - let raw_authorities_set = source_client - .grandpa_authorities_set(header_hash) + const SUB_API_GRANDPA_AUTHORITIES: &str = "GrandpaApi_grandpa_authorities"; + + source_client + .state_call(header_hash, SUB_API_GRANDPA_AUTHORITIES.to_string(), ()) .await - .map_err(|err| Error::RetrieveAuthorities(C::NAME, header_hash, err))?; - GrandpaAuthoritiesSet::decode(&mut &raw_authorities_set[..]) - .map_err(|err| Error::DecodeAuthorities(C::NAME, header_hash, err)) + .map_err(|err| Error::RetrieveAuthorities(C::NAME, header_hash, err)) } } @@ -183,7 +183,6 @@ impl Grandpa { impl Engine for Grandpa { const ID: ConsensusEngineId = GRANDPA_ENGINE_ID; type ConsensusLogReader = GrandpaConsensusLogReader<::Number>; - type FinalityClient = SubstrateGrandpaFinalityClient; type FinalityProof = GrandpaJustification>; type FinalityVerificationContext = JustificationVerificationContext; type EquivocationProof = sp_consensus_grandpa::EquivocationProof, BlockNumberOf>; @@ -200,8 +199,14 @@ impl Engine for Grandpa { bp_header_chain::storage_keys::pallet_operating_mode_key(C::WITH_CHAIN_GRANDPA_PALLET_NAME) } + async fn source_finality_proofs( + client: &impl Client, + ) -> Result, SubstrateError> { + client.subscribe_grandpa_finality_justifications().await + } + async fn verify_and_optimize_proof( - target_client: &Client, + target_client: &impl Client, header: &C::Header, proof: &mut Self::FinalityProof, ) -> Result { @@ -239,7 +244,7 @@ impl Engine for Grandpa { /// Prepare initialization data for the GRANDPA verifier pallet. async fn prepare_initialization_data( - source_client: Client, + source_client: impl Client, ) -> Result, BlockNumberOf>> { // In ideal world we just need to get best finalized header and then to read GRANDPA // authorities set (`pallet_grandpa::CurrentSetId` + `GrandpaApi::grandpa_authorities()`) at @@ -248,17 +253,14 @@ impl Engine for Grandpa { // But now there are problems with this approach - `CurrentSetId` may return invalid value. // So here we're waiting for the next justification, read the authorities set and then try // to figure out the set id with bruteforce. - let justifications = Self::source_finality_proofs(&source_client) + let mut justifications = Self::source_finality_proofs(&source_client) .await .map_err(|err| Error::Subscribe(C::NAME, err))?; // Read next justification - the header that it finalizes will be used as initial header. let justification = justifications .next() .await - .map_err(|e| Error::ReadJustification(C::NAME, e)) - .and_then(|justification| { - justification.ok_or(Error::ReadJustificationStreamEnded(C::NAME)) - })?; + .ok_or(Error::ReadJustificationStreamEnded(C::NAME))?; // Read initial header. let justification: GrandpaJustification = @@ -359,14 +361,14 @@ impl Engine for Grandpa { } async fn finality_verification_context( - target_client: &Client, + target_client: &impl Client, at: HashOf, ) -> Result { let current_authority_set_key = bp_header_chain::storage_keys::current_authority_set_key( C::WITH_CHAIN_GRANDPA_PALLET_NAME, ); let authority_set: AuthoritySet = target_client - .storage_value(current_authority_set_key, Some(at)) + .storage_value(at, current_authority_set_key) .await? .map(Ok) .unwrap_or(Err(SubstrateError::Custom(format!( @@ -385,11 +387,11 @@ impl Engine for Grandpa { } async fn synced_headers_finality_info( - target_client: &Client, + target_client: &impl Client, at: TargetChain::Hash, ) -> Result>>, SubstrateError> { let stored_headers_grandpa_info: Vec>> = target_client - .typed_state_call(C::SYNCED_HEADERS_GRANDPA_INFO_METHOD.to_string(), (), Some(at)) + .state_call(at, C::SYNCED_HEADERS_GRANDPA_INFO_METHOD.to_string(), ()) .await?; let mut headers_grandpa_info = vec![]; @@ -407,7 +409,7 @@ impl Engine for Grandpa { } async fn generate_source_key_ownership_proof( - source_client: &Client, + source_client: &impl Client, at: C::Hash, equivocation: &Self::EquivocationProof, ) -> Result { diff --git a/bridges/relays/lib-substrate-relay/src/finality_base/mod.rs b/bridges/relays/lib-substrate-relay/src/finality_base/mod.rs index 825960b1b3ef2cc4f73b7565d6a2c8fe3e30fdd9..71d15ca3868e04da680f83387ac792b3a02a5f24 100644 --- a/bridges/relays/lib-substrate-relay/src/finality_base/mod.rs +++ b/bridges/relays/lib-substrate-relay/src/finality_base/mod.rs @@ -50,11 +50,11 @@ pub type SubstrateFinalityProofsStream

= /// Subscribe to new finality proofs. pub async fn finality_proofs( - client: &Client, + client: &impl Client, ) -> Result, Error> { Ok(unfold( P::FinalityEngine::source_finality_proofs(client).await?, - move |subscription| async move { + move |mut subscription| async move { loop { let log_error = |err| { log::error!( @@ -65,8 +65,7 @@ pub async fn finality_proofs( ); }; - let next_justification = - subscription.next().await.map_err(|err| log_error(err.to_string())).ok()??; + let next_justification = subscription.next().await?; let decoded_justification = >::FinalityProof::decode( @@ -93,7 +92,7 @@ pub async fn finality_proofs( /// /// The runtime API method should be `FinalityApi::best_finalized()`. pub async fn best_synced_header_id( - target_client: &Client, + target_client: &impl Client, at: HashOf, ) -> Result>, Error> where @@ -102,6 +101,6 @@ where { // now let's read id of best finalized peer header at our best finalized block target_client - .typed_state_call(SourceChain::BEST_FINALIZED_HEADER_ID_METHOD.into(), (), Some(at)) + .state_call(at, SourceChain::BEST_FINALIZED_HEADER_ID_METHOD.into(), ()) .await } diff --git a/bridges/relays/lib-substrate-relay/src/messages_lane.rs b/bridges/relays/lib-substrate-relay/src/messages_lane.rs index 08550d19bae03aaf955c81800267cd80f9ce0f20..e3786dcdc5e31dad2cdf00ba2db073adb87f78b2 100644 --- a/bridges/relays/lib-substrate-relay/src/messages_lane.rs +++ b/bridges/relays/lib-substrate-relay/src/messages_lane.rs @@ -88,13 +88,13 @@ impl MessageLane for MessageLaneAdapter

{ } /// Substrate <-> Substrate messages relay parameters. -pub struct MessagesRelayParams { +pub struct MessagesRelayParams { /// Messages source client. - pub source_client: Client, + pub source_client: SourceClnt, /// Source transaction params. pub source_transaction_params: TransactionParams>, /// Messages target client. - pub target_client: Client, + pub target_client: TargetClnt, /// Target transaction params. pub target_transaction_params: TransactionParams>, /// Optional on-demand source to target headers relay. @@ -179,8 +179,13 @@ impl>> } /// Run Substrate-to-Substrate messages sync loop. -pub async fn run(params: MessagesRelayParams

) -> anyhow::Result<()> +pub async fn run( + params: MessagesRelayParams, +) -> anyhow::Result<()> where + P: SubstrateMessageLane, + SourceClnt: Client, + TargetClnt: Client, AccountIdOf: From< as Pair>::Public>, AccountIdOf: From< as Pair>::Public>, BalanceOf: TryFrom>, @@ -190,7 +195,7 @@ where let limits = match params.limits { Some(limits) => limits, None => - select_delivery_transaction_limits_rpc::

( + select_delivery_transaction_limits_rpc( ¶ms, P::TargetChain::max_extrinsic_weight(), P::SourceChain::MAX_UNREWARDED_RELAYERS_IN_CONFIRMATION_TX, @@ -250,14 +255,14 @@ where max_messages_size_in_single_batch, }, }, - SubstrateMessagesSource::

::new( + SubstrateMessagesSource::::new( source_client.clone(), target_client.clone(), params.lane_id, params.source_transaction_params, params.target_to_source_headers_relay, ), - SubstrateMessagesTarget::

::new( + SubstrateMessagesTarget::::new( target_client, source_client, params.lane_id, @@ -278,8 +283,8 @@ where /// Deliver range of Substrate-to-Substrate messages. No checks are made to ensure that transaction /// will succeed. pub async fn relay_messages_range( - source_client: Client, - target_client: Client, + source_client: impl Client, + target_client: impl Client, source_transaction_params: TransactionParams>, target_transaction_params: TransactionParams>, at_source_block: HeaderIdOf, @@ -295,14 +300,14 @@ where let relayer_id_at_source: AccountIdOf = source_transaction_params.signer.public().into(); messages_relay::relay_messages_range( - SubstrateMessagesSource::

::new( + SubstrateMessagesSource::::new( source_client.clone(), target_client.clone(), lane_id, source_transaction_params, None, ), - SubstrateMessagesTarget::

::new( + SubstrateMessagesTarget::::new( target_client, source_client, lane_id, @@ -321,8 +326,8 @@ where /// Relay messages delivery confirmation of Substrate-to-Substrate messages. /// No checks are made to ensure that transaction will succeed. pub async fn relay_messages_delivery_confirmation( - source_client: Client, - target_client: Client, + source_client: impl Client, + target_client: impl Client, source_transaction_params: TransactionParams>, at_target_block: HeaderIdOf, lane_id: LaneId, @@ -335,14 +340,14 @@ where let relayer_id_at_source: AccountIdOf = source_transaction_params.signer.public().into(); messages_relay::relay_messages_delivery_confirmation( - SubstrateMessagesSource::

::new( + SubstrateMessagesSource::::new( source_client.clone(), target_client.clone(), lane_id, source_transaction_params, None, ), - SubstrateMessagesTarget::

::new( + SubstrateMessagesTarget::::new( target_client, source_client, lane_id, @@ -546,12 +551,15 @@ macro_rules! generate_receive_message_delivery_proof_call_builder { } /// Returns maximal number of messages and their maximal cumulative dispatch weight. -async fn select_delivery_transaction_limits_rpc( - params: &MessagesRelayParams

, +async fn select_delivery_transaction_limits_rpc( + params: &MessagesRelayParams, max_extrinsic_weight: Weight, max_unconfirmed_messages_at_inbound_lane: MessageNonce, ) -> anyhow::Result where + P: SubstrateMessageLane, + SourceClnt: Client, + TargetClnt: Client, AccountIdOf: From< as Pair>::Public>, { // We may try to guess accurate value, based on maximal number of messages and per-message @@ -567,20 +575,21 @@ where let weight_for_messages_dispatch = max_extrinsic_weight - weight_for_delivery_tx; // weight of empty message delivery with outbound lane state - let delivery_tx_with_zero_messages = dummy_messages_delivery_transaction::

(params, 0)?; + let best_target_block_hash = params.target_client.best_header_hash().await?; + let delivery_tx_with_zero_messages = dummy_messages_delivery_transaction::(params, 0)?; let delivery_tx_with_zero_messages_weight = params .target_client - .extimate_extrinsic_weight(delivery_tx_with_zero_messages) + .estimate_extrinsic_weight(best_target_block_hash, delivery_tx_with_zero_messages) .await .map_err(|e| { anyhow::format_err!("Failed to estimate delivery extrinsic weight: {:?}", e) })?; // weight of single message delivery with outbound lane state - let delivery_tx_with_one_message = dummy_messages_delivery_transaction::

(params, 1)?; + let delivery_tx_with_one_message = dummy_messages_delivery_transaction::(params, 1)?; let delivery_tx_with_one_message_weight = params .target_client - .extimate_extrinsic_weight(delivery_tx_with_one_message) + .estimate_extrinsic_weight(best_target_block_hash, delivery_tx_with_one_message) .await .map_err(|e| { anyhow::format_err!("Failed to estimate delivery extrinsic weight: {:?}", e) @@ -615,8 +624,8 @@ where } /// Returns dummy message delivery transaction with zero messages and `1kb` proof. -fn dummy_messages_delivery_transaction( - params: &MessagesRelayParams

, +fn dummy_messages_delivery_transaction( + params: &MessagesRelayParams, messages: u32, ) -> anyhow::Result<::SignedTransaction> where diff --git a/bridges/relays/lib-substrate-relay/src/messages_metrics.rs b/bridges/relays/lib-substrate-relay/src/messages_metrics.rs index b30e75bd8bacbbd25c056eb7d499cc18d040f991..8845f43dcb62aa778b50354141381290fc0b897d 100644 --- a/bridges/relays/lib-substrate-relay/src/messages_metrics.rs +++ b/bridges/relays/lib-substrate-relay/src/messages_metrics.rs @@ -36,7 +36,7 @@ use std::{fmt::Debug, marker::PhantomData}; /// Add relay accounts balance metrics. pub async fn add_relay_balances_metrics( - client: Client, + client: impl Client, metrics: &MetricsParams, relay_accounts: &Vec>>, lanes: &[LaneId], diff --git a/bridges/relays/lib-substrate-relay/src/messages_source.rs b/bridges/relays/lib-substrate-relay/src/messages_source.rs index 49deff046f9ca0914846d19b18653f85b8cd8554..1f597e278da404a5c3d8d0dff0032030d96ed433 100644 --- a/bridges/relays/lib-substrate-relay/src/messages_source.rs +++ b/bridges/relays/lib-substrate-relay/src/messages_source.rs @@ -63,19 +63,21 @@ pub type SubstrateMessagesProof = (Weight, FromBridgedChainMessagesProof = Vec<(MessagePayload, &'a mut OutboundMessageDetails)>; /// Substrate client as Substrate messages source. -pub struct SubstrateMessagesSource { - source_client: Client, - target_client: Client, +pub struct SubstrateMessagesSource { + source_client: SourceClnt, + target_client: TargetClnt, lane_id: LaneId, transaction_params: TransactionParams>, target_to_source_headers_relay: Option>>, } -impl SubstrateMessagesSource

{ +impl, TargetClnt> + SubstrateMessagesSource +{ /// Create new Substrate headers source. pub fn new( - source_client: Client, - target_client: Client, + source_client: SourceClnt, + target_client: TargetClnt, lane_id: LaneId, transaction_params: TransactionParams>, target_to_source_headers_relay: Option< @@ -98,22 +100,25 @@ impl SubstrateMessagesSource

{ ) -> Result, SubstrateError> { self.source_client .storage_value( + id.hash(), outbound_lane_data_key( P::TargetChain::WITH_CHAIN_MESSAGES_PALLET_NAME, &self.lane_id, ), - Some(id.1), ) .await } /// Ensure that the messages pallet at source chain is active. async fn ensure_pallet_active(&self) -> Result<(), SubstrateError> { - ensure_messages_pallet_active::(&self.source_client).await + ensure_messages_pallet_active::(&self.source_client) + .await } } -impl Clone for SubstrateMessagesSource

{ +impl Clone + for SubstrateMessagesSource +{ fn clone(&self) -> Self { Self { source_client: self.source_client.clone(), @@ -126,7 +131,12 @@ impl Clone for SubstrateMessagesSource

{ } #[async_trait] -impl RelayClient for SubstrateMessagesSource

{ +impl< + P: SubstrateMessageLane, + SourceClnt: Client, + TargetClnt: Client, + > RelayClient for SubstrateMessagesSource +{ type Error = SubstrateError; async fn reconnect(&mut self) -> Result<(), SubstrateError> { @@ -150,13 +160,17 @@ impl RelayClient for SubstrateMessagesSource

{ } #[async_trait] -impl SourceClient> for SubstrateMessagesSource

+impl< + P: SubstrateMessageLane, + SourceClnt: Client, + TargetClnt: Client, + > SourceClient> for SubstrateMessagesSource where AccountIdOf: From< as Pair>::Public>, { type BatchTransaction = BatchProofTransaction; - type TransactionTracker = TransactionTracker>; + type TransactionTracker = TransactionTracker; async fn state(&self) -> Result>, SubstrateError> { // we can't continue to deliver confirmations if source node is out of sync, because @@ -169,7 +183,7 @@ where // we can't relay confirmations if messages pallet at source chain is halted self.ensure_pallet_active().await?; - read_client_state(&self.source_client, Some(&self.target_client)).await + read_client_state_from_both_chains(&self.source_client, &self.target_client).await } async fn latest_generated_nonce( @@ -203,12 +217,12 @@ where id: SourceHeaderIdOf>, nonces: RangeInclusive, ) -> Result>, SubstrateError> { - let mut out_msgs_details = self + let mut out_msgs_details: Vec<_> = self .source_client - .typed_state_call::<_, Vec<_>>( + .state_call::<_, Vec<_>>( + id.hash(), P::TargetChain::TO_CHAIN_MESSAGE_DETAILS_METHOD.into(), (self.lane_id, *nonces.start(), *nonces.end()), - Some(id.1), ) .await?; validate_out_msgs_details::(&out_msgs_details, nonces)?; @@ -226,7 +240,7 @@ where out_msg_details.nonce, ); let msg_payload: MessagePayload = - self.source_client.storage_value(msg_key, Some(id.1)).await?.ok_or_else(|| { + self.source_client.storage_value(id.hash(), msg_key).await?.ok_or_else(|| { SubstrateError::Custom(format!( "Message to {} {:?}/{} is missing from runtime the storage of {} at {:?}", P::TargetChain::NAME, @@ -240,15 +254,16 @@ where msgs_to_refine.push((msg_payload, out_msg_details)); } + let best_target_header_hash = self.target_client.best_header_hash().await?; for mut msgs_to_refine_batch in split_msgs_to_refine::(self.lane_id, msgs_to_refine)? { let in_msgs_details = self .target_client - .typed_state_call::<_, Vec>( + .state_call::<_, Vec>( + best_target_header_hash, P::SourceChain::FROM_CHAIN_MESSAGE_DETAILS_METHOD.into(), (self.lane_id, &msgs_to_refine_batch), - None, ) .await?; if in_msgs_details.len() != msgs_to_refine_batch.len() { @@ -326,7 +341,7 @@ where let proof = self .source_client - .prove_storage(storage_keys, id.1) + .prove_storage(id.1, storage_keys) .await? .into_iter_nodes() .collect(); @@ -387,15 +402,19 @@ where } /// Ensure that the messages pallet at source chain is active. -pub(crate) async fn ensure_messages_pallet_active( - client: &Client, +pub(crate) async fn ensure_messages_pallet_active( + client: &AtChainClient, ) -> Result<(), SubstrateError> where AtChain: ChainWithMessages, WithChain: ChainWithMessages, + AtChainClient: Client, { let operating_mode = client - .storage_value(operating_mode_key(WithChain::WITH_CHAIN_MESSAGES_PALLET_NAME), None) + .storage_value( + client.best_header_hash().await?, + operating_mode_key(WithChain::WITH_CHAIN_MESSAGES_PALLET_NAME), + ) .await?; let is_halted = operating_mode == Some(MessagesOperatingMode::Basic(BasicOperatingMode::Halted)); @@ -412,11 +431,10 @@ where /// bridge GRANDPA pallet deployed and it provides `best_finalized_header_id_method_name` /// runtime API to read the best finalized Bridged chain header. /// -/// If `peer_client` is `None`, the value of `actual_best_finalized_peer_at_best_self` will -/// always match the `best_finalized_peer_at_best_self`. +/// The value of `actual_best_finalized_peer_at_best_self` will always match +/// the `best_finalized_peer_at_best_self`. pub async fn read_client_state( - self_client: &Client, - peer_client: Option<&Client>, + self_client: &impl Client, ) -> Result, HeaderIdOf>, SubstrateError> where SelfChain: Chain, @@ -431,30 +449,42 @@ where let peer_on_self_best_finalized_id = best_synced_header_id::(self_client, self_best_id.hash()).await?; - // read actual header, matching the `peer_on_self_best_finalized_id` from the peer chain - let actual_peer_on_self_best_finalized_id = - match (peer_client, peer_on_self_best_finalized_id.as_ref()) { - (Some(peer_client), Some(peer_on_self_best_finalized_id)) => { - let actual_peer_on_self_best_finalized = - peer_client.header_by_number(peer_on_self_best_finalized_id.number()).await?; - Some(actual_peer_on_self_best_finalized.id()) - }, - _ => peer_on_self_best_finalized_id, - }; - Ok(ClientState { best_self: self_best_id, best_finalized_self: self_best_finalized_id, best_finalized_peer_at_best_self: peer_on_self_best_finalized_id, - actual_best_finalized_peer_at_best_self: actual_peer_on_self_best_finalized_id, + actual_best_finalized_peer_at_best_self: peer_on_self_best_finalized_id, }) } +/// Does the same stuff as `read_client_state`, but properly fills the +/// `actual_best_finalized_peer_at_best_self` field of the result. +pub async fn read_client_state_from_both_chains( + self_client: &impl Client, + peer_client: &impl Client, +) -> Result, HeaderIdOf>, SubstrateError> +where + SelfChain: Chain, + PeerChain: Chain, +{ + let mut client_state = read_client_state::(self_client).await?; + client_state.actual_best_finalized_peer_at_best_self = + match client_state.best_finalized_peer_at_best_self.as_ref() { + Some(peer_on_self_best_finalized_id) => { + let actual_peer_on_self_best_finalized = + peer_client.header_by_number(peer_on_self_best_finalized_id.number()).await?; + Some(actual_peer_on_self_best_finalized.id()) + }, + _ => client_state.best_finalized_peer_at_best_self, + }; + Ok(client_state) +} + /// Reads best `PeerChain` header known to the `SelfChain` using provided runtime API method. /// /// Method is supposed to be the `FinalityApi::best_finalized()` method. pub async fn best_finalized_peer_header_at_self( - self_client: &Client, + self_client: &impl Client, at_self_hash: HashOf, ) -> Result>, SubstrateError> where @@ -463,10 +493,10 @@ where { // now let's read id of best finalized peer header at our best finalized block self_client - .typed_state_call::<_, Option<_>>( + .state_call::<_, Option<_>>( + at_self_hash, PeerChain::BEST_FINALIZED_HEADER_ID_METHOD.into(), (), - Some(at_self_hash), ) .await } diff --git a/bridges/relays/lib-substrate-relay/src/messages_target.rs b/bridges/relays/lib-substrate-relay/src/messages_target.rs index 5ffb2b6c771e0fec2bf44640993abba3706cb0a5..e1c7645eac6834ed8768ef6f416ce415c37653cf 100644 --- a/bridges/relays/lib-substrate-relay/src/messages_target.rs +++ b/bridges/relays/lib-substrate-relay/src/messages_target.rs @@ -23,7 +23,9 @@ use crate::{ BatchProofTransaction, MessageLaneAdapter, ReceiveMessagesProofCallBuilder, SubstrateMessageLane, }, - messages_source::{ensure_messages_pallet_active, read_client_state, SubstrateMessagesProof}, + messages_source::{ + ensure_messages_pallet_active, read_client_state_from_both_chains, SubstrateMessagesProof, + }, on_demand::OnDemandRelay, TransactionParams, }; @@ -52,20 +54,24 @@ pub type SubstrateMessagesDeliveryProof = (UnrewardedRelayersState, FromBridgedChainMessagesDeliveryProof>); /// Substrate client as Substrate messages target. -pub struct SubstrateMessagesTarget { - target_client: Client, - source_client: Client, +pub struct SubstrateMessagesTarget { + target_client: TargetClnt, + source_client: SourceClnt, lane_id: LaneId, relayer_id_at_source: AccountIdOf, transaction_params: Option>>, source_to_target_headers_relay: Option>>, } -impl SubstrateMessagesTarget

{ +impl SubstrateMessagesTarget +where + P: SubstrateMessageLane, + TargetClnt: Client, +{ /// Create new Substrate headers target. pub fn new( - target_client: Client, - source_client: Client, + target_client: TargetClnt, + source_client: SourceClnt, lane_id: LaneId, relayer_id_at_source: AccountIdOf, transaction_params: Option>>, @@ -90,22 +96,25 @@ impl SubstrateMessagesTarget

{ ) -> Result>>, SubstrateError> { self.target_client .storage_value( + id.hash(), inbound_lane_data_key( P::SourceChain::WITH_CHAIN_MESSAGES_PALLET_NAME, &self.lane_id, ), - Some(id.1), ) .await } /// Ensure that the messages pallet at target chain is active. async fn ensure_pallet_active(&self) -> Result<(), SubstrateError> { - ensure_messages_pallet_active::(&self.target_client).await + ensure_messages_pallet_active::(&self.target_client) + .await } } -impl Clone for SubstrateMessagesTarget

{ +impl Clone + for SubstrateMessagesTarget +{ fn clone(&self) -> Self { Self { target_client: self.target_client.clone(), @@ -119,7 +128,12 @@ impl Clone for SubstrateMessagesTarget

{ } #[async_trait] -impl RelayClient for SubstrateMessagesTarget

{ +impl< + P: SubstrateMessageLane, + SourceClnt: Client, + TargetClnt: Client, + > RelayClient for SubstrateMessagesTarget +{ type Error = SubstrateError; async fn reconnect(&mut self) -> Result<(), SubstrateError> { @@ -143,14 +157,18 @@ impl RelayClient for SubstrateMessagesTarget

{ } #[async_trait] -impl TargetClient> for SubstrateMessagesTarget

+impl< + P: SubstrateMessageLane, + SourceClnt: Client, + TargetClnt: Client, + > TargetClient> for SubstrateMessagesTarget where AccountIdOf: From< as Pair>::Public>, BalanceOf: TryFrom>, { type BatchTransaction = BatchProofTransaction; - type TransactionTracker = TransactionTracker>; + type TransactionTracker = TransactionTracker; async fn state(&self) -> Result>, SubstrateError> { // we can't continue to deliver confirmations if source node is out of sync, because @@ -163,7 +181,7 @@ where // we can't relay messages if messages pallet at target chain is halted self.ensure_pallet_active().await?; - read_client_state(&self.target_client, Some(&self.source_client)).await + read_client_state_from_both_chains(&self.target_client, &self.source_client).await } async fn latest_received_nonce( @@ -219,7 +237,7 @@ where ); let proof = self .target_client - .prove_storage(vec![inbound_data_key], id.1) + .prove_storage(id.hash(), vec![inbound_data_key]) .await? .into_iter_nodes() .collect(); diff --git a/bridges/relays/lib-substrate-relay/src/on_demand/headers.rs b/bridges/relays/lib-substrate-relay/src/on_demand/headers.rs index 202f53ea4e4f50510f125f28da86de878125d581..d18c582dfac4340a72f1bebd2eea3cabd0563dbe 100644 --- a/bridges/relays/lib-substrate-relay/src/on_demand/headers.rs +++ b/bridges/relays/lib-substrate-relay/src/on_demand/headers.rs @@ -53,25 +53,30 @@ use crate::{ /// relay) needs it to continue its regular work. When enough headers are relayed, on-demand stops /// syncing headers. #[derive(Clone)] -pub struct OnDemandHeadersRelay { +pub struct OnDemandHeadersRelay { /// Relay task name. relay_task_name: String, /// Shared reference to maximal required finalized header number. required_header_number: RequiredHeaderNumberRef, /// Client of the source chain. - source_client: Client, + source_client: SourceClnt, /// Client of the target chain. - target_client: Client, + target_client: TargetClnt, } -impl OnDemandHeadersRelay

{ +impl< + P: SubstrateFinalitySyncPipeline, + SourceClnt: Client, + TargetClnt: Client, + > OnDemandHeadersRelay +{ /// Create new on-demand headers relay. /// /// If `metrics_params` is `Some(_)`, the metrics of the finality relay are registered. /// Otherwise, all required metrics must be exposed outside of this method. pub fn new( - source_client: Client, - target_client: Client, + source_client: SourceClnt, + target_client: TargetClnt, target_transaction_params: TransactionParams>, headers_to_relay: HeadersToRelay, metrics_params: Option, @@ -104,8 +109,12 @@ impl OnDemandHeadersRelay

{ } #[async_trait] -impl OnDemandRelay - for OnDemandHeadersRelay

+impl< + P: SubstrateFinalitySyncPipeline, + SourceClnt: Client, + TargetClnt: Client, + > OnDemandRelay + for OnDemandHeadersRelay { async fn reconnect(&self) -> Result<(), SubstrateError> { // using clone is fine here (to avoid mut requirement), because clone on Client clones @@ -139,7 +148,7 @@ impl OnDemandRelay::new(self.source_client.clone(), None); + SubstrateFinalitySource::::new(self.source_client.clone(), None); let (header, mut proof) = finality_source.prove_block_finality(current_required_header).await?; let header_id = header.id(); @@ -198,8 +207,8 @@ impl OnDemandRelay( - source_client: Client, - target_client: Client, + source_client: impl Client, + target_client: impl Client, target_transaction_params: TransactionParams>, headers_to_relay: HeadersToRelay, required_header_number: RequiredHeaderNumberRef, @@ -209,7 +218,7 @@ async fn background_task( { let relay_task_name = on_demand_headers_relay_name::(); let target_transactions_mortality = target_transaction_params.mortality; - let mut finality_source = SubstrateFinalitySource::

::new( + let mut finality_source = SubstrateFinalitySource::::new( source_client.clone(), Some(required_header_number.clone()), ); @@ -246,7 +255,8 @@ async fn background_task( // read best finalized source header number from target let best_finalized_source_header_at_target = - best_finalized_source_header_at_target::

(&finality_target, &relay_task_name).await; + best_finalized_source_header_at_target::(&finality_target, &relay_task_name) + .await; if matches!(best_finalized_source_header_at_target, Err(ref e) if e.is_connection_error()) { relay_utils::relay_loop::reconnect_failed_client( FailedClient::Target, @@ -410,13 +420,17 @@ async fn mandatory_headers_scan_range( /// it. /// /// Returns `true` if header was found and (asked to be) relayed and `false` otherwise. -async fn relay_mandatory_header_from_range( - finality_source: &SubstrateFinalitySource

, +async fn relay_mandatory_header_from_range( + finality_source: &SubstrateFinalitySource, required_header_number: &RequiredHeaderNumberRef, best_finalized_source_header_at_target: String, range: (BlockNumberOf, BlockNumberOf), relay_task_name: &str, -) -> Result { +) -> Result +where + P: SubstrateFinalitySyncPipeline, + SourceClnt: Client, +{ // search for mandatory header first let mandatory_source_header_number = find_mandatory_header_in_range(finality_source, range).await?; @@ -451,10 +465,14 @@ async fn relay_mandatory_header_from_range( /// Read best finalized source block number from source client. /// /// Returns `None` if we have failed to read the number. -async fn best_finalized_source_header_at_source( - finality_source: &SubstrateFinalitySource

, +async fn best_finalized_source_header_at_source( + finality_source: &SubstrateFinalitySource, relay_task_name: &str, -) -> Result, relay_substrate_client::Error> { +) -> Result, relay_substrate_client::Error> +where + P: SubstrateFinalitySyncPipeline, + SourceClnt: Client, +{ finality_source.on_chain_best_finalized_block_number().await.map_err(|error| { log::error!( target: "bridge", @@ -470,11 +488,16 @@ async fn best_finalized_source_header_at_source( - finality_target: &SubstrateFinalityTarget

, +async fn best_finalized_source_header_at_target( + finality_target: &SubstrateFinalityTarget, relay_task_name: &str, -) -> Result, as RelayClient>::Error> +) -> Result< + BlockNumberOf, + as RelayClient>::Error, +> where + P: SubstrateFinalitySyncPipeline, + TargetClnt: Client, AccountIdOf: From< as sp_core::Pair>::Public>, { finality_target @@ -496,10 +519,14 @@ where /// Read first mandatory header in given inclusive range. /// /// Returns `Ok(None)` if there were no mandatory headers in the range. -async fn find_mandatory_header_in_range( - finality_source: &SubstrateFinalitySource

, +async fn find_mandatory_header_in_range( + finality_source: &SubstrateFinalitySource, range: (BlockNumberOf, BlockNumberOf), -) -> Result>, relay_substrate_client::Error> { +) -> Result>, relay_substrate_client::Error> +where + P: SubstrateFinalitySyncPipeline, + SourceClnt: Client, +{ let mut current = range.0; while current <= range.1 { let header = finality_source.client().header_by_number(current).await?; 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 966bdc3107203a61cf405adba2cf09124330954e..654cb6628d5f062d5790a2d14ffa1ae6fadb7475 100644 --- a/bridges/relays/lib-substrate-relay/src/on_demand/parachains.rs +++ b/bridges/relays/lib-substrate-relay/src/on_demand/parachains.rs @@ -53,29 +53,34 @@ use std::fmt::Debug; /// (e.g. messages relay) needs it to continue its regular work. When enough parachain headers /// are relayed, on-demand stops syncing headers. #[derive(Clone)] -pub struct OnDemandParachainsRelay { +pub struct OnDemandParachainsRelay { /// Relay task name. relay_task_name: String, /// Channel used to communicate with background task and ask for relay of parachain heads. required_header_number_sender: Sender>, /// Source relay chain client. - source_relay_client: Client, + source_relay_client: SourceRelayClnt, /// Target chain client. - target_client: Client, + target_client: TargetClnt, /// On-demand relay chain relay. on_demand_source_relay_to_target_headers: Arc>, } -impl OnDemandParachainsRelay

{ +impl< + P: SubstrateParachainsPipeline, + SourceRelayClnt: Client, + TargetClnt: Client, + > OnDemandParachainsRelay +{ /// Create new on-demand parachains relay. /// /// Note that the argument is the source relay chain client, not the parachain client. /// That's because parachain finality is determined by the relay chain and we don't /// need to connect to the parachain itself here. pub fn new( - source_relay_client: Client, - target_client: Client, + source_relay_client: SourceRelayClnt, + target_client: TargetClnt, target_transaction_params: TransactionParams>, on_demand_source_relay_to_target_headers: Arc< dyn OnDemandRelay, @@ -114,10 +119,13 @@ impl OnDemandParachainsRelay

{ } #[async_trait] -impl OnDemandRelay - for OnDemandParachainsRelay

+impl + OnDemandRelay + for OnDemandParachainsRelay where P::SourceParachain: Chain, + SourceRelayClnt: Client, + TargetClnt: Client, { async fn reconnect(&self) -> Result<(), SubstrateError> { // using clone is fine here (to avoid mut requirement), because clone on Client clones @@ -147,7 +155,7 @@ where required_parachain_header: BlockNumberOf, ) -> Result<(HeaderIdOf, Vec>), SubstrateError> { // select headers to prove - let parachains_source = ParachainsSource::

::new( + let parachains_source = ParachainsSource::::new( self.source_relay_client.clone(), Arc::new(Mutex::new(AvailableHeader::Missing)), ); @@ -231,8 +239,8 @@ where /// Background task that is responsible for starting parachain headers relay. async fn background_task( - source_relay_client: Client, - target_client: Client, + source_relay_client: impl Client, + target_client: impl Client, target_transaction_params: TransactionParams>, on_demand_source_relay_to_target_headers: Arc< dyn OnDemandRelay, @@ -255,9 +263,11 @@ async fn background_task( let parachains_relay_task = futures::future::Fuse::terminated(); futures::pin_mut!(parachains_relay_task); - let mut parachains_source = - ParachainsSource::

::new(source_relay_client.clone(), required_para_header_ref.clone()); - let mut parachains_target = ParachainsTarget::

::new( + let mut parachains_source = ParachainsSource::::new( + source_relay_client.clone(), + required_para_header_ref.clone(), + ); + let mut parachains_target = ParachainsTarget::::new( source_relay_client.clone(), target_client.clone(), target_transaction_params.clone(), @@ -446,9 +456,9 @@ struct RelayData { } /// Read required data from source and target clients. -async fn read_relay_data( - source: &ParachainsSource

, - target: &ParachainsTarget

, +async fn read_relay_data( + source: &ParachainsSource, + target: &ParachainsTarget, required_header_number: BlockNumberOf, ) -> Result< RelayData< @@ -459,7 +469,9 @@ async fn read_relay_data( FailedClient, > where - ParachainsTarget

: + SourceRelayClnt: Client, + TargetClnt: Client, + ParachainsTarget: TargetClient> + RelayClient, { let map_target_err = |e| { @@ -642,13 +654,19 @@ trait SelectHeadersToProveEnvironment { } #[async_trait] -impl<'a, P: SubstrateParachainsPipeline> +impl<'a, P: SubstrateParachainsPipeline, SourceRelayClnt, TargetClnt> SelectHeadersToProveEnvironment< BlockNumberOf, HashOf, BlockNumberOf, HashOf, - > for (&'a OnDemandParachainsRelay

, &'a ParachainsSource

) + > + for ( + &'a OnDemandParachainsRelay, + &'a ParachainsSource, + ) where + SourceRelayClnt: Client, + TargetClnt: Client, { fn parachain_id(&self) -> ParaId { ParaId(P::SourceParachain::PARACHAIN_ID) @@ -665,7 +683,6 @@ impl<'a, P: SubstrateParachainsPipeline> ) -> Result, SubstrateError> { Ok(crate::messages_source::read_client_state::( &self.0.target_client, - None, ) .await? .best_finalized_peer_at_best_self diff --git a/bridges/relays/lib-substrate-relay/src/parachains/source.rs b/bridges/relays/lib-substrate-relay/src/parachains/source.rs index 4cc512b9d9b45c7334ffb121c1a8613b7f118550..11b9d6dbf5bd3fe12a4249ac9c2f9864291392d7 100644 --- a/bridges/relays/lib-substrate-relay/src/parachains/source.rs +++ b/bridges/relays/lib-substrate-relay/src/parachains/source.rs @@ -37,22 +37,24 @@ pub type RequiredHeaderIdRef = Arc>>>; /// Substrate client as parachain heads source. #[derive(Clone)] -pub struct ParachainsSource { - client: Client, +pub struct ParachainsSource { + client: SourceRelayClnt, max_head_id: RequiredHeaderIdRef, } -impl ParachainsSource

{ +impl> + ParachainsSource +{ /// Creates new parachains source client. pub fn new( - client: Client, + client: SourceRelayClnt, max_head_id: RequiredHeaderIdRef, ) -> Self { ParachainsSource { client, max_head_id } } /// Returns reference to the underlying RPC client. - pub fn client(&self) -> &Client { + pub fn client(&self) -> &SourceRelayClnt { &self.client } @@ -64,8 +66,8 @@ impl ParachainsSource

{ let para_id = ParaId(P::SourceParachain::PARACHAIN_ID); let storage_key = parachain_head_storage_key_at_source(P::SourceRelayChain::PARAS_PALLET_NAME, para_id); - let para_head = self.client.raw_storage_value(storage_key, Some(at_block.1)).await?; - let para_head = para_head.map(|h| ParaHead::decode(&mut &h.0[..])).transpose()?; + let para_head: Option = + self.client.storage_value(at_block.hash(), storage_key).await?; let para_head = match para_head { Some(para_head) => para_head, None => return Ok(None), @@ -76,7 +78,9 @@ impl ParachainsSource

{ } #[async_trait] -impl RelayClient for ParachainsSource

{ +impl> RelayClient + for ParachainsSource +{ type Error = SubstrateError; async fn reconnect(&mut self) -> Result<(), SubstrateError> { @@ -85,8 +89,8 @@ impl RelayClient for ParachainsSource

{ } #[async_trait] -impl SourceClient> - for ParachainsSource

+impl> + SourceClient> for ParachainsSource where P::SourceParachain: Chain, { @@ -151,7 +155,7 @@ where parachain_head_storage_key_at_source(P::SourceRelayChain::PARAS_PALLET_NAME, parachain); let parachain_heads_proof = self .client - .prove_storage(vec![storage_key.clone()], at_block.1) + .prove_storage(at_block.hash(), vec![storage_key.clone()]) .await? .into_iter_nodes() .collect(); @@ -165,10 +169,8 @@ where // rereading actual value here let parachain_head = self .client - .raw_storage_value(storage_key, Some(at_block.1)) + .storage_value::(at_block.hash(), storage_key) .await? - .map(|h| ParaHead::decode(&mut &h.0[..])) - .transpose()? .ok_or_else(|| { SubstrateError::Custom(format!( "Failed to read expected parachain {parachain:?} head at {at_block:?}" diff --git a/bridges/relays/lib-substrate-relay/src/parachains/target.rs b/bridges/relays/lib-substrate-relay/src/parachains/target.rs index 531d55b53223609c523d521f43a38336353c597f..f66b193340c1a5e243b3bca17a111ed20f422c37 100644 --- a/bridges/relays/lib-substrate-relay/src/parachains/target.rs +++ b/bridges/relays/lib-substrate-relay/src/parachains/target.rs @@ -42,31 +42,42 @@ use relay_substrate_client::{ }; use relay_utils::relay_loop::Client as RelayClient; use sp_core::Pair; +use sp_runtime::traits::Header; /// Substrate client as parachain heads source. -pub struct ParachainsTarget { - source_client: Client, - target_client: Client, +pub struct ParachainsTarget { + source_client: SourceClnt, + target_client: TargetClnt, transaction_params: TransactionParams>, } -impl ParachainsTarget

{ +impl< + P: SubstrateParachainsPipeline, + SourceClnt: Client, + TargetClnt: Client, + > ParachainsTarget +{ /// Creates new parachains target client. pub fn new( - source_client: Client, - target_client: Client, + source_client: SourceClnt, + target_client: TargetClnt, transaction_params: TransactionParams>, ) -> Self { ParachainsTarget { source_client, target_client, transaction_params } } /// Returns reference to the underlying RPC client. - pub fn target_client(&self) -> &Client { + pub fn target_client(&self) -> &TargetClnt { &self.target_client } } -impl Clone for ParachainsTarget

{ +impl< + P: SubstrateParachainsPipeline, + SourceClnt: Client, + TargetClnt: Clone, + > Clone for ParachainsTarget +{ fn clone(&self) -> Self { ParachainsTarget { source_client: self.source_client.clone(), @@ -77,7 +88,12 @@ impl Clone for ParachainsTarget

{ } #[async_trait] -impl RelayClient for ParachainsTarget

{ +impl< + P: SubstrateParachainsPipeline, + SourceClnt: Client, + TargetClnt: Client, + > RelayClient for ParachainsTarget +{ type Error = SubstrateError; async fn reconnect(&mut self) -> Result<(), SubstrateError> { @@ -88,14 +104,17 @@ impl RelayClient for ParachainsTarget

{ } #[async_trait] -impl

TargetClient> for ParachainsTarget

+impl TargetClient> + for ParachainsTarget where P: SubstrateParachainsPipeline, + SourceClnt: Client, + TargetClnt: Client, AccountIdOf: From< as Pair>::Public>, P::SourceParachain: ChainBase, P::SourceRelayChain: ChainBase, { - type TransactionTracker = TransactionTracker>; + type TransactionTracker = TransactionTracker; async fn best_block(&self) -> Result, Self::Error> { let best_header = self.target_client.best_header().await?; @@ -109,10 +128,10 @@ where at_block: &HeaderIdOf, ) -> Result, Self::Error> { self.target_client - .typed_state_call::<_, Option>>( + .state_call::<_, Option>>( + at_block.hash(), P::SourceRelayChain::BEST_FINALIZED_HEADER_ID_METHOD.into(), (), - Some(at_block.1), ) .await? .map(Ok) @@ -124,7 +143,11 @@ where ) -> Result>, Self::Error> { Ok(self .target_client - .typed_state_call(P::SourceRelayChain::FREE_HEADERS_INTERVAL_METHOD.into(), (), None) + .state_call( + self.target_client.best_header().await?.hash(), + P::SourceRelayChain::FREE_HEADERS_INTERVAL_METHOD.into(), + (), + ) .await .unwrap_or_else(|e| { log::info!( @@ -151,7 +174,7 @@ where &P::SourceParachain::PARACHAIN_ID.into(), ); let storage_value: Option = - self.target_client.storage_value(storage_key, Some(at_block.hash())).await?; + self.target_client.storage_value(at_block.hash(), storage_key).await?; let para_info = match storage_value { Some(para_info) => para_info, None => return Ok(None), @@ -172,7 +195,7 @@ where ¶_info.best_head_hash.head_hash, ); let storage_value: Option = - self.target_client.storage_value(storage_key, Some(at_block.hash())).await?; + self.target_client.storage_value(at_block.hash(), storage_key).await?; let para_head_number = match storage_value { Some(para_head_data) => para_head_data.decode_parachain_head_data::()?.number, diff --git a/bridges/relays/messages/Cargo.toml b/bridges/relays/messages/Cargo.toml index 570e11c0da6feeaa7bbbbd76a845df51444a10cb..96e441fc6730e808065c86d83020ea36e29a2c1b 100644 --- a/bridges/relays/messages/Cargo.toml +++ b/bridges/relays/messages/Cargo.toml @@ -11,19 +11,19 @@ publish = false workspace = true [dependencies] -async-std = { version = "1.9.0", features = ["attributes"] } -async-trait = "0.1.79" -env_logger = "0.11" -futures = "0.3.30" -hex = "0.4" +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 } -num-traits = "0.2" -parking_lot = "0.12.1" +num-traits = { workspace = true, default-features = true } +parking_lot = { workspace = true, default-features = true } # Bridge Dependencies -bp-messages = { path = "../../primitives/messages" } -finality-relay = { path = "../finality" } -relay-utils = { path = "../utils" } +bp-messages = { workspace = true, default-features = true } +finality-relay = { workspace = true } +relay-utils = { workspace = true } -sp-arithmetic = { path = "../../../substrate/primitives/arithmetic" } +sp-arithmetic = { workspace = true, default-features = true } diff --git a/bridges/relays/parachains/Cargo.toml b/bridges/relays/parachains/Cargo.toml index 8d38e4e6bd07c2420adcf233729c1bac9bb77c37..ed03bdbb0f65e6f5e3b15c63f6ccd680c89e6626 100644 --- a/bridges/relays/parachains/Cargo.toml +++ b/bridges/relays/parachains/Cargo.toml @@ -11,18 +11,18 @@ publish = false workspace = true [dependencies] -async-std = "1.9.0" -async-trait = "0.1.79" -futures = "0.3.30" +async-std = { workspace = true } +async-trait = { workspace = true } +futures = { workspace = true } log = { workspace = true } -relay-utils = { path = "../utils" } +relay-utils = { workspace = true } # Bridge dependencies -bp-polkadot-core = { path = "../../primitives/polkadot-core" } -relay-substrate-client = { path = "../client-substrate" } +bp-polkadot-core = { workspace = true, default-features = true } +relay-substrate-client = { workspace = true } [dev-dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12" } -relay-substrate-client = { path = "../client-substrate", features = ["test-helpers"] } -sp-core = { path = "../../../substrate/primitives/core" } +codec = { workspace = true, default-features = true } +relay-substrate-client = { features = ["test-helpers"], workspace = true } +sp-core = { workspace = true, default-features = true } diff --git a/bridges/relays/utils/Cargo.toml b/bridges/relays/utils/Cargo.toml index 4765730a0b4f9906fd163600a7937f8d6aad661f..93e42763967b90c32409dcacbac22486a09a9892 100644 --- a/bridges/relays/utils/Cargo.toml +++ b/bridges/relays/utils/Cargo.toml @@ -11,29 +11,29 @@ publish = false workspace = true [dependencies] -ansi_term = "0.12" -anyhow = "1.0" -async-std = "1.9.0" -async-trait = "0.1.79" -backoff = "0.4" -isahc = "1.2" -env_logger = "0.11.3" -futures = "0.3.30" -jsonpath_lib = "0.3" +ansi_term = { workspace = true } +anyhow = { workspace = true } +async-std = { workspace = true } +async-trait = { workspace = true } +backoff = { workspace = true } +isahc = { workspace = true } +env_logger = { workspace = true } +futures = { workspace = true } +jsonpath_lib = { workspace = true } log = { workspace = true } -num-traits = "0.2" -parking_lot = "0.12.1" +num-traits = { workspace = true, default-features = true } +parking_lot = { workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } -sysinfo = "0.30" -time = { version = "0.3", features = ["formatting", "local-offset", "std"] } -tokio = { version = "1.37", features = ["rt"] } +sysinfo = { workspace = true } +time = { features = ["formatting", "local-offset", "std"], workspace = true } +tokio = { features = ["rt"], workspace = true, default-features = true } thiserror = { workspace = true } # Bridge dependencies -bp-runtime = { path = "../../primitives/runtime" } +bp-runtime = { workspace = true, default-features = true } # Substrate dependencies -sp-runtime = { path = "../../../substrate/primitives/runtime" } -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../../substrate/utils/prometheus" } +sp-runtime = { workspace = true, default-features = true } +prometheus-endpoint = { workspace = true, default-features = true } diff --git a/bridges/snowbridge/pallets/ethereum-client/Cargo.toml b/bridges/snowbridge/pallets/ethereum-client/Cargo.toml index cab2b06b0931e6d28df83434b3319c8384bd3679..666ac3fbc8a2ab32b485c088c37b536e751cdd46 100644 --- a/bridges/snowbridge/pallets/ethereum-client/Cargo.toml +++ b/bridges/snowbridge/pallets/ethereum-client/Cargo.toml @@ -17,34 +17,34 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] serde = { optional = true, workspace = true, default-features = true } serde_json = { optional = true, workspace = true, default-features = true } -codec = { version = "3.6.12", package = "parity-scale-codec", default-features = false, features = ["derive"] } -scale-info = { version = "2.9.0", default-features = false, features = ["derive"] } -hex-literal = { version = "0.4.1", optional = true } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } +hex-literal = { optional = true, workspace = true, default-features = true } log = { workspace = true } -frame-benchmarking = { path = "../../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-support = { path = "../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../substrate/frame/system", default-features = false } -sp-core = { path = "../../../../substrate/primitives/core", default-features = false } -sp-std = { path = "../../../../substrate/primitives/std", default-features = false } -sp-runtime = { path = "../../../../substrate/primitives/runtime", default-features = false } -sp-io = { path = "../../../../substrate/primitives/io", default-features = false, optional = true } +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 } +sp-io = { optional = true, workspace = true } -snowbridge-core = { path = "../../primitives/core", default-features = false } -snowbridge-ethereum = { path = "../../primitives/ethereum", default-features = false } -snowbridge-pallet-ethereum-client-fixtures = { path = "fixtures", default-features = false, optional = true } -snowbridge-beacon-primitives = { path = "../../primitives/beacon", default-features = false } -static_assertions = { version = "1.1.0", default-features = false } -pallet-timestamp = { path = "../../../../substrate/frame/timestamp", default-features = false, optional = true } +snowbridge-core = { workspace = true } +snowbridge-ethereum = { workspace = true } +snowbridge-pallet-ethereum-client-fixtures = { optional = true, workspace = true } +snowbridge-beacon-primitives = { workspace = true } +static_assertions = { workspace = true } +pallet-timestamp = { optional = true, workspace = true } [dev-dependencies] -rand = "0.8.5" -sp-keyring = { path = "../../../../substrate/primitives/keyring" } +rand = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } -hex-literal = "0.4.1" -pallet-timestamp = { path = "../../../../substrate/frame/timestamp" } -snowbridge-pallet-ethereum-client-fixtures = { path = "fixtures" } -sp-io = { path = "../../../../substrate/primitives/io" } +hex-literal = { workspace = true, default-features = true } +pallet-timestamp = { workspace = true, default-features = true } +snowbridge-pallet-ethereum-client-fixtures = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } serde = { workspace = true, default-features = true } [features] diff --git a/bridges/snowbridge/pallets/ethereum-client/fixtures/Cargo.toml b/bridges/snowbridge/pallets/ethereum-client/fixtures/Cargo.toml index 858e2513a961288dd24c47e7d57ada1506b212d2..bd4176875733f64f61026e165a2a03b221193bad 100644 --- a/bridges/snowbridge/pallets/ethereum-client/fixtures/Cargo.toml +++ b/bridges/snowbridge/pallets/ethereum-client/fixtures/Cargo.toml @@ -15,11 +15,11 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -hex-literal = { version = "0.4.1" } -sp-core = { path = "../../../../../substrate/primitives/core", default-features = false } -sp-std = { path = "../../../../../substrate/primitives/std", default-features = false } -snowbridge-core = { path = "../../../primitives/core", default-features = false } -snowbridge-beacon-primitives = { path = "../../../primitives/beacon", default-features = false } +hex-literal = { workspace = true, default-features = true } +sp-core = { workspace = true } +sp-std = { workspace = true } +snowbridge-core = { workspace = true } +snowbridge-beacon-primitives = { workspace = true } [features] default = ["std"] diff --git a/bridges/snowbridge/pallets/inbound-queue/Cargo.toml b/bridges/snowbridge/pallets/inbound-queue/Cargo.toml index d63398770f207051ebb5adb72f4f574c767e8770..1b08bb39b4346a76e58c0a695b4c71126bd40510 100644 --- a/bridges/snowbridge/pallets/inbound-queue/Cargo.toml +++ b/bridges/snowbridge/pallets/inbound-queue/Cargo.toml @@ -16,35 +16,35 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] serde = { optional = true, workspace = true, default-features = true } -codec = { version = "3.6.12", package = "parity-scale-codec", default-features = false, features = ["derive"] } -scale-info = { version = "2.9.0", default-features = false, features = ["derive"] } -hex-literal = { version = "0.4.1", optional = true } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } +hex-literal = { optional = true, workspace = true, default-features = true } log = { workspace = true } -alloy-primitives = { version = "0.4.2", default-features = false, features = ["rlp"] } -alloy-sol-types = { version = "0.4.2", default-features = false } +alloy-primitives = { features = ["rlp"], workspace = true } +alloy-sol-types = { workspace = true } -frame-benchmarking = { path = "../../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-support = { path = "../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../substrate/frame/system", default-features = false } -pallet-balances = { path = "../../../../substrate/frame/balances", default-features = false } -sp-core = { path = "../../../../substrate/primitives/core", default-features = false } -sp-std = { path = "../../../../substrate/primitives/std", default-features = false } -sp-io = { path = "../../../../substrate/primitives/io", default-features = false } -sp-runtime = { path = "../../../../substrate/primitives/runtime", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-balances = { workspace = true } +sp-core = { workspace = true } +sp-std = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } -xcm = { package = "staging-xcm", path = "../../../../polkadot/xcm", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../polkadot/xcm/xcm-executor", default-features = false } +xcm = { workspace = true } +xcm-executor = { workspace = true } -snowbridge-core = { path = "../../primitives/core", default-features = false } -snowbridge-router-primitives = { path = "../../primitives/router", default-features = false } -snowbridge-beacon-primitives = { path = "../../primitives/beacon", default-features = false } -snowbridge-pallet-inbound-queue-fixtures = { path = "fixtures", default-features = false, optional = true } +snowbridge-core = { workspace = true } +snowbridge-router-primitives = { workspace = true } +snowbridge-beacon-primitives = { workspace = true } +snowbridge-pallet-inbound-queue-fixtures = { optional = true, workspace = true } [dev-dependencies] -frame-benchmarking = { path = "../../../../substrate/frame/benchmarking" } -sp-keyring = { path = "../../../../substrate/primitives/keyring" } -snowbridge-pallet-ethereum-client = { path = "../ethereum-client" } -hex-literal = { version = "0.4.1" } +frame-benchmarking = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +snowbridge-pallet-ethereum-client = { workspace = true, default-features = true } +hex-literal = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/bridges/snowbridge/pallets/inbound-queue/fixtures/Cargo.toml b/bridges/snowbridge/pallets/inbound-queue/fixtures/Cargo.toml index e84246fb5a551b2512c4e00cb4ca00171e8c3f75..b66b57c3620ad5488d58b90a8f337ecd88f07e5d 100644 --- a/bridges/snowbridge/pallets/inbound-queue/fixtures/Cargo.toml +++ b/bridges/snowbridge/pallets/inbound-queue/fixtures/Cargo.toml @@ -15,11 +15,11 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -hex-literal = { version = "0.4.1" } -sp-core = { path = "../../../../../substrate/primitives/core", default-features = false } -sp-std = { path = "../../../../../substrate/primitives/std", default-features = false } -snowbridge-core = { path = "../../../primitives/core", default-features = false } -snowbridge-beacon-primitives = { path = "../../../primitives/beacon", default-features = false } +hex-literal = { workspace = true, default-features = true } +sp-core = { workspace = true } +sp-std = { workspace = true } +snowbridge-core = { workspace = true } +snowbridge-beacon-primitives = { workspace = true } [features] default = ["std"] diff --git a/bridges/snowbridge/pallets/inbound-queue/src/mock.rs b/bridges/snowbridge/pallets/inbound-queue/src/mock.rs index a842f9aa60cb9ae500c9e8a0079006da7c1bf5d0..a031676c6076ad417a9d0fd1f060e9387bb99eea 100644 --- a/bridges/snowbridge/pallets/inbound-queue/src/mock.rs +++ b/bridges/snowbridge/pallets/inbound-queue/src/mock.rs @@ -53,20 +53,11 @@ parameter_types! { pub const ExistentialDeposit: u128 = 1; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } parameter_types! { diff --git a/bridges/snowbridge/pallets/outbound-queue/Cargo.toml b/bridges/snowbridge/pallets/outbound-queue/Cargo.toml index 15c6c3a5b32b0fc2bd1a95fd842bab78f07a697a..78546e258daa30e966ddef1ed48c35cebcc17d65 100644 --- a/bridges/snowbridge/pallets/outbound-queue/Cargo.toml +++ b/bridges/snowbridge/pallets/outbound-queue/Cargo.toml @@ -16,27 +16,27 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] serde = { features = ["alloc", "derive"], workspace = true } -codec = { version = "3.6.12", package = "parity-scale-codec", default-features = false, features = ["derive"] } -scale-info = { version = "2.9.0", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } -frame-benchmarking = { path = "../../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-support = { path = "../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../substrate/frame/system", default-features = false } -sp-core = { path = "../../../../substrate/primitives/core", default-features = false } -sp-std = { path = "../../../../substrate/primitives/std", default-features = false } -sp-runtime = { path = "../../../../substrate/primitives/runtime", default-features = false } -sp-io = { path = "../../../../substrate/primitives/io", default-features = false } -sp-arithmetic = { path = "../../../../substrate/primitives/arithmetic", default-features = false } +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 } +sp-io = { workspace = true } +sp-arithmetic = { workspace = true } -bridge-hub-common = { path = "../../../../cumulus/parachains/runtimes/bridge-hubs/common", default-features = false } +bridge-hub-common = { workspace = true } -snowbridge-core = { path = "../../primitives/core", default-features = false, features = ["serde"] } -snowbridge-outbound-queue-merkle-tree = { path = "merkle-tree", default-features = false } -ethabi = { package = "ethabi-decode", version = "1.0.0", default-features = false } +snowbridge-core = { features = ["serde"], workspace = true } +snowbridge-outbound-queue-merkle-tree = { workspace = true } +ethabi = { workspace = true } [dev-dependencies] -pallet-message-queue = { path = "../../../../substrate/frame/message-queue", default-features = false } -sp-keyring = { path = "../../../../substrate/primitives/keyring" } +pallet-message-queue = { workspace = true } +sp-keyring = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/bridges/snowbridge/pallets/outbound-queue/merkle-tree/Cargo.toml b/bridges/snowbridge/pallets/outbound-queue/merkle-tree/Cargo.toml index 1b1a9905928f8b5ea8eaccc15d18813f87406494..00cc700fbe832cea4e77ddabe3a148c42bd30bef 100644 --- a/bridges/snowbridge/pallets/outbound-queue/merkle-tree/Cargo.toml +++ b/bridges/snowbridge/pallets/outbound-queue/merkle-tree/Cargo.toml @@ -15,18 +15,18 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { version = "3.6.12", package = "parity-scale-codec", default-features = false, features = ["derive"] } -scale-info = { version = "2.7.0", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } -sp-core = { path = "../../../../../substrate/primitives/core", default-features = false } -sp-runtime = { path = "../../../../../substrate/primitives/runtime", default-features = false } +sp-core = { workspace = true } +sp-runtime = { workspace = true } [dev-dependencies] -hex-literal = { version = "0.4.1" } -env_logger = "0.11" -hex = "0.4" -array-bytes = "6.2.2" -sp-crypto-hashing = { path = "../../../../../substrate/primitives/crypto/hashing" } +hex-literal = { workspace = true, default-features = true } +env_logger = { workspace = true } +hex = { workspace = true, default-features = true } +array-bytes = { workspace = true, default-features = true } +sp-crypto-hashing = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/bridges/snowbridge/pallets/outbound-queue/runtime-api/Cargo.toml b/bridges/snowbridge/pallets/outbound-queue/runtime-api/Cargo.toml index b8d704f1cb92d570ea8e8b06cd00410bea7746bb..d35bdde5a81e7a80a228efff19c3c1de0eceefef 100644 --- a/bridges/snowbridge/pallets/outbound-queue/runtime-api/Cargo.toml +++ b/bridges/snowbridge/pallets/outbound-queue/runtime-api/Cargo.toml @@ -15,12 +15,12 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { version = "3.6.12", package = "parity-scale-codec", features = ["derive"], default-features = false } -sp-std = { path = "../../../../../substrate/primitives/std", default-features = false } -sp-api = { path = "../../../../../substrate/primitives/api", default-features = false } -frame-support = { path = "../../../../../substrate/frame/support", default-features = false } -snowbridge-outbound-queue-merkle-tree = { path = "../merkle-tree", default-features = false } -snowbridge-core = { path = "../../../primitives/core", default-features = false } +codec = { features = ["derive"], workspace = true } +sp-std = { workspace = true } +sp-api = { workspace = true } +frame-support = { workspace = true } +snowbridge-outbound-queue-merkle-tree = { workspace = true } +snowbridge-core = { workspace = true } [features] default = ["std"] diff --git a/bridges/snowbridge/pallets/system/Cargo.toml b/bridges/snowbridge/pallets/system/Cargo.toml index 5bbbb1d9310da4c3617ec4b03ea63620c30feb20..f1e749afb9977c440ba7bbfa55c8a8acbc8c0cda 100644 --- a/bridges/snowbridge/pallets/system/Cargo.toml +++ b/bridges/snowbridge/pallets/system/Cargo.toml @@ -15,33 +15,33 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", -] } -scale-info = { version = "2.9.0", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-support = { path = "../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../substrate/frame/system", default-features = false } +], workspace = true } +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } log = { workspace = true } -sp-core = { path = "../../../../substrate/primitives/core", default-features = false } -sp-std = { path = "../../../../substrate/primitives/std", default-features = false } -sp-io = { path = "../../../../substrate/primitives/io", default-features = false } -sp-runtime = { path = "../../../../substrate/primitives/runtime", default-features = false } +sp-core = { workspace = true } +sp-std = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } -xcm = { package = "staging-xcm", path = "../../../../polkadot/xcm", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../polkadot/xcm/xcm-executor", default-features = false } +xcm = { workspace = true } +xcm-executor = { workspace = true } -snowbridge-core = { path = "../../primitives/core", default-features = false } +snowbridge-core = { workspace = true } [dev-dependencies] -hex = "0.4.1" -hex-literal = { version = "0.4.1" } -pallet-balances = { path = "../../../../substrate/frame/balances" } -sp-keyring = { path = "../../../../substrate/primitives/keyring" } -polkadot-primitives = { path = "../../../../polkadot/primitives" } -pallet-message-queue = { path = "../../../../substrate/frame/message-queue" } -snowbridge-pallet-outbound-queue = { path = "../outbound-queue" } +hex = { workspace = true, default-features = true } +hex-literal = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +pallet-message-queue = { workspace = true, default-features = true } +snowbridge-pallet-outbound-queue = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/bridges/snowbridge/pallets/system/runtime-api/Cargo.toml b/bridges/snowbridge/pallets/system/runtime-api/Cargo.toml index 42df5edfb7b2d4e5abaf0e30850ecbd3ebd04b98..7c524dd2edadb6132be50616f7e6855ad463c8b4 100644 --- a/bridges/snowbridge/pallets/system/runtime-api/Cargo.toml +++ b/bridges/snowbridge/pallets/system/runtime-api/Cargo.toml @@ -15,13 +15,13 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", -] } -sp-std = { path = "../../../../../substrate/primitives/std", default-features = false } -sp-api = { path = "../../../../../substrate/primitives/api", default-features = false } -xcm = { package = "staging-xcm", path = "../../../../../polkadot/xcm", default-features = false } -snowbridge-core = { path = "../../../primitives/core", default-features = false } +], workspace = true } +sp-std = { workspace = true } +sp-api = { workspace = true } +xcm = { workspace = true } +snowbridge-core = { workspace = true } [features] default = ["std"] diff --git a/bridges/snowbridge/pallets/system/src/mock.rs b/bridges/snowbridge/pallets/system/src/mock.rs index d7fc4152b371025687d2a36cbd49e628c88205fc..98bd3da9ab27c974a1a85abbb208064e41f89991 100644 --- a/bridges/snowbridge/pallets/system/src/mock.rs +++ b/bridges/snowbridge/pallets/system/src/mock.rs @@ -112,20 +112,11 @@ impl frame_system::Config for Test { type Block = Block; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); type ExistentialDeposit = ConstU128<1>; type AccountStore = System; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } impl pallet_xcm_origin::Config for Test { diff --git a/bridges/snowbridge/primitives/beacon/Cargo.toml b/bridges/snowbridge/primitives/beacon/Cargo.toml index 18123910c35b2e198ec03ca1aa01aef1ea0d96ca..9ced99fbf3fdddd8f64877606f957da14c70f608 100644 --- a/bridges/snowbridge/primitives/beacon/Cargo.toml +++ b/bridges/snowbridge/primitives/beacon/Cargo.toml @@ -13,26 +13,26 @@ workspace = true [dependencies] serde = { optional = true, features = ["derive"], workspace = true, default-features = true } -hex = { version = "0.4", default-features = false } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -scale-info = { version = "2.9.0", default-features = false, features = ["derive"] } -rlp = { version = "0.5", default-features = false } +hex = { workspace = true } +codec = { workspace = true } +scale-info = { features = ["derive"], workspace = true } +rlp = { workspace = true } -frame-support = { path = "../../../../substrate/frame/support", default-features = false } -sp-runtime = { path = "../../../../substrate/primitives/runtime", default-features = false } -sp-core = { path = "../../../../substrate/primitives/core", default-features = false } -sp-std = { path = "../../../../substrate/primitives/std", default-features = false } -sp-io = { path = "../../../../substrate/primitives/io", default-features = false } +frame-support = { workspace = true } +sp-runtime = { workspace = true } +sp-core = { workspace = true } +sp-std = { workspace = true } +sp-io = { workspace = true } -ssz_rs = { version = "0.9.0", default-features = false } -ssz_rs_derive = { version = "0.9.0", default-features = false } -byte-slice-cast = { version = "1.2.1", default-features = false } +ssz_rs = { workspace = true } +ssz_rs_derive = { workspace = true } +byte-slice-cast = { workspace = true } -snowbridge-ethereum = { path = "../ethereum", default-features = false } -milagro-bls = { package = "snowbridge-milagro-bls", version = "1.5.4", default-features = false } +snowbridge-ethereum = { workspace = true } +milagro-bls = { workspace = true } [dev-dependencies] -hex-literal = { version = "0.4.1" } +hex-literal = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/bridges/snowbridge/primitives/core/Cargo.toml b/bridges/snowbridge/primitives/core/Cargo.toml index 573ab6608e5f91c0333f5ee7288cb679d6c38fb6..f9bee1ff4959ae56f73b50d4c91c2ea2e63bb0a6 100644 --- a/bridges/snowbridge/primitives/core/Cargo.toml +++ b/bridges/snowbridge/primitives/core/Cargo.toml @@ -13,28 +13,28 @@ workspace = true [dependencies] serde = { optional = true, features = ["alloc", "derive"], workspace = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -scale-info = { version = "2.9.0", default-features = false, features = ["derive"] } -hex-literal = { version = "0.4.1" } +codec = { workspace = true } +scale-info = { features = ["derive"], workspace = true } +hex-literal = { workspace = true, default-features = true } -polkadot-parachain-primitives = { path = "../../../../polkadot/parachain", default-features = false } -xcm = { package = "staging-xcm", path = "../../../../polkadot/xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../../polkadot/xcm/xcm-builder", default-features = false } +polkadot-parachain-primitives = { workspace = true } +xcm = { workspace = true } +xcm-builder = { workspace = true } -frame-support = { path = "../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../substrate/frame/system", default-features = false } -sp-runtime = { path = "../../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../../substrate/primitives/std", default-features = false } -sp-io = { path = "../../../../substrate/primitives/io", default-features = false } -sp-core = { path = "../../../../substrate/primitives/core", default-features = false } -sp-arithmetic = { path = "../../../../substrate/primitives/arithmetic", default-features = false } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } +sp-io = { workspace = true } +sp-core = { workspace = true } +sp-arithmetic = { workspace = true } -snowbridge-beacon-primitives = { path = "../beacon", default-features = false } +snowbridge-beacon-primitives = { workspace = true } -ethabi = { package = "ethabi-decode", version = "1.0.0", default-features = false } +ethabi = { workspace = true } [dev-dependencies] -hex = { version = "0.4.3" } +hex = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/bridges/snowbridge/primitives/ethereum/Cargo.toml b/bridges/snowbridge/primitives/ethereum/Cargo.toml index fb0b6cbaf3c2fba82c709fbc84ca565c53e7505e..764ce90b8139d936d16e38a2f337c05004427675 100644 --- a/bridges/snowbridge/primitives/ethereum/Cargo.toml +++ b/bridges/snowbridge/primitives/ethereum/Cargo.toml @@ -14,23 +14,23 @@ workspace = true [dependencies] serde = { optional = true, features = ["derive"], workspace = true, default-features = true } serde-big-array = { optional = true, features = ["const-generics"], workspace = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.9.0", default-features = false, features = ["derive"] } -ethbloom = { version = "0.13.0", default-features = false } -ethereum-types = { version = "0.14.1", default-features = false, features = ["codec", "rlp", "serialize"] } -hex-literal = { version = "0.4.1", default-features = false } -parity-bytes = { version = "0.1.2", default-features = false } -rlp = { version = "0.5.2", default-features = false } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } +ethbloom = { workspace = true } +ethereum-types = { features = ["codec", "rlp", "serialize"], workspace = true } +hex-literal = { workspace = true } +parity-bytes = { workspace = true } +rlp = { workspace = true } -sp-io = { path = "../../../../substrate/primitives/io", default-features = false } -sp-std = { path = "../../../../substrate/primitives/std", default-features = false } -sp-runtime = { path = "../../../../substrate/primitives/runtime", default-features = false } +sp-io = { workspace = true } +sp-std = { workspace = true } +sp-runtime = { workspace = true } -ethabi = { package = "ethabi-decode", version = "1.0.0", default-features = false } +ethabi = { workspace = true } [dev-dependencies] -wasm-bindgen-test = "0.3.19" -rand = "0.8.5" +wasm-bindgen-test = { workspace = true } +rand = { workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } [features] diff --git a/bridges/snowbridge/primitives/router/Cargo.toml b/bridges/snowbridge/primitives/router/Cargo.toml index ec0888dd41b0cd197b49efda9f83e188916fb8fa..ee8d481cec12ae07d107c0463b778345fcfcecee 100644 --- a/bridges/snowbridge/primitives/router/Cargo.toml +++ b/bridges/snowbridge/primitives/router/Cargo.toml @@ -12,25 +12,24 @@ categories = ["cryptography::cryptocurrencies"] workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -scale-info = { version = "2.9.0", default-features = false, features = ["derive"] } +codec = { workspace = true } +scale-info = { features = ["derive"], workspace = true } log = { workspace = true } -frame-support = { path = "../../../../substrate/frame/support", default-features = false } -sp-core = { path = "../../../../substrate/primitives/core", default-features = false } -sp-io = { path = "../../../../substrate/primitives/io", default-features = false } -sp-runtime = { path = "../../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../../substrate/primitives/std", default-features = false } +frame-support = { workspace = true } +sp-core = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } -xcm = { package = "staging-xcm", path = "../../../../polkadot/xcm", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../polkadot/xcm/xcm-executor", default-features = false } +xcm = { workspace = true } +xcm-executor = { workspace = true } -snowbridge-core = { path = "../core", default-features = false } +snowbridge-core = { workspace = true } -hex-literal = { version = "0.4.1" } +hex-literal = { workspace = true, default-features = true } [dev-dependencies] -rustc-hex = { version = "2.1.0" } [features] default = ["std"] diff --git a/bridges/snowbridge/runtime/runtime-common/Cargo.toml b/bridges/snowbridge/runtime/runtime-common/Cargo.toml index 2372908b86ab5134f4ea0f8373ffe00cbcc2bd32..d47cb3cb7101fb54d7bdde854ff73e628555e86b 100644 --- a/bridges/snowbridge/runtime/runtime-common/Cargo.toml +++ b/bridges/snowbridge/runtime/runtime-common/Cargo.toml @@ -13,15 +13,15 @@ workspace = true [dependencies] log = { workspace = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -frame-support = { path = "../../../../substrate/frame/support", default-features = false } -sp-std = { path = "../../../../substrate/primitives/std", default-features = false } -sp-arithmetic = { path = "../../../../substrate/primitives/arithmetic", default-features = false } -xcm = { package = "staging-xcm", path = "../../../../polkadot/xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../../polkadot/xcm/xcm-builder", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../polkadot/xcm/xcm-executor", default-features = false } +codec = { workspace = true } +frame-support = { workspace = true } +sp-std = { workspace = true } +sp-arithmetic = { workspace = true } +xcm = { workspace = true } +xcm-builder = { workspace = true } +xcm-executor = { workspace = true } -snowbridge-core = { path = "../../primitives/core", default-features = false } +snowbridge-core = { workspace = true } [dev-dependencies] diff --git a/bridges/snowbridge/runtime/test-common/Cargo.toml b/bridges/snowbridge/runtime/test-common/Cargo.toml index e19c682de4542994e19e20d0c194598fc8009db5..6f8e586bf5ff12e7d870df95ffc6a0f02461357b 100644 --- a/bridges/snowbridge/runtime/test-common/Cargo.toml +++ b/bridges/snowbridge/runtime/test-common/Cargo.toml @@ -11,38 +11,38 @@ categories = ["cryptography::cryptocurrencies"] workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } # Substrate -frame-support = { path = "../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../substrate/frame/system", default-features = false } -pallet-balances = { path = "../../../../substrate/frame/balances", default-features = false } -pallet-session = { path = "../../../../substrate/frame/session", default-features = false } -pallet-message-queue = { path = "../../../../substrate/frame/message-queue", default-features = false } -pallet-timestamp = { path = "../../../../substrate/frame/timestamp", default-features = false } -pallet-utility = { path = "../../../../substrate/frame/utility", default-features = false } -sp-core = { path = "../../../../substrate/primitives/core", default-features = false } -sp-io = { path = "../../../../substrate/primitives/io", default-features = false } -sp-keyring = { path = "../../../../substrate/primitives/keyring" } -sp-runtime = { path = "../../../../substrate/primitives/runtime", default-features = false } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-balances = { workspace = true } +pallet-session = { workspace = true } +pallet-message-queue = { workspace = true } +pallet-timestamp = { workspace = true } +pallet-utility = { workspace = true } +sp-core = { workspace = true } +sp-io = { workspace = true } +sp-keyring = { workspace = true, default-features = true } +sp-runtime = { workspace = true } # Polkadot -pallet-xcm = { path = "../../../../polkadot/xcm/pallet-xcm", default-features = false } -xcm = { package = "staging-xcm", path = "../../../../polkadot/xcm", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../polkadot/xcm/xcm-executor", default-features = false } +pallet-xcm = { workspace = true } +xcm = { workspace = true } +xcm-executor = { workspace = true } # Cumulus -cumulus-pallet-parachain-system = { path = "../../../../cumulus/pallets/parachain-system", default-features = false } -pallet-collator-selection = { path = "../../../../cumulus/pallets/collator-selection", default-features = false } -parachain-info = { package = "staging-parachain-info", path = "../../../../cumulus/parachains/pallets/parachain-info", default-features = false } -parachains-runtimes-test-utils = { path = "../../../../cumulus/parachains/runtimes/test-utils", default-features = false } +cumulus-pallet-parachain-system = { workspace = true } +pallet-collator-selection = { workspace = true } +parachain-info = { workspace = true } +parachains-runtimes-test-utils = { workspace = true } # Ethereum Bridge (Snowbridge) -snowbridge-core = { path = "../../primitives/core", default-features = false } -snowbridge-pallet-ethereum-client = { path = "../../pallets/ethereum-client", default-features = false } -snowbridge-pallet-ethereum-client-fixtures = { path = "../../pallets/ethereum-client/fixtures", default-features = false } -snowbridge-pallet-outbound-queue = { path = "../../pallets/outbound-queue", default-features = false } -snowbridge-pallet-system = { path = "../../pallets/system", default-features = false } +snowbridge-core = { workspace = true } +snowbridge-pallet-ethereum-client = { workspace = true } +snowbridge-pallet-ethereum-client-fixtures = { workspace = true } +snowbridge-pallet-outbound-queue = { workspace = true } +snowbridge-pallet-system = { workspace = true } [features] default = ["std"] diff --git a/bridges/testing/framework/utils/generate_hex_encoded_call/package-lock.json b/bridges/testing/framework/utils/generate_hex_encoded_call/package-lock.json index b2dddaa19ed1561b98422b3a28f6777308b3ba47..ca3abcc528cfaabc19cebf47426ef62f4ea5a8a6 100644 --- a/bridges/testing/framework/utils/generate_hex_encoded_call/package-lock.json +++ b/bridges/testing/framework/utils/generate_hex_encoded_call/package-lock.json @@ -736,9 +736,9 @@ } }, "node_modules/ws": { - "version": "8.16.0", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.16.0.tgz", - "integrity": "sha512-HS0c//TP7Ina87TfiPUz1rQzMhHrl/SG2guqRcTOIUYD2q8uhUdNHZYJUaQ8aTGPzCh+c6oawMKW35nFl1dxyQ==", + "version": "8.17.1", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.17.1.tgz", + "integrity": "sha512-6XQFvXTkbfUOZOKKILFG1PDK2NDQs4azKQl26T0YS5CxqWLgXajbPZ+h4gZekJyRqFU8pvnbAbbs/3TgRPy+GQ==", "engines": { "node": ">=10.0.0" }, diff --git a/cumulus/client/cli/Cargo.toml b/cumulus/client/cli/Cargo.toml index 410ac8b983d96f0a38633ac0199208a4e249e49b..9b6f6b73960b416c481b43f053477c70e55b8495 100644 --- a/cumulus/client/cli/Cargo.toml +++ b/cumulus/client/cli/Cargo.toml @@ -10,15 +10,15 @@ license = "GPL-3.0-or-later WITH Classpath-exception-2.0" workspace = true [dependencies] -clap = { version = "4.5.3", features = ["derive"] } -codec = { package = "parity-scale-codec", version = "3.6.12" } -url = "2.4.0" +clap = { features = ["derive"], workspace = true } +codec = { workspace = true, default-features = true } +url = { workspace = true } # Substrate -sc-cli = { path = "../../../substrate/client/cli" } -sc-client-api = { path = "../../../substrate/client/api" } -sc-chain-spec = { path = "../../../substrate/client/chain-spec" } -sc-service = { path = "../../../substrate/client/service" } -sp-core = { path = "../../../substrate/primitives/core" } -sp-runtime = { path = "../../../substrate/primitives/runtime" } -sp-blockchain = { path = "../../../substrate/primitives/blockchain" } +sc-cli = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-chain-spec = { workspace = true, default-features = true } +sc-service = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } diff --git a/cumulus/client/collator/Cargo.toml b/cumulus/client/collator/Cargo.toml index 39cedf87a0cb1b6fb8296c1a3bdec1483170af38..6ebde0c2c653b8279ead203bdabeafd3ab8292e1 100644 --- a/cumulus/client/collator/Cargo.toml +++ b/cumulus/client/collator/Cargo.toml @@ -10,41 +10,41 @@ license = "GPL-3.0-or-later WITH Classpath-exception-2.0" workspace = true [dependencies] -parking_lot = "0.12.1" -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } -futures = "0.3.30" -tracing = "0.1.25" +parking_lot = { workspace = true, default-features = true } +codec = { features = ["derive"], workspace = true, default-features = true } +futures = { workspace = true } +tracing = { workspace = true, default-features = true } # Substrate -sc-client-api = { path = "../../../substrate/client/api" } -sp-consensus = { path = "../../../substrate/primitives/consensus/common" } -sp-api = { path = "../../../substrate/primitives/api" } -sp-core = { path = "../../../substrate/primitives/core" } -sp-runtime = { path = "../../../substrate/primitives/runtime" } +sc-client-api = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } # Polkadot -polkadot-node-primitives = { path = "../../../polkadot/node/primitives" } -polkadot-node-subsystem = { path = "../../../polkadot/node/subsystem" } -polkadot-overseer = { path = "../../../polkadot/node/overseer" } -polkadot-primitives = { path = "../../../polkadot/primitives" } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-overseer = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } # Cumulus -cumulus-client-consensus-common = { path = "../consensus/common" } -cumulus-client-network = { path = "../network" } -cumulus-primitives-core = { path = "../../primitives/core" } +cumulus-client-consensus-common = { workspace = true, default-features = true } +cumulus-client-network = { workspace = true, default-features = true } +cumulus-primitives-core = { workspace = true, default-features = true } [dev-dependencies] -async-trait = "0.1.79" +async-trait = { workspace = true } # Substrate -sp-maybe-compressed-blob = { path = "../../../substrate/primitives/maybe-compressed-blob" } -sp-state-machine = { path = "../../../substrate/primitives/state-machine" } -sp-tracing = { path = "../../../substrate/primitives/tracing" } +sp-maybe-compressed-blob = { workspace = true, default-features = true } +sp-state-machine = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } # Polkadot -polkadot-node-subsystem-test-helpers = { path = "../../../polkadot/node/subsystem-test-helpers" } +polkadot-node-subsystem-test-helpers = { workspace = true } # Cumulus -cumulus-test-client = { path = "../../test/client" } -cumulus-test-runtime = { path = "../../test/runtime" } -cumulus-test-relay-sproof-builder = { path = "../../test/relay-sproof-builder" } +cumulus-test-client = { workspace = true } +cumulus-test-runtime = { workspace = true } +cumulus-test-relay-sproof-builder = { workspace = true, default-features = true } diff --git a/cumulus/client/consensus/aura/Cargo.toml b/cumulus/client/consensus/aura/Cargo.toml index fad30e59e869d3a4144b33cdd34c6b73990d7e9f..5ab3e6f2512974db1dc00234ff47faeed6737b70 100644 --- a/cumulus/client/consensus/aura/Cargo.toml +++ b/cumulus/client/consensus/aura/Cargo.toml @@ -10,44 +10,45 @@ license = "GPL-3.0-or-later WITH Classpath-exception-2.0" workspace = true [dependencies] -async-trait = "0.1.79" -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } -futures = "0.3.28" -tracing = "0.1.37" -schnellru = "0.2.1" +async-trait = { workspace = true } +codec = { features = ["derive"], workspace = true, default-features = true } +futures = { workspace = true } +parking_lot = { workspace = true } +tracing = { workspace = true, default-features = true } +schnellru = { workspace = true } # Substrate -sc-client-api = { path = "../../../../substrate/client/api" } -sc-consensus = { path = "../../../../substrate/client/consensus/common" } -sc-consensus-aura = { path = "../../../../substrate/client/consensus/aura" } -sc-consensus-babe = { path = "../../../../substrate/client/consensus/babe" } -sc-consensus-slots = { path = "../../../../substrate/client/consensus/slots" } -sc-telemetry = { path = "../../../../substrate/client/telemetry" } -sp-api = { path = "../../../../substrate/primitives/api" } -sp-application-crypto = { path = "../../../../substrate/primitives/application-crypto" } -sp-block-builder = { path = "../../../../substrate/primitives/block-builder" } -sp-blockchain = { path = "../../../../substrate/primitives/blockchain" } -sp-consensus = { path = "../../../../substrate/primitives/consensus/common" } -sp-consensus-aura = { path = "../../../../substrate/primitives/consensus/aura" } -sp-core = { path = "../../../../substrate/primitives/core" } -sp-inherents = { path = "../../../../substrate/primitives/inherents" } -sp-keystore = { path = "../../../../substrate/primitives/keystore" } -sp-runtime = { path = "../../../../substrate/primitives/runtime" } -sp-timestamp = { path = "../../../../substrate/primitives/timestamp" } -sp-state-machine = { path = "../../../../substrate/primitives/state-machine" } -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../../../substrate/utils/prometheus" } +sc-client-api = { workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } +sc-consensus-aura = { workspace = true, default-features = true } +sc-consensus-babe = { workspace = true, default-features = true } +sc-consensus-slots = { workspace = true, default-features = true } +sc-telemetry = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-application-crypto = { workspace = true, default-features = true } +sp-block-builder = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-consensus-aura = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-inherents = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-timestamp = { workspace = true, default-features = true } +sp-state-machine = { workspace = true, default-features = true } +prometheus-endpoint = { workspace = true, default-features = true } # Cumulus -cumulus-client-consensus-common = { path = "../common" } -cumulus-relay-chain-interface = { path = "../../relay-chain-interface" } -cumulus-client-consensus-proposer = { path = "../proposer" } -cumulus-client-parachain-inherent = { path = "../../parachain-inherent" } -cumulus-primitives-aura = { path = "../../../primitives/aura" } -cumulus-primitives-core = { path = "../../../primitives/core" } -cumulus-client-collator = { path = "../../collator" } +cumulus-client-consensus-common = { workspace = true, default-features = true } +cumulus-relay-chain-interface = { workspace = true, default-features = true } +cumulus-client-consensus-proposer = { workspace = true, default-features = true } +cumulus-client-parachain-inherent = { workspace = true, default-features = true } +cumulus-primitives-aura = { workspace = true, default-features = true } +cumulus-primitives-core = { workspace = true, default-features = true } +cumulus-client-collator = { workspace = true, default-features = true } # Polkadot -polkadot-primitives = { path = "../../../../polkadot/primitives" } -polkadot-node-primitives = { path = "../../../../polkadot/node/primitives" } -polkadot-node-subsystem = { path = "../../../../polkadot/node/subsystem" } -polkadot-overseer = { path = "../../../../polkadot/node/overseer" } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-overseer = { workspace = true, default-features = true } diff --git a/cumulus/client/consensus/aura/src/collators/lookahead.rs b/cumulus/client/consensus/aura/src/collators/lookahead.rs index 09416233ea9b39dfd4bd4126149d51f922d7b6e4..b6f7b07f55d3e4f2f779b7d90f933b5f897a8079 100644 --- a/cumulus/client/consensus/aura/src/collators/lookahead.rs +++ b/cumulus/client/consensus/aura/src/collators/lookahead.rs @@ -363,13 +363,11 @@ where Ok(x) => x, }; - let validation_code_hash = match params.code_hash_provider.code_hash_at(parent_hash) - { - None => { - tracing::error!(target: crate::LOG_TARGET, ?parent_hash, "Could not fetch validation code hash"); - break - }, - Some(v) => v, + let Some(validation_code_hash) = + params.code_hash_provider.code_hash_at(parent_hash) + else { + tracing::error!(target: crate::LOG_TARGET, ?parent_hash, "Could not fetch validation code hash"); + break }; super::check_validation_code_or_log( diff --git a/cumulus/client/consensus/aura/src/collators/mod.rs b/cumulus/client/consensus/aura/src/collators/mod.rs index 6e0067d0cedb602face8943737f99f3cb1a201a3..0abc034c1ed6baf051d04d1ff04680c3192acbf3 100644 --- a/cumulus/client/consensus/aura/src/collators/mod.rs +++ b/cumulus/client/consensus/aura/src/collators/mod.rs @@ -64,7 +64,7 @@ async fn check_validation_code_or_log( ?relay_parent, ?local_validation_code_hash, relay_validation_code_hash = ?state, - "Parachain code doesn't match validation code stored in the relay chain state", + "Parachain code doesn't match validation code stored in the relay chain state.", ); }, None => { diff --git a/cumulus/client/consensus/aura/src/equivocation_import_queue.rs b/cumulus/client/consensus/aura/src/equivocation_import_queue.rs index be554bdcfc79b986f11da24404a47556031657b2..68f2d37c8748863be879134d3fd0849adf5efb11 100644 --- a/cumulus/client/consensus/aura/src/equivocation_import_queue.rs +++ b/cumulus/client/consensus/aura/src/equivocation_import_queue.rs @@ -21,6 +21,7 @@ /// should be thrown out and which ones should be kept. use codec::Codec; use cumulus_client_consensus_common::ParachainBlockImportMarker; +use parking_lot::Mutex; use schnellru::{ByLength, LruMap}; use sc_consensus::{ @@ -70,7 +71,7 @@ impl NaiveEquivocationDefender { struct Verifier { client: Arc, create_inherent_data_providers: CIDP, - defender: NaiveEquivocationDefender, + defender: Mutex, telemetry: Option, _phantom: std::marker::PhantomData (Block, P)>, } @@ -88,7 +89,7 @@ where CIDP: CreateInherentDataProviders, { async fn verify( - &mut self, + &self, mut block_params: BlockImportParams, ) -> Result, String> { // Skip checks that include execution, if being told so, or when importing only state. @@ -137,7 +138,7 @@ where block_params.post_hash = Some(post_hash); // Check for and reject egregious amounts of equivocations. - if self.defender.insert_and_check(slot) { + if self.defender.lock().insert_and_check(slot) { return Err(format!( "Rejecting block {:?} due to excessive equivocations at slot", post_hash, @@ -243,7 +244,7 @@ where let verifier = Verifier:: { client, create_inherent_data_providers, - defender: NaiveEquivocationDefender::default(), + defender: Mutex::new(NaiveEquivocationDefender::default()), telemetry, _phantom: std::marker::PhantomData, }; diff --git a/cumulus/client/consensus/common/Cargo.toml b/cumulus/client/consensus/common/Cargo.toml index d369304e2e33f6ec51b02f7853b51fee9c4581ae..4bc2f1d1e600e5f82faaf7cfa84a3b831cf085b7 100644 --- a/cumulus/client/consensus/common/Cargo.toml +++ b/cumulus/client/consensus/common/Cargo.toml @@ -10,41 +10,42 @@ license = "GPL-3.0-or-later WITH Classpath-exception-2.0" workspace = true [dependencies] -async-trait = "0.1.79" -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } -dyn-clone = "1.0.16" -futures = "0.3.28" +async-trait = { workspace = true } +codec = { features = ["derive"], workspace = true, default-features = true } +dyn-clone = { workspace = true } +futures = { workspace = true } log = { workspace = true, default-features = true } -tracing = "0.1.37" +tracing = { workspace = true, default-features = true } # Substrate -sc-client-api = { path = "../../../../substrate/client/api" } -sc-consensus = { path = "../../../../substrate/client/consensus/common" } -sc-consensus-babe = { path = "../../../../substrate/client/consensus/babe" } -sp-blockchain = { path = "../../../../substrate/primitives/blockchain" } -sp-consensus = { path = "../../../../substrate/primitives/consensus/common" } -sp-consensus-slots = { path = "../../../../substrate/primitives/consensus/slots" } -sp-core = { path = "../../../../substrate/primitives/core" } -sp-runtime = { path = "../../../../substrate/primitives/runtime" } -sp-timestamp = { path = "../../../../substrate/primitives/timestamp" } -sp-trie = { path = "../../../../substrate/primitives/trie" } -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../../../substrate/utils/prometheus" } +sc-client-api = { workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } +sc-consensus-babe = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-consensus-slots = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-timestamp = { workspace = true, default-features = true } +sp-trie = { workspace = true, default-features = true } +sp-version = { workspace = true, default-features = true } +prometheus-endpoint = { workspace = true, default-features = true } # Polkadot -polkadot-primitives = { path = "../../../../polkadot/primitives" } +polkadot-primitives = { workspace = true, default-features = true } # Cumulus -cumulus-primitives-core = { path = "../../../primitives/core" } -cumulus-relay-chain-interface = { path = "../../relay-chain-interface" } -cumulus-client-pov-recovery = { path = "../../pov-recovery" } -schnellru = "0.2.1" +cumulus-primitives-core = { workspace = true, default-features = true } +cumulus-relay-chain-interface = { workspace = true, default-features = true } +cumulus-client-pov-recovery = { workspace = true, default-features = true } +schnellru = { workspace = true } [dev-dependencies] -futures-timer = "3.0.2" +futures-timer = { workspace = true } # Substrate -sp-tracing = { path = "../../../../substrate/primitives/tracing" } +sp-tracing = { workspace = true, default-features = true } # Cumulus -cumulus-test-client = { path = "../../../test/client" } -cumulus-test-relay-sproof-builder = { path = "../../../test/relay-sproof-builder" } +cumulus-test-client = { workspace = true } +cumulus-test-relay-sproof-builder = { workspace = true, default-features = true } diff --git a/cumulus/client/consensus/common/src/import_queue.rs b/cumulus/client/consensus/common/src/import_queue.rs index 8024b7695a285a414c89cea74561ece91dfd48de..488693604fefccbe2c9b37a22c8ee3c4809383f2 100644 --- a/cumulus/client/consensus/common/src/import_queue.rs +++ b/cumulus/client/consensus/common/src/import_queue.rs @@ -50,7 +50,7 @@ pub struct VerifyNothing; #[async_trait::async_trait] impl Verifier for VerifyNothing { async fn verify( - &mut self, + &self, params: BlockImportParams, ) -> Result, String> { Ok(params) diff --git a/cumulus/client/consensus/common/src/lib.rs b/cumulus/client/consensus/common/src/lib.rs index cebe34e7ea58828372a9261e3be94866e119546a..2b0d8290182abd722ebe72a662b45a9564ff273d 100644 --- a/cumulus/client/consensus/common/src/lib.rs +++ b/cumulus/client/consensus/common/src/lib.rs @@ -172,13 +172,13 @@ impl Clone for ParachainBlockImport { impl BlockImport for ParachainBlockImport where Block: BlockT, - BI: BlockImport + Send, + BI: BlockImport + Send + Sync, BE: Backend, { type Error = BI::Error; async fn check_block( - &mut self, + &self, block: sc_consensus::BlockCheckParams, ) -> Result { self.inner.check_block(block).await diff --git a/cumulus/client/consensus/common/src/tests.rs b/cumulus/client/consensus/common/src/tests.rs index aca9226570723c3285b2817e6bcdca22b141968b..2a944bc7f9fa221d63c48678f2899d50251b3655 100644 --- a/cumulus/client/consensus/common/src/tests.rs +++ b/cumulus/client/consensus/common/src/tests.rs @@ -38,6 +38,7 @@ use polkadot_primitives::HeadData; use sc_client_api::{Backend as _, UsageProvider}; use sc_consensus::{BlockImport, BlockImportParams, ForkChoiceStrategy}; use sp_consensus::{BlockOrigin, BlockStatus}; +use sp_version::RuntimeVersion; use std::{ collections::{BTreeMap, HashMap}, pin::Pin, @@ -153,6 +154,14 @@ impl RelayChainInterface for Relaychain { unimplemented!("Not needed for test") } + async fn candidates_pending_availability( + &self, + _: PHash, + _: ParaId, + ) -> RelayChainResult> { + unimplemented!("Not needed for test") + } + async fn session_index_for_child(&self, _: PHash) -> RelayChainResult { Ok(0) } @@ -247,6 +256,10 @@ impl RelayChainInterface for Relaychain { extrinsics_root: PHash::zero(), })) } + + async fn version(&self, _: PHash) -> RelayChainResult { + unimplemented!("Not needed for test") + } } fn sproof_with_best_parent(client: &Client) -> RelayStateSproofBuilder { diff --git a/cumulus/client/consensus/proposer/Cargo.toml b/cumulus/client/consensus/proposer/Cargo.toml index 42ca4e06f8f45e410006304cf1290e811e153b4c..ce91d48bf589a88e5eb0f81507e73da3d28a6b81 100644 --- a/cumulus/client/consensus/proposer/Cargo.toml +++ b/cumulus/client/consensus/proposer/Cargo.toml @@ -10,15 +10,15 @@ license = "GPL-3.0-or-later WITH Classpath-exception-2.0" workspace = true [dependencies] -anyhow = "1.0" -async-trait = "0.1.79" +anyhow = { workspace = true } +async-trait = { workspace = true } thiserror = { workspace = true } # Substrate -sp-consensus = { path = "../../../../substrate/primitives/consensus/common" } -sp-inherents = { path = "../../../../substrate/primitives/inherents" } -sp-runtime = { path = "../../../../substrate/primitives/runtime" } -sp-state-machine = { path = "../../../../substrate/primitives/state-machine" } +sp-consensus = { 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 } # Cumulus -cumulus-primitives-parachain-inherent = { path = "../../../primitives/parachain-inherent" } +cumulus-primitives-parachain-inherent = { workspace = true, default-features = true } diff --git a/cumulus/client/consensus/relay-chain/Cargo.toml b/cumulus/client/consensus/relay-chain/Cargo.toml index 7c3a901db6c32131e762c3de971606fffddebc80..f3ee6fc2f7d257ff2be86c3d9a0096ea78d30be8 100644 --- a/cumulus/client/consensus/relay-chain/Cargo.toml +++ b/cumulus/client/consensus/relay-chain/Cargo.toml @@ -10,23 +10,23 @@ license = "GPL-3.0-or-later WITH Classpath-exception-2.0" workspace = true [dependencies] -async-trait = "0.1.79" -futures = "0.3.28" -parking_lot = "0.12.1" -tracing = "0.1.37" +async-trait = { workspace = true } +futures = { workspace = true } +parking_lot = { workspace = true, default-features = true } +tracing = { workspace = true, default-features = true } # Substrate -sc-consensus = { path = "../../../../substrate/client/consensus/common" } -sp-api = { path = "../../../../substrate/primitives/api" } -sp-block-builder = { path = "../../../../substrate/primitives/block-builder" } -sp-blockchain = { path = "../../../../substrate/primitives/blockchain" } -sp-consensus = { path = "../../../../substrate/primitives/consensus/common" } -sp-core = { path = "../../../../substrate/primitives/core" } -sp-inherents = { path = "../../../../substrate/primitives/inherents" } -sp-runtime = { path = "../../../../substrate/primitives/runtime" } -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../../../substrate/utils/prometheus" } +sc-consensus = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-block-builder = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-inherents = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +prometheus-endpoint = { workspace = true, default-features = true } # Cumulus -cumulus-client-consensus-common = { path = "../common" } -cumulus-primitives-core = { path = "../../../primitives/core" } -cumulus-relay-chain-interface = { path = "../../relay-chain-interface" } +cumulus-client-consensus-common = { workspace = true, default-features = true } +cumulus-primitives-core = { workspace = true, default-features = true } +cumulus-relay-chain-interface = { workspace = true, default-features = true } diff --git a/cumulus/client/consensus/relay-chain/src/import_queue.rs b/cumulus/client/consensus/relay-chain/src/import_queue.rs index 1b521e79d4820fbc4c6709cb177170afa60d3f37..1d6f039da4c123fc79c1132b7b96e93a96c69411 100644 --- a/cumulus/client/consensus/relay-chain/src/import_queue.rs +++ b/cumulus/client/consensus/relay-chain/src/import_queue.rs @@ -52,7 +52,7 @@ where CIDP: CreateInherentDataProviders, { async fn verify( - &mut self, + &self, mut block_params: BlockImportParams, ) -> Result, String> { block_params.fork_choice = Some(sc_consensus::ForkChoiceStrategy::Custom( diff --git a/cumulus/client/network/Cargo.toml b/cumulus/client/network/Cargo.toml index d4fc752872589fbfd361f5df49939874d208ab3d..bc67678eedeb199d57aad6f35f5be386231b841e 100644 --- a/cumulus/client/network/Cargo.toml +++ b/cumulus/client/network/Cargo.toml @@ -10,47 +10,51 @@ license = "GPL-3.0-or-later WITH Classpath-exception-2.0" workspace = true [dependencies] -async-trait = "0.1.79" -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } -futures = "0.3.28" -futures-timer = "3.0.2" -parking_lot = "0.12.1" -tracing = "0.1.37" +async-trait = { workspace = true } +codec = { features = ["derive"], workspace = true, default-features = true } +futures = { workspace = true } +futures-timer = { workspace = true } +parking_lot = { workspace = true, default-features = true } +tracing = { workspace = true, default-features = true } # Substrate -sc-client-api = { path = "../../../substrate/client/api" } -sp-blockchain = { path = "../../../substrate/primitives/blockchain" } -sp-consensus = { path = "../../../substrate/primitives/consensus/common" } -sp-core = { path = "../../../substrate/primitives/core" } -sp-runtime = { path = "../../../substrate/primitives/runtime" } -sp-state-machine = { path = "../../../substrate/primitives/state-machine" } +sc-client-api = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-state-machine = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-version = { workspace = true, default-features = true } # Polkadot -polkadot-node-primitives = { path = "../../../polkadot/node/primitives" } -polkadot-parachain-primitives = { path = "../../../polkadot/parachain" } -polkadot-primitives = { path = "../../../polkadot/primitives" } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-parachain-primitives = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } # Cumulus -cumulus-relay-chain-interface = { path = "../relay-chain-interface" } +cumulus-relay-chain-interface = { workspace = true, default-features = true } [dev-dependencies] -portpicker = "0.1.1" -tokio = { version = "1.32.0", features = ["macros"] } -url = "2.4.0" +portpicker = { workspace = true } +tokio = { features = ["macros"], workspace = true, default-features = true } +url = { workspace = true } +rstest = { workspace = true } # Substrate -sc-cli = { path = "../../../substrate/client/cli" } -sc-client-api = { path = "../../../substrate/client/api" } -sp-consensus = { path = "../../../substrate/primitives/consensus/common" } -sp-core = { path = "../../../substrate/primitives/core" } -sp-keyring = { path = "../../../substrate/primitives/keyring" } -sp-keystore = { path = "../../../substrate/primitives/keystore" } -substrate-test-utils = { path = "../../../substrate/test-utils" } +sc-cli = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +substrate-test-utils = { workspace = true } # Polkadot -polkadot-test-client = { path = "../../../polkadot/node/test/client" } +polkadot-test-client = { workspace = true } # Cumulus -cumulus-primitives-core = { path = "../../primitives/core" } -cumulus-relay-chain-inprocess-interface = { path = "../relay-chain-inprocess-interface" } -cumulus-test-service = { path = "../../test/service" } +cumulus-primitives-core = { workspace = true, default-features = true } +cumulus-relay-chain-inprocess-interface = { workspace = true, default-features = true } +cumulus-test-service = { workspace = true } diff --git a/cumulus/client/network/src/lib.rs b/cumulus/client/network/src/lib.rs index f442ed5840bddcd4a859d149635ff740e4d232f4..dab15bba590a0f46720d45bdaddc92f594fb8a9f 100644 --- a/cumulus/client/network/src/lib.rs +++ b/cumulus/client/network/src/lib.rs @@ -20,6 +20,7 @@ //! that use the relay chain provided consensus. See [`RequireSecondedInBlockAnnounce`] //! and [`WaitToAnnounce`] for more information about this implementation. +use sp_api::RuntimeApiInfo; use sp_consensus::block_validation::{ BlockAnnounceValidator as BlockAnnounceValidatorT, Validation, }; @@ -28,6 +29,7 @@ use sp_runtime::traits::{Block as BlockT, Header as HeaderT}; use cumulus_relay_chain_interface::RelayChainInterface; use polkadot_node_primitives::{CollationSecondedSignal, Statement}; +use polkadot_node_subsystem::messages::RuntimeApiRequest; use polkadot_parachain_primitives::primitives::HeadData; use polkadot_primitives::{ CandidateReceipt, CompactStatement, Hash as PHash, Id as ParaId, OccupiedCoreAssumption, @@ -266,18 +268,41 @@ where Ok(para_head) } - /// Get the backed block hash of the given parachain in the relay chain. - async fn backed_block_hash( + /// Get the backed block hashes of the given parachain in the relay chain. + async fn backed_block_hashes( relay_chain_interface: &RCInterface, hash: PHash, para_id: ParaId, - ) -> Result, BoxedError> { - let candidate_receipt = relay_chain_interface - .candidate_pending_availability(hash, para_id) + ) -> Result, BoxedError> { + let runtime_api_version = relay_chain_interface + .version(hash) .await .map_err(|e| Box::new(BlockAnnounceError(format!("{:?}", e))) as Box<_>)?; + let parachain_host_runtime_api_version = + runtime_api_version + .api_version( + &>::ID, + ) + .unwrap_or_default(); + + // If the relay chain runtime does not support the new runtime API, fallback to the + // deprecated one. + let candidate_receipts = if parachain_host_runtime_api_version < + RuntimeApiRequest::CANDIDATES_PENDING_AVAILABILITY_RUNTIME_REQUIREMENT + { + #[allow(deprecated)] + relay_chain_interface + .candidate_pending_availability(hash, para_id) + .await + .map(|c| c.into_iter().collect::>()) + } else { + relay_chain_interface.candidates_pending_availability(hash, para_id).await + } + .map_err(|e| Box::new(BlockAnnounceError(format!("{:?}", e))) as Box<_>)?; - Ok(candidate_receipt.map(|cr| cr.descriptor.para_head)) + Ok(candidate_receipts.into_iter().map(|cr| cr.descriptor.para_head)) } /// Handle a block announcement with empty data (no statement) attached to it. @@ -298,15 +323,20 @@ where let best_head = Self::included_block(&relay_chain_interface, relay_chain_best_hash, para_id).await?; let known_best_number = best_head.number(); - let backed_block = || async { - Self::backed_block_hash(&relay_chain_interface, relay_chain_best_hash, para_id).await - }; if best_head == header { tracing::debug!(target: LOG_TARGET, "Announced block matches best block.",); - Ok(Validation::Success { is_new_best: true }) - } else if Some(HeadData(header.encode()).hash()) == backed_block().await? { + return Ok(Validation::Success { is_new_best: true }) + } + + let mut backed_blocks = + Self::backed_block_hashes(&relay_chain_interface, relay_chain_best_hash, para_id) + .await?; + + let head_hash = HeadData(header.encode()).hash(); + + if backed_blocks.any(|block_hash| block_hash == head_hash) { tracing::debug!(target: LOG_TARGET, "Announced block matches latest backed block.",); Ok(Validation::Success { is_new_best: true }) diff --git a/cumulus/client/network/src/tests.rs b/cumulus/client/network/src/tests.rs index 3f5757d5eac13cd751a89e77545a937b3223c9a0..eb0d7f0e01b391279648a5aea6031a275cf409a5 100644 --- a/cumulus/client/network/src/tests.rs +++ b/cumulus/client/network/src/tests.rs @@ -34,6 +34,7 @@ use polkadot_test_client::{ Client as PClient, ClientBlockImportExt, DefaultTestClientBuilderExt, FullBackend as PBackend, InitPolkadotBlockBuilder, TestClientBuilder, TestClientBuilderExt, }; +use rstest::rstest; use sc_client_api::{Backend, BlockchainEvents}; use sp_blockchain::HeaderBackend; use sp_consensus::BlockOrigin; @@ -42,7 +43,8 @@ use sp_keyring::Sr25519Keyring; use sp_keystore::{testing::MemoryKeystore, Keystore, KeystorePtr}; use sp_runtime::RuntimeAppPublic; use sp_state_machine::StorageValue; -use std::{collections::BTreeMap, time::Duration}; +use sp_version::RuntimeVersion; +use std::{borrow::Cow, collections::BTreeMap, time::Duration}; fn check_error(error: crate::BoxedError, check_error: impl Fn(&BlockAnnounceError) -> bool) { let error = *error @@ -53,6 +55,33 @@ fn check_error(error: crate::BoxedError, check_error: impl Fn(&BlockAnnounceErro } } +fn dummy_candidate() -> CommittedCandidateReceipt { + CommittedCandidateReceipt { + descriptor: CandidateDescriptor { + para_head: polkadot_parachain_primitives::primitives::HeadData( + default_header().encode(), + ) + .hash(), + para_id: 0u32.into(), + relay_parent: PHash::random(), + collator: CollatorPair::generate().0.public(), + persisted_validation_data_hash: PHash::random(), + pov_hash: PHash::random(), + erasure_root: PHash::random(), + signature: sp_core::sr25519::Signature::default().into(), + validation_code_hash: ValidationCodeHash::from(PHash::random()), + }, + commitments: CandidateCommitments { + upward_messages: Default::default(), + horizontal_messages: Default::default(), + new_validation_code: None, + head_data: HeadData(Vec::new()), + processed_downward_messages: 0, + hrmp_watermark: 0, + }, + } +} + #[derive(Clone)] struct DummyRelayChainInterface { data: Arc>, @@ -69,6 +98,8 @@ impl DummyRelayChainInterface { data: Arc::new(Mutex::new(ApiData { validators: vec![Sr25519Keyring::Alice.public().into()], has_pending_availability: false, + runtime_version: + RuntimeApiRequest::CANDIDATES_PENDING_AVAILABILITY_RUNTIME_REQUIREMENT, })), relay_client: Arc::new(builder.build()), relay_backend, @@ -131,36 +162,37 @@ impl RelayChainInterface for DummyRelayChainInterface { _: PHash, _: ParaId, ) -> RelayChainResult> { + if self.data.lock().runtime_version >= + RuntimeApiRequest::CANDIDATES_PENDING_AVAILABILITY_RUNTIME_REQUIREMENT + { + panic!("Should have used candidates_pending_availability instead"); + } + if self.data.lock().has_pending_availability { - Ok(Some(CommittedCandidateReceipt { - descriptor: CandidateDescriptor { - para_head: polkadot_parachain_primitives::primitives::HeadData( - default_header().encode(), - ) - .hash(), - para_id: 0u32.into(), - relay_parent: PHash::random(), - collator: CollatorPair::generate().0.public(), - persisted_validation_data_hash: PHash::random(), - pov_hash: PHash::random(), - erasure_root: PHash::random(), - signature: sp_core::sr25519::Signature::default().into(), - validation_code_hash: ValidationCodeHash::from(PHash::random()), - }, - commitments: CandidateCommitments { - upward_messages: Default::default(), - horizontal_messages: Default::default(), - new_validation_code: None, - head_data: HeadData(Vec::new()), - processed_downward_messages: 0, - hrmp_watermark: 0, - }, - })) + Ok(Some(dummy_candidate())) } else { Ok(None) } } + async fn candidates_pending_availability( + &self, + _: PHash, + _: ParaId, + ) -> RelayChainResult> { + if self.data.lock().runtime_version < + RuntimeApiRequest::CANDIDATES_PENDING_AVAILABILITY_RUNTIME_REQUIREMENT + { + panic!("Should have used candidate_pending_availability instead"); + } + + if self.data.lock().has_pending_availability { + Ok(vec![dummy_candidate()]) + } else { + Ok(vec![]) + } + } + async fn session_index_for_child(&self, _: PHash) -> RelayChainResult { Ok(0) } @@ -264,6 +296,28 @@ impl RelayChainInterface for DummyRelayChainInterface { Ok(header) } + + async fn version(&self, _: PHash) -> RelayChainResult { + let version = self.data.lock().runtime_version; + + let apis = sp_version::create_apis_vec!([( + >::ID, + version + )]) + .into_owned() + .to_vec(); + + Ok(RuntimeVersion { + spec_name: sp_version::create_runtime_str!("test"), + impl_name: sp_version::create_runtime_str!("test"), + authoring_version: 1, + spec_version: 1, + impl_version: 0, + apis: Cow::Owned(apis), + transaction_version: 5, + state_version: 1, + }) + } } fn make_validator_and_api() -> ( @@ -574,11 +628,14 @@ fn relay_parent_not_imported_when_block_announce_is_processed() { /// Ensures that when we receive a block announcement without a statement included, while the block /// is not yet included by the node checking the announcement, but the node is already backed. -#[test] -fn block_announced_without_statement_and_block_only_backed() { +#[rstest] +#[case(RuntimeApiRequest::CANDIDATES_PENDING_AVAILABILITY_RUNTIME_REQUIREMENT)] +#[case(10)] +fn block_announced_without_statement_and_block_only_backed(#[case] runtime_version: u32) { block_on(async move { let (mut validator, api) = make_validator_and_api(); api.data.lock().has_pending_availability = true; + api.data.lock().runtime_version = runtime_version; let header = default_header(); @@ -592,4 +649,5 @@ fn block_announced_without_statement_and_block_only_backed() { struct ApiData { validators: Vec, has_pending_availability: bool, + runtime_version: u32, } diff --git a/cumulus/client/parachain-inherent/Cargo.toml b/cumulus/client/parachain-inherent/Cargo.toml index 85619e8403458c0bfa3dae6dadc688f2cb895731..9d346ce17f564b0c27a815294cfc61c760da303e 100644 --- a/cumulus/client/parachain-inherent/Cargo.toml +++ b/cumulus/client/parachain-inherent/Cargo.toml @@ -7,24 +7,24 @@ description = "Inherent that needs to be present in every parachain block. Conta license = "Apache-2.0" [dependencies] -async-trait = "0.1.79" -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } -scale-info = { version = "2.11.1", features = ["derive"] } -tracing = { version = "0.1.37" } +async-trait = { workspace = true } +codec = { features = ["derive"], workspace = true, default-features = true } +scale-info = { features = ["derive"], workspace = true, default-features = true } +tracing = { workspace = true, default-features = true } # Substrate -sc-client-api = { path = "../../../substrate/client/api" } -sp-api = { path = "../../../substrate/primitives/api" } -sp-crypto-hashing = { path = "../../../substrate/primitives/crypto/hashing" } -sp-inherents = { path = "../../../substrate/primitives/inherents" } -sp-runtime = { path = "../../../substrate/primitives/runtime" } -sp-state-machine = { path = "../../../substrate/primitives/state-machine" } -sp-std = { path = "../../../substrate/primitives/std" } -sp-storage = { path = "../../../substrate/primitives/storage" } -sp-trie = { path = "../../../substrate/primitives/trie" } +sc-client-api = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +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 } # Cumulus -cumulus-primitives-core = { path = "../../primitives/core" } -cumulus-primitives-parachain-inherent = { path = "../../primitives/parachain-inherent" } -cumulus-relay-chain-interface = { path = "../relay-chain-interface" } -cumulus-test-relay-sproof-builder = { path = "../../test/relay-sproof-builder" } +cumulus-primitives-core = { workspace = true, default-features = true } +cumulus-primitives-parachain-inherent = { workspace = true, default-features = true } +cumulus-relay-chain-interface = { workspace = true, default-features = true } +cumulus-test-relay-sproof-builder = { workspace = true, default-features = true } diff --git a/cumulus/client/pov-recovery/Cargo.toml b/cumulus/client/pov-recovery/Cargo.toml index 7afe7fae34bd799ed75d557ad5f0ca5067743f7f..a95b24bc2933aa2d8529e70ee2b37759625b1757 100644 --- a/cumulus/client/pov-recovery/Cargo.toml +++ b/cumulus/client/pov-recovery/Cargo.toml @@ -10,38 +10,46 @@ license = "GPL-3.0-or-later WITH Classpath-exception-2.0" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } -futures = "0.3.28" -futures-timer = "3.0.2" -rand = "0.8.5" -tracing = "0.1.37" +codec = { features = ["derive"], workspace = true, default-features = true } +futures = { workspace = true } +futures-timer = { workspace = true } +rand = { workspace = true, default-features = true } +tracing = { workspace = true, default-features = true } # Substrate -sc-client-api = { path = "../../../substrate/client/api" } -sc-consensus = { path = "../../../substrate/client/consensus/common" } -sp-consensus = { path = "../../../substrate/primitives/consensus/common" } -sp-maybe-compressed-blob = { path = "../../../substrate/primitives/maybe-compressed-blob" } -sp-runtime = { path = "../../../substrate/primitives/runtime" } +sc-client-api = { workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-maybe-compressed-blob = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-version = { workspace = true, default-features = true } # Polkadot -polkadot-node-primitives = { path = "../../../polkadot/node/primitives" } -polkadot-node-subsystem = { path = "../../../polkadot/node/subsystem" } -polkadot-overseer = { path = "../../../polkadot/node/overseer" } -polkadot-primitives = { path = "../../../polkadot/primitives" } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-overseer = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } # Cumulus -cumulus-primitives-core = { path = "../../primitives/core" } -cumulus-relay-chain-interface = { path = "../relay-chain-interface" } -async-trait = "0.1.79" +cumulus-primitives-core = { workspace = true, default-features = true } +cumulus-relay-chain-interface = { workspace = true, default-features = true } +async-trait = { workspace = true } [dev-dependencies] -tokio = { version = "1.32.0", features = ["macros"] } -portpicker = "0.1.1" +rstest = { workspace = true } +tokio = { features = ["macros"], workspace = true, default-features = true } +portpicker = { workspace = true } +sp-blockchain = { workspace = true, default-features = true } +cumulus-test-client = { workspace = true } +sc-utils = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +assert_matches = { workspace = true } # Cumulus -cumulus-test-service = { path = "../../test/service" } +cumulus-test-service = { workspace = true } # Substrate -sc-cli = { path = "../../../substrate/client/cli" } -sc-client-api = { path = "../../../substrate/client/api" } -substrate-test-utils = { path = "../../../substrate/test-utils" } +sc-cli = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +substrate-test-utils = { workspace = true } diff --git a/cumulus/client/pov-recovery/src/active_candidate_recovery.rs b/cumulus/client/pov-recovery/src/active_candidate_recovery.rs index c41c543f04d1f0d3f3a9fe7356dc7ab3ed5e5f11..50de98909ea471ea3de39a9edd85f4f9d71a8b3b 100644 --- a/cumulus/client/pov-recovery/src/active_candidate_recovery.rs +++ b/cumulus/client/pov-recovery/src/active_candidate_recovery.rs @@ -21,7 +21,7 @@ use polkadot_node_subsystem::messages::AvailabilityRecoveryMessage; use futures::{channel::oneshot, stream::FuturesUnordered, Future, FutureExt, StreamExt}; -use std::{collections::HashSet, pin::Pin, sync::Arc}; +use std::{pin::Pin, sync::Arc}; use crate::RecoveryHandle; @@ -32,14 +32,12 @@ pub(crate) struct ActiveCandidateRecovery { /// The recoveries that are currently being executed. recoveries: FuturesUnordered>)> + Send>>>, - /// The block hashes of the candidates currently being recovered. - candidates: HashSet, recovery_handle: Box, } impl ActiveCandidateRecovery { pub fn new(recovery_handle: Box) -> Self { - Self { recoveries: Default::default(), candidates: Default::default(), recovery_handle } + Self { recoveries: Default::default(), recovery_handle } } /// Recover the given `candidate`. @@ -63,8 +61,6 @@ impl ActiveCandidateRecovery { ) .await; - self.candidates.insert(block_hash); - self.recoveries.push( async move { match rx.await { @@ -97,7 +93,6 @@ impl ActiveCandidateRecovery { pub async fn wait_for_recovery(&mut self) -> (Block::Hash, Option>) { loop { if let Some(res) = self.recoveries.next().await { - self.candidates.remove(&res.0); return res } else { futures::pending!() diff --git a/cumulus/client/pov-recovery/src/lib.rs b/cumulus/client/pov-recovery/src/lib.rs index 0ca21749c3eb557a78f0996c703e86b35cab6f17..6ace18155e871d40baa2662c8c13b605b5768bbe 100644 --- a/cumulus/client/pov-recovery/src/lib.rs +++ b/cumulus/client/pov-recovery/src/lib.rs @@ -48,11 +48,12 @@ use sc_client_api::{BlockBackend, BlockchainEvents, UsageProvider}; use sc_consensus::import_queue::{ImportQueueService, IncomingBlock}; +use sp_api::RuntimeApiInfo; use sp_consensus::{BlockOrigin, BlockStatus, SyncOracle}; use sp_runtime::traits::{Block as BlockT, Header as HeaderT, NumberFor}; use polkadot_node_primitives::{PoV, POV_BOMB_LIMIT}; -use polkadot_node_subsystem::messages::AvailabilityRecoveryMessage; +use polkadot_node_subsystem::messages::{AvailabilityRecoveryMessage, RuntimeApiRequest}; use polkadot_overseer::Handle as OverseerHandle; use polkadot_primitives::{ CandidateReceipt, CommittedCandidateReceipt, Id as ParaId, SessionIndex, @@ -75,6 +76,9 @@ use std::{ time::Duration, }; +#[cfg(test)] +mod tests; + mod active_candidate_recovery; use active_candidate_recovery::ActiveCandidateRecovery; @@ -544,7 +548,7 @@ where ) .await { - Ok(pending_candidate_stream) => pending_candidate_stream.fuse(), + Ok(pending_candidates_stream) => pending_candidates_stream.fuse(), Err(err) => { tracing::error!(target: LOG_TARGET, error = ?err, "Unable to retrieve pending candidate stream."); return @@ -554,9 +558,11 @@ where futures::pin_mut!(pending_candidates); loop { select! { - pending_candidate = pending_candidates.next() => { - if let Some((receipt, session_index)) = pending_candidate { - self.handle_pending_candidate(receipt, session_index); + next_pending_candidates = pending_candidates.next() => { + if let Some((candidates, session_index)) = next_pending_candidates { + for candidate in candidates { + self.handle_pending_candidate(candidate, session_index); + } } else { tracing::debug!(target: LOG_TARGET, "Pending candidates stream ended"); return; @@ -615,7 +621,7 @@ async fn pending_candidates( relay_chain_client: impl RelayChainInterface + Clone, para_id: ParaId, sync_service: Arc, -) -> RelayChainResult> { +) -> RelayChainResult, SessionIndex)>> { let import_notification_stream = relay_chain_client.import_notification_stream().await?; let filtered_stream = import_notification_stream.filter_map(move |n| { @@ -632,16 +638,54 @@ async fn pending_candidates( return None } - let pending_availability_result = client_for_closure - .candidate_pending_availability(hash, para_id) + let runtime_api_version = client_for_closure + .version(hash) .await .map_err(|e| { tracing::error!( target: LOG_TARGET, error = ?e, - "Failed to fetch pending candidates.", + "Failed to fetch relay chain runtime version.", ) - }); + }) + .ok()?; + let parachain_host_runtime_api_version = runtime_api_version + .api_version( + &>::ID, + ) + .unwrap_or_default(); + + // If the relay chain runtime does not support the new runtime API, fallback to the + // deprecated one. + let pending_availability_result = if parachain_host_runtime_api_version < + RuntimeApiRequest::CANDIDATES_PENDING_AVAILABILITY_RUNTIME_REQUIREMENT + { + #[allow(deprecated)] + client_for_closure + .candidate_pending_availability(hash, para_id) + .await + .map_err(|e| { + tracing::error!( + target: LOG_TARGET, + error = ?e, + "Failed to fetch pending candidates.", + ) + }) + .map(|candidate| candidate.into_iter().collect::>()) + } else { + client_for_closure.candidates_pending_availability(hash, para_id).await.map_err( + |e| { + tracing::error!( + target: LOG_TARGET, + error = ?e, + "Failed to fetch pending candidates.", + ) + }, + ) + }; + let session_index_result = client_for_closure.session_index_for_child(hash).await.map_err(|e| { tracing::error!( @@ -651,8 +695,8 @@ async fn pending_candidates( ) }); - if let Ok(Some(candidate)) = pending_availability_result { - session_index_result.map(|session_index| (candidate, session_index)).ok() + if let Ok(candidates) = pending_availability_result { + session_index_result.map(|session_index| (candidates, session_index)).ok() } else { None } diff --git a/cumulus/client/pov-recovery/src/tests.rs b/cumulus/client/pov-recovery/src/tests.rs new file mode 100644 index 0000000000000000000000000000000000000000..75bf308ef27aa051e42806b7f65e7ab8b45a9c1a --- /dev/null +++ b/cumulus/client/pov-recovery/src/tests.rs @@ -0,0 +1,1404 @@ +// 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 . + +use super::*; +use assert_matches::assert_matches; +use codec::{Decode, Encode}; +use cumulus_primitives_core::relay_chain::{BlockId, CandidateCommitments, CandidateDescriptor}; +use cumulus_relay_chain_interface::{ + InboundDownwardMessage, InboundHrmpMessage, OccupiedCoreAssumption, PHash, PHeader, + PersistedValidationData, StorageValue, ValidationCodeHash, ValidatorId, +}; +use cumulus_test_client::{ + runtime::{Block, Header}, + Sr25519Keyring, +}; +use futures::{channel::mpsc, SinkExt}; +use polkadot_node_primitives::AvailableData; +use polkadot_node_subsystem::{messages::AvailabilityRecoveryMessage, RecoveryError, TimeoutExt}; +use rstest::rstest; +use sc_client_api::{ + BlockImportNotification, ClientInfo, CompactProof, FinalityNotification, FinalityNotifications, + FinalizeSummary, ImportNotifications, StorageEventStream, StorageKey, +}; +use sc_consensus::import_queue::RuntimeOrigin; +use sc_utils::mpsc::{TracingUnboundedReceiver, TracingUnboundedSender}; +use sp_blockchain::Info; +use sp_runtime::{generic::SignedBlock, Justifications}; +use sp_version::RuntimeVersion; +use std::{ + borrow::Cow, + collections::BTreeMap, + ops::Range, + sync::{Arc, Mutex}, +}; +use tokio::task; + +const GENESIS_HASH: PHash = PHash::zero(); +const TEST_SESSION_INDEX: SessionIndex = 0; + +struct AvailabilityRecoverySubsystemHandle { + tx: mpsc::Sender, +} + +impl AvailabilityRecoverySubsystemHandle { + fn new() -> (Self, mpsc::Receiver) { + let (tx, rx) = mpsc::channel(10); + + (Self { tx }, rx) + } +} + +#[async_trait::async_trait] +impl RecoveryHandle for AvailabilityRecoverySubsystemHandle { + async fn send_recovery_msg( + &mut self, + message: AvailabilityRecoveryMessage, + _origin: &'static str, + ) { + self.tx.send(message).await.expect("Receiver dropped"); + } +} + +struct ParachainClientInner { + import_notifications_rx: Option>>, + finality_notifications_rx: Option>>, + usage_infos: Vec>, + block_statuses: Arc>>, +} + +impl ParachainClientInner { + fn new( + usage_infos: Vec>, + block_statuses: Arc>>, + ) -> ( + Self, + TracingUnboundedSender>, + TracingUnboundedSender>, + ) { + let (import_notifications_tx, import_notifications_rx) = + sc_utils::mpsc::tracing_unbounded("import_notif", 10); + let (finality_notifications_tx, finality_notifications_rx) = + sc_utils::mpsc::tracing_unbounded("finality_notif", 10); + ( + Self { + import_notifications_rx: Some(import_notifications_rx), + finality_notifications_rx: Some(finality_notifications_rx), + usage_infos, + block_statuses, + }, + import_notifications_tx, + finality_notifications_tx, + ) + } +} +struct ParachainClient { + inner: Arc>>, +} + +impl ParachainClient { + fn new( + usage_infos: Vec>, + block_statuses: Arc>>, + ) -> ( + Self, + TracingUnboundedSender>, + TracingUnboundedSender>, + ) { + let (inner, import_notifications_tx, finality_notifications_tx) = + ParachainClientInner::new(usage_infos, block_statuses); + ( + Self { inner: Arc::new(Mutex::new(inner)) }, + import_notifications_tx, + finality_notifications_tx, + ) + } +} + +impl BlockchainEvents for ParachainClient { + fn import_notification_stream(&self) -> ImportNotifications { + self.inner + .lock() + .expect("poisoned lock") + .import_notifications_rx + .take() + .expect("Should only be taken once") + } + + fn every_import_notification_stream(&self) -> ImportNotifications { + unimplemented!() + } + + fn finality_notification_stream(&self) -> FinalityNotifications { + self.inner + .lock() + .expect("poisoned lock") + .finality_notifications_rx + .take() + .expect("Should only be taken once") + } + + fn storage_changes_notification_stream( + &self, + _filter_keys: Option<&[StorageKey]>, + _child_filter_keys: Option<&[(StorageKey, Option>)]>, + ) -> sp_blockchain::Result> { + unimplemented!() + } +} + +impl BlockBackend for ParachainClient { + fn block_body( + &self, + _: Block::Hash, + ) -> sp_blockchain::Result::Extrinsic>>> { + unimplemented!() + } + + fn block(&self, _: Block::Hash) -> sp_blockchain::Result>> { + unimplemented!() + } + + fn block_status(&self, hash: Block::Hash) -> sp_blockchain::Result { + Ok(self + .inner + .lock() + .expect("Poisoned lock") + .block_statuses + .lock() + .expect("Poisoned lock") + .get(&hash) + .cloned() + .unwrap_or(BlockStatus::Unknown)) + } + + fn justifications(&self, _: Block::Hash) -> sp_blockchain::Result> { + unimplemented!() + } + + fn block_hash(&self, _: NumberFor) -> sp_blockchain::Result> { + unimplemented!() + } + + fn indexed_transaction(&self, _: Block::Hash) -> sp_blockchain::Result>> { + unimplemented!() + } + + fn has_indexed_transaction(&self, _: Block::Hash) -> sp_blockchain::Result { + unimplemented!() + } + + fn block_indexed_body(&self, _: Block::Hash) -> sp_blockchain::Result>>> { + unimplemented!() + } + + fn requires_full_sync(&self) -> bool { + unimplemented!() + } +} + +impl UsageProvider for ParachainClient { + fn usage_info(&self) -> ClientInfo { + let infos = &mut self.inner.lock().expect("Poisoned lock").usage_infos; + assert!(!infos.is_empty()); + + if infos.len() == 1 { + infos.last().unwrap().clone() + } else { + infos.remove(0) + } + } +} + +struct ParachainImportQueue { + import_requests_tx: TracingUnboundedSender>>, +} + +impl ParachainImportQueue { + fn new() -> (Self, TracingUnboundedReceiver>>) { + let (import_requests_tx, import_requests_rx) = + sc_utils::mpsc::tracing_unbounded("test_import_req_forwarding", 10); + (Self { import_requests_tx }, import_requests_rx) + } +} + +impl ImportQueueService for ParachainImportQueue { + fn import_blocks(&mut self, origin: BlockOrigin, blocks: Vec>) { + assert_matches!(origin, BlockOrigin::ConsensusBroadcast); + self.import_requests_tx.unbounded_send(blocks).unwrap(); + } + + fn import_justifications( + &mut self, + _: RuntimeOrigin, + _: Block::Hash, + _: NumberFor, + _: Justifications, + ) { + unimplemented!() + } +} + +#[derive(Default)] +struct DummySyncOracle { + is_major_syncing: bool, +} + +impl DummySyncOracle { + fn new(is_major_syncing: bool) -> Self { + Self { is_major_syncing } + } +} + +impl SyncOracle for DummySyncOracle { + fn is_major_syncing(&self) -> bool { + self.is_major_syncing + } + + fn is_offline(&self) -> bool { + false + } +} + +#[derive(Clone)] +struct RelaychainInner { + runtime_version: u32, + import_notifications: Vec, + candidates_pending_availability: HashMap>, +} + +#[derive(Clone)] +struct Relaychain { + inner: Arc>, +} + +impl Relaychain { + fn new(relay_chain_blocks: Vec<(PHeader, Vec)>) -> Self { + let (candidates_pending_availability, import_notifications) = relay_chain_blocks + .into_iter() + .map(|(header, receipt)| ((header.hash(), receipt), header)) + .unzip(); + Self { + inner: Arc::new(Mutex::new(RelaychainInner { + import_notifications, + candidates_pending_availability, + // The version that introduced candidates_pending_availability + runtime_version: + RuntimeApiRequest::CANDIDATES_PENDING_AVAILABILITY_RUNTIME_REQUIREMENT, + })), + } + } + + fn set_runtime_version(&self, version: u32) { + self.inner.lock().expect("Poisoned lock").runtime_version = version; + } +} + +#[async_trait::async_trait] +impl RelayChainInterface for Relaychain { + async fn version(&self, _: PHash) -> RelayChainResult { + let version = self.inner.lock().expect("Poisoned lock").runtime_version; + + let apis = sp_version::create_apis_vec!([( + >::ID, + version + )]) + .into_owned() + .to_vec(); + + Ok(RuntimeVersion { + spec_name: sp_version::create_runtime_str!("test"), + impl_name: sp_version::create_runtime_str!("test"), + authoring_version: 1, + spec_version: 1, + impl_version: 0, + apis: Cow::Owned(apis), + transaction_version: 5, + state_version: 1, + }) + } + + async fn validators(&self, _: PHash) -> RelayChainResult> { + unimplemented!("Not needed for test") + } + + async fn best_block_hash(&self) -> RelayChainResult { + unimplemented!("Not needed for test") + } + + async fn finalized_block_hash(&self) -> RelayChainResult { + unimplemented!("Not needed for test") + } + + async fn retrieve_dmq_contents( + &self, + _: ParaId, + _: PHash, + ) -> RelayChainResult> { + unimplemented!("Not needed for test") + } + + async fn retrieve_all_inbound_hrmp_channel_contents( + &self, + _: ParaId, + _: PHash, + ) -> RelayChainResult>> { + unimplemented!("Not needed for test") + } + + async fn persisted_validation_data( + &self, + _: PHash, + _: ParaId, + _: OccupiedCoreAssumption, + ) -> RelayChainResult> { + unimplemented!("Not needed for test") + } + + async fn validation_code_hash( + &self, + _: PHash, + _: ParaId, + _: OccupiedCoreAssumption, + ) -> RelayChainResult> { + unimplemented!("Not needed for test") + } + + async fn candidate_pending_availability( + &self, + hash: PHash, + _: ParaId, + ) -> RelayChainResult> { + if self.inner.lock().expect("Poisoned lock").runtime_version >= + RuntimeApiRequest::CANDIDATES_PENDING_AVAILABILITY_RUNTIME_REQUIREMENT + { + panic!("Should have used candidates_pending_availability instead"); + } + + Ok(self + .inner + .lock() + .expect("Poisoned lock") + .candidates_pending_availability + .remove(&hash) + .map(|mut c| { + assert_eq!(c.len(), 1); + c.pop().unwrap() + })) + } + + async fn candidates_pending_availability( + &self, + hash: PHash, + _: ParaId, + ) -> RelayChainResult> { + if self.inner.lock().expect("Poisoned lock").runtime_version < + RuntimeApiRequest::CANDIDATES_PENDING_AVAILABILITY_RUNTIME_REQUIREMENT + { + panic!("Should have used candidate_pending_availability instead"); + } + + Ok(self + .inner + .lock() + .expect("Poisoned lock") + .candidates_pending_availability + .remove(&hash) + .expect("Not found")) + } + + async fn session_index_for_child(&self, _: PHash) -> RelayChainResult { + Ok(TEST_SESSION_INDEX) + } + + async fn import_notification_stream( + &self, + ) -> RelayChainResult + Send>>> { + Ok(Box::pin( + futures::stream::iter(std::mem::take( + &mut self.inner.lock().expect("Poisoned lock").import_notifications, + )) + .chain(futures::stream::pending()), + )) + } + + async fn finality_notification_stream( + &self, + ) -> RelayChainResult + Send>>> { + unimplemented!("Not needed for test") + } + + async fn is_major_syncing(&self) -> RelayChainResult { + unimplemented!("Not needed for test"); + } + + fn overseer_handle(&self) -> RelayChainResult { + unimplemented!("Not needed for test") + } + + async fn get_storage_by_key( + &self, + _: PHash, + _: &[u8], + ) -> RelayChainResult> { + unimplemented!("Not needed for test") + } + + async fn prove_read( + &self, + _: PHash, + _: &Vec>, + ) -> RelayChainResult { + unimplemented!("Not needed for test") + } + + async fn wait_for_block(&self, _: PHash) -> RelayChainResult<()> { + unimplemented!("Not needed for test"); + } + + async fn new_best_notification_stream( + &self, + ) -> RelayChainResult + Send>>> { + unimplemented!("Not needed for test"); + } + + async fn header(&self, _: BlockId) -> RelayChainResult> { + unimplemented!("Not needed for test"); + } +} + +fn make_candidate_chain(candidate_number_range: Range) -> Vec { + let collator = Sr25519Keyring::Ferdie; + let mut latest_parent_hash = GENESIS_HASH; + let mut candidates = vec![]; + + for number in candidate_number_range { + let head_data = Header { + number, + digest: Default::default(), + extrinsics_root: Default::default(), + parent_hash: latest_parent_hash, + state_root: Default::default(), + }; + + latest_parent_hash = head_data.hash(); + + candidates.push(CommittedCandidateReceipt { + descriptor: CandidateDescriptor { + para_id: ParaId::from(1000), + relay_parent: PHash::zero(), + collator: collator.public().into(), + persisted_validation_data_hash: PHash::zero(), + pov_hash: PHash::zero(), + erasure_root: PHash::zero(), + signature: collator.sign(&[0u8; 132]).into(), + para_head: PHash::zero(), + validation_code_hash: PHash::zero().into(), + }, + commitments: CandidateCommitments { + head_data: head_data.encode().into(), + upward_messages: vec![].try_into().expect("empty vec fits within bounds"), + new_validation_code: None, + horizontal_messages: vec![].try_into().expect("empty vec fits within bounds"), + processed_downward_messages: 0, + hrmp_watermark: 0_u32, + }, + }); + } + + candidates +} + +fn dummy_usage_info(finalized_number: u32) -> ClientInfo { + ClientInfo { + chain: Info { + best_hash: PHash::zero(), + best_number: 0, + genesis_hash: PHash::zero(), + finalized_hash: PHash::zero(), + // Only this field is being used. + finalized_number, + finalized_state: None, + number_leaves: 0, + block_gap: None, + }, + usage: None, + } +} + +fn dummy_pvd() -> PersistedValidationData { + PersistedValidationData { + parent_head: vec![].into(), + relay_parent_number: 1, + relay_parent_storage_root: PHash::zero(), + max_pov_size: 100, + } +} + +#[tokio::test] +async fn pending_candidate_height_lower_than_latest_finalized() { + sp_tracing::init_for_tests(); + + for finalized_number in [3, 4, 5] { + let (recovery_subsystem_tx, mut recovery_subsystem_rx) = + AvailabilityRecoverySubsystemHandle::new(); + let recovery_delay_range = + RecoveryDelayRange { min: Duration::from_millis(0), max: Duration::from_millis(10) }; + let (_explicit_recovery_chan_tx, explicit_recovery_chan_rx) = mpsc::channel(10); + let candidates = make_candidate_chain(1..4); + let relay_chain_client = Relaychain::new(vec![( + PHeader { + parent_hash: PHash::from_low_u64_be(0), + number: 1, + state_root: PHash::random(), + extrinsics_root: PHash::random(), + digest: Default::default(), + }, + candidates, + )]); + let (parachain_client, _import_notifications_tx, _finality_notifications_tx) = + ParachainClient::new(vec![dummy_usage_info(finalized_number)], Default::default()); + let (parachain_import_queue, mut import_requests_rx) = ParachainImportQueue::new(); + + // If the latest finalized block has a larger height compared to the pending candidate, the + // new candidate won't be recovered. Candidates have heights is 1, 2 and 3. Latest finalized + // block is 3, 4 or 5. + let pov_recovery = PoVRecovery::::new( + Box::new(recovery_subsystem_tx), + recovery_delay_range, + Arc::new(parachain_client), + Box::new(parachain_import_queue), + relay_chain_client, + ParaId::new(1000), + explicit_recovery_chan_rx, + Arc::new(DummySyncOracle::default()), + ); + + task::spawn(pov_recovery.run()); + + // No recovery message received + assert_matches!( + recovery_subsystem_rx.next().timeout(Duration::from_millis(100)).await, + None + ); + + // No import request received + assert_matches!(import_requests_rx.next().timeout(Duration::from_millis(100)).await, None); + } +} + +#[rstest] +#[case(RuntimeApiRequest::CANDIDATES_PENDING_AVAILABILITY_RUNTIME_REQUIREMENT)] +#[case(10)] +#[tokio::test] +async fn single_pending_candidate_recovery_success(#[case] runtime_version: u32) { + sp_tracing::init_for_tests(); + + let (recovery_subsystem_tx, mut recovery_subsystem_rx) = + AvailabilityRecoverySubsystemHandle::new(); + let recovery_delay_range = + RecoveryDelayRange { min: Duration::from_millis(0), max: Duration::from_millis(10) }; + let (_explicit_recovery_chan_tx, explicit_recovery_chan_rx) = mpsc::channel(10); + let candidates = make_candidate_chain(1..2); + let header = Header::decode(&mut &candidates[0].commitments.head_data.0[..]).unwrap(); + let candidate_hash = candidates[0].hash(); + + let relay_chain_client = Relaychain::new(vec![( + PHeader { + parent_hash: PHash::from_low_u64_be(0), + number: 1, + state_root: PHash::random(), + extrinsics_root: PHash::random(), + digest: Default::default(), + }, + candidates, + )]); + relay_chain_client.set_runtime_version(runtime_version); + + let mut known_blocks = HashMap::new(); + known_blocks.insert(GENESIS_HASH, BlockStatus::InChainWithState); + let (parachain_client, _import_notifications_tx, _finality_notifications_tx) = + ParachainClient::new(vec![dummy_usage_info(0)], Arc::new(Mutex::new(known_blocks))); + let (parachain_import_queue, mut import_requests_rx) = ParachainImportQueue::new(); + + let pov_recovery = PoVRecovery::::new( + Box::new(recovery_subsystem_tx), + recovery_delay_range, + Arc::new(parachain_client), + Box::new(parachain_import_queue), + relay_chain_client, + ParaId::new(1000), + explicit_recovery_chan_rx, + Arc::new(DummySyncOracle::default()), + ); + + task::spawn(pov_recovery.run()); + + assert_matches!( + recovery_subsystem_rx.next().await, + Some(AvailabilityRecoveryMessage::RecoverAvailableData( + receipt, + session_index, + None, + None, + response_tx + )) => { + assert_eq!(receipt.hash(), candidate_hash); + assert_eq!(session_index, TEST_SESSION_INDEX); + response_tx.send( + Ok( + AvailableData { + pov: Arc::new(PoV { + block_data: ParachainBlockData::::new( + header.clone(), + vec![], + CompactProof {encoded_nodes: vec![]} + ).encode().into() + }), + validation_data: dummy_pvd(), + } + ) + ).unwrap() + } + ); + + // No more recovery messages received. + assert_matches!(recovery_subsystem_rx.next().timeout(Duration::from_millis(100)).await, None); + + // Received import request for the recovered candidate + assert_matches!(import_requests_rx.next().await, Some(incoming_blocks) => { + assert_eq!(incoming_blocks.len(), 1); + assert_eq!(incoming_blocks[0].header, Some(header)); + }); + + // No import request received + assert_matches!(import_requests_rx.next().timeout(Duration::from_millis(100)).await, None); +} + +#[tokio::test] +async fn single_pending_candidate_recovery_retry_succeeds() { + sp_tracing::init_for_tests(); + + let (recovery_subsystem_tx, mut recovery_subsystem_rx) = + AvailabilityRecoverySubsystemHandle::new(); + let recovery_delay_range = + RecoveryDelayRange { min: Duration::from_millis(0), max: Duration::from_millis(10) }; + let (_explicit_recovery_chan_tx, explicit_recovery_chan_rx) = mpsc::channel(10); + let candidates = make_candidate_chain(1..2); + let header = Header::decode(&mut &candidates[0].commitments.head_data.0[..]).unwrap(); + let candidate_hash = candidates[0].hash(); + + let relay_chain_client = Relaychain::new(vec![( + PHeader { + parent_hash: PHash::from_low_u64_be(0), + number: 1, + state_root: PHash::random(), + extrinsics_root: PHash::random(), + digest: Default::default(), + }, + candidates, + )]); + let mut known_blocks = HashMap::new(); + known_blocks.insert(GENESIS_HASH, BlockStatus::InChainWithState); + let (parachain_client, _import_notifications_tx, _finality_notifications_tx) = + ParachainClient::new(vec![dummy_usage_info(0)], Arc::new(Mutex::new(known_blocks))); + let (parachain_import_queue, mut import_requests_rx) = ParachainImportQueue::new(); + + let pov_recovery = PoVRecovery::::new( + Box::new(recovery_subsystem_tx), + recovery_delay_range, + Arc::new(parachain_client), + Box::new(parachain_import_queue), + relay_chain_client, + ParaId::new(1000), + explicit_recovery_chan_rx, + Arc::new(DummySyncOracle::default()), + ); + + task::spawn(pov_recovery.run()); + + // First recovery fails. + assert_matches!( + recovery_subsystem_rx.next().await, + Some(AvailabilityRecoveryMessage::RecoverAvailableData( + receipt, + session_index, + None, + None, + response_tx + )) => { + assert_eq!(receipt.hash(), candidate_hash); + assert_eq!(session_index, TEST_SESSION_INDEX); + response_tx.send( + Err(RecoveryError::Unavailable) + ).unwrap() + } + ); + // Candidate is not imported. + assert_matches!(import_requests_rx.next().timeout(Duration::from_millis(100)).await, None); + + // Recovery is retried and it succeeds now. + assert_matches!( + recovery_subsystem_rx.next().await, + Some(AvailabilityRecoveryMessage::RecoverAvailableData( + receipt, + session_index, + None, + None, + response_tx + )) => { + assert_eq!(receipt.hash(), candidate_hash); + assert_eq!(session_index, TEST_SESSION_INDEX); + response_tx.send( + Ok( + AvailableData { + pov: Arc::new(PoV { + block_data: ParachainBlockData::::new( + header.clone(), + vec![], + CompactProof {encoded_nodes: vec![]} + ).encode().into() + }), + validation_data: dummy_pvd(), + } + ) + ).unwrap() + } + ); + + // No more recovery messages received. + assert_matches!(recovery_subsystem_rx.next().timeout(Duration::from_millis(100)).await, None); + + // Received import request for the recovered candidate + assert_matches!(import_requests_rx.next().await, Some(incoming_blocks) => { + assert_eq!(incoming_blocks.len(), 1); + assert_eq!(incoming_blocks[0].header, Some(header)); + }); + + // No import request received + assert_matches!(import_requests_rx.next().timeout(Duration::from_millis(100)).await, None); +} + +#[tokio::test] +async fn single_pending_candidate_recovery_retry_fails() { + sp_tracing::init_for_tests(); + + let (recovery_subsystem_tx, mut recovery_subsystem_rx) = + AvailabilityRecoverySubsystemHandle::new(); + let recovery_delay_range = + RecoveryDelayRange { min: Duration::from_millis(0), max: Duration::from_millis(10) }; + let (_explicit_recovery_chan_tx, explicit_recovery_chan_rx) = mpsc::channel(10); + let candidates = make_candidate_chain(1..2); + let candidate_hash = candidates[0].hash(); + + let relay_chain_client = Relaychain::new(vec![( + PHeader { + parent_hash: PHash::from_low_u64_be(0), + number: 1, + state_root: PHash::random(), + extrinsics_root: PHash::random(), + digest: Default::default(), + }, + candidates, + )]); + let mut known_blocks = HashMap::new(); + known_blocks.insert(GENESIS_HASH, BlockStatus::InChainWithState); + let (parachain_client, _import_notifications_tx, _finality_notifications_tx) = + ParachainClient::new(vec![dummy_usage_info(0)], Arc::new(Mutex::new(known_blocks))); + let (parachain_import_queue, mut import_requests_rx) = ParachainImportQueue::new(); + + let pov_recovery = PoVRecovery::::new( + Box::new(recovery_subsystem_tx), + recovery_delay_range, + Arc::new(parachain_client), + Box::new(parachain_import_queue), + relay_chain_client, + ParaId::new(1000), + explicit_recovery_chan_rx, + Arc::new(DummySyncOracle::default()), + ); + + task::spawn(pov_recovery.run()); + + // First recovery fails. + assert_matches!( + recovery_subsystem_rx.next().await, + Some(AvailabilityRecoveryMessage::RecoverAvailableData( + receipt, + session_index, + None, + None, + response_tx + )) => { + assert_eq!(receipt.hash(), candidate_hash); + assert_eq!(session_index, TEST_SESSION_INDEX); + response_tx.send( + Err(RecoveryError::Unavailable) + ).unwrap() + } + ); + // Candidate is not imported. + assert_matches!(import_requests_rx.next().timeout(Duration::from_millis(100)).await, None); + + // Second retry fails. + assert_matches!( + recovery_subsystem_rx.next().await, + Some(AvailabilityRecoveryMessage::RecoverAvailableData( + receipt, + session_index, + None, + None, + response_tx + )) => { + assert_eq!(receipt.hash(), candidate_hash); + assert_eq!(session_index, TEST_SESSION_INDEX); + response_tx.send( + Err(RecoveryError::Unavailable) + ).unwrap() + } + ); + // Candidate is not imported. + assert_matches!(import_requests_rx.next().timeout(Duration::from_millis(100)).await, None); + + // After the second attempt, give up. + // No more recovery messages received. + assert_matches!(recovery_subsystem_rx.next().timeout(Duration::from_millis(100)).await, None); +} + +#[tokio::test] +async fn single_pending_candidate_recovery_irrecoverable_error() { + sp_tracing::init_for_tests(); + + let (recovery_subsystem_tx, mut recovery_subsystem_rx) = + AvailabilityRecoverySubsystemHandle::new(); + let recovery_delay_range = + RecoveryDelayRange { min: Duration::from_millis(0), max: Duration::from_millis(10) }; + let (_explicit_recovery_chan_tx, explicit_recovery_chan_rx) = mpsc::channel(10); + let candidates = make_candidate_chain(1..2); + let candidate_hash = candidates[0].hash(); + + let relay_chain_client = Relaychain::new(vec![( + PHeader { + parent_hash: PHash::from_low_u64_be(0), + number: 1, + state_root: PHash::random(), + extrinsics_root: PHash::random(), + digest: Default::default(), + }, + candidates, + )]); + let mut known_blocks = HashMap::new(); + known_blocks.insert(GENESIS_HASH, BlockStatus::InChainWithState); + let (parachain_client, _import_notifications_tx, _finality_notifications_tx) = + ParachainClient::new(vec![dummy_usage_info(0)], Arc::new(Mutex::new(known_blocks))); + let (parachain_import_queue, mut import_requests_rx) = ParachainImportQueue::new(); + + let pov_recovery = PoVRecovery::::new( + Box::new(recovery_subsystem_tx), + recovery_delay_range, + Arc::new(parachain_client), + Box::new(parachain_import_queue), + relay_chain_client, + ParaId::new(1000), + explicit_recovery_chan_rx, + Arc::new(DummySyncOracle::default()), + ); + + task::spawn(pov_recovery.run()); + + // Recovery succeeds but the block data is wrong. Will not be retried. + assert_matches!( + recovery_subsystem_rx.next().await, + Some(AvailabilityRecoveryMessage::RecoverAvailableData( + receipt, + session_index, + None, + None, + response_tx + )) => { + assert_eq!(receipt.hash(), candidate_hash); + assert_eq!(session_index, TEST_SESSION_INDEX); + response_tx.send( + Ok( + AvailableData { + pov: Arc::new(PoV { + // Empty block data. It will fail to decode. + block_data: vec![].into() + }), + validation_data: dummy_pvd(), + } + ) + ).unwrap() + } + ); + // Candidate is not imported. + assert_matches!(import_requests_rx.next().timeout(Duration::from_millis(100)).await, None); + + // No more recovery messages received. + assert_matches!(recovery_subsystem_rx.next().timeout(Duration::from_millis(100)).await, None); +} + +#[tokio::test] +async fn pending_candidates_recovery_skipped_while_syncing() { + sp_tracing::init_for_tests(); + + let (recovery_subsystem_tx, mut recovery_subsystem_rx) = + AvailabilityRecoverySubsystemHandle::new(); + let recovery_delay_range = + RecoveryDelayRange { min: Duration::from_millis(0), max: Duration::from_millis(10) }; + let (_explicit_recovery_chan_tx, explicit_recovery_chan_rx) = mpsc::channel(10); + let candidates = make_candidate_chain(1..4); + + let relay_chain_client = Relaychain::new(vec![( + PHeader { + parent_hash: PHash::from_low_u64_be(0), + number: 1, + state_root: PHash::random(), + extrinsics_root: PHash::random(), + digest: Default::default(), + }, + candidates, + )]); + let mut known_blocks = HashMap::new(); + known_blocks.insert(GENESIS_HASH, BlockStatus::InChainWithState); + let (parachain_client, _import_notifications_tx, _finality_notifications_tx) = + ParachainClient::new(vec![dummy_usage_info(0)], Arc::new(Mutex::new(known_blocks))); + let (parachain_import_queue, mut import_requests_rx) = ParachainImportQueue::new(); + + let pov_recovery = PoVRecovery::::new( + Box::new(recovery_subsystem_tx), + recovery_delay_range, + Arc::new(parachain_client), + Box::new(parachain_import_queue), + relay_chain_client, + ParaId::new(1000), + explicit_recovery_chan_rx, + Arc::new(DummySyncOracle::new(true)), + ); + + task::spawn(pov_recovery.run()); + + // No recovery messages received. + assert_matches!(recovery_subsystem_rx.next().timeout(Duration::from_millis(100)).await, None); + + // No candidate is imported. + assert_matches!(import_requests_rx.next().timeout(Duration::from_millis(100)).await, None); +} + +#[tokio::test] +async fn candidate_is_imported_while_awaiting_recovery() { + sp_tracing::init_for_tests(); + + let (recovery_subsystem_tx, mut recovery_subsystem_rx) = + AvailabilityRecoverySubsystemHandle::new(); + let recovery_delay_range = + RecoveryDelayRange { min: Duration::from_millis(0), max: Duration::from_millis(10) }; + let (_explicit_recovery_chan_tx, explicit_recovery_chan_rx) = mpsc::channel(10); + let candidates = make_candidate_chain(1..2); + let header = Header::decode(&mut &candidates[0].commitments.head_data.0[..]).unwrap(); + let candidate_hash = candidates[0].hash(); + + let relay_chain_client = Relaychain::new(vec![( + PHeader { + parent_hash: PHash::from_low_u64_be(0), + number: 1, + state_root: PHash::random(), + extrinsics_root: PHash::random(), + digest: Default::default(), + }, + candidates, + )]); + let mut known_blocks = HashMap::new(); + known_blocks.insert(GENESIS_HASH, BlockStatus::InChainWithState); + let (parachain_client, import_notifications_tx, _finality_notifications_tx) = + ParachainClient::new(vec![dummy_usage_info(0)], Arc::new(Mutex::new(known_blocks))); + let (parachain_import_queue, mut import_requests_rx) = ParachainImportQueue::new(); + + let pov_recovery = PoVRecovery::::new( + Box::new(recovery_subsystem_tx), + recovery_delay_range, + Arc::new(parachain_client), + Box::new(parachain_import_queue), + relay_chain_client, + ParaId::new(1000), + explicit_recovery_chan_rx, + Arc::new(DummySyncOracle::default()), + ); + + task::spawn(pov_recovery.run()); + + let recovery_response_tx; + + assert_matches!( + recovery_subsystem_rx.next().await, + Some(AvailabilityRecoveryMessage::RecoverAvailableData( + receipt, + session_index, + None, + None, + response_tx + )) => { + assert_eq!(receipt.hash(), candidate_hash); + assert_eq!(session_index, TEST_SESSION_INDEX); + recovery_response_tx = response_tx; + } + ); + + // While candidate is pending recovery, import the candidate from external source. + let (unpin_sender, _unpin_receiver) = sc_utils::mpsc::tracing_unbounded("test_unpin", 10); + import_notifications_tx + .unbounded_send(BlockImportNotification::new( + header.hash(), + BlockOrigin::ConsensusBroadcast, + header.clone(), + false, + None, + unpin_sender, + )) + .unwrap(); + + recovery_response_tx + .send(Ok(AvailableData { + pov: Arc::new(PoV { + block_data: ParachainBlockData::::new( + header.clone(), + vec![], + CompactProof { encoded_nodes: vec![] }, + ) + .encode() + .into(), + }), + validation_data: dummy_pvd(), + })) + .unwrap(); + + // Received import request for the recovered candidate. This could be optimised to not trigger a + // reimport. + assert_matches!(import_requests_rx.next().await, Some(incoming_blocks) => { + assert_eq!(incoming_blocks.len(), 1); + assert_eq!(incoming_blocks[0].header, Some(header)); + }); + + // No more recovery messages received. + assert_matches!(recovery_subsystem_rx.next().timeout(Duration::from_millis(100)).await, None); + + // No more import requests received + assert_matches!(import_requests_rx.next().timeout(Duration::from_millis(100)).await, None); +} + +#[tokio::test] +async fn candidate_is_finalized_while_awaiting_recovery() { + sp_tracing::init_for_tests(); + + let (recovery_subsystem_tx, mut recovery_subsystem_rx) = + AvailabilityRecoverySubsystemHandle::new(); + let recovery_delay_range = + RecoveryDelayRange { min: Duration::from_millis(0), max: Duration::from_millis(10) }; + let (_explicit_recovery_chan_tx, explicit_recovery_chan_rx) = mpsc::channel(10); + let candidates = make_candidate_chain(1..2); + let header = Header::decode(&mut &candidates[0].commitments.head_data.0[..]).unwrap(); + let candidate_hash = candidates[0].hash(); + + let relay_chain_client = Relaychain::new(vec![( + PHeader { + parent_hash: PHash::from_low_u64_be(0), + number: 1, + state_root: PHash::random(), + extrinsics_root: PHash::random(), + digest: Default::default(), + }, + candidates, + )]); + let mut known_blocks = HashMap::new(); + known_blocks.insert(GENESIS_HASH, BlockStatus::InChainWithState); + let (parachain_client, _import_notifications_tx, finality_notifications_tx) = + ParachainClient::new(vec![dummy_usage_info(0)], Arc::new(Mutex::new(known_blocks))); + let (parachain_import_queue, mut import_requests_rx) = ParachainImportQueue::new(); + + let pov_recovery = PoVRecovery::::new( + Box::new(recovery_subsystem_tx), + recovery_delay_range, + Arc::new(parachain_client), + Box::new(parachain_import_queue), + relay_chain_client, + ParaId::new(1000), + explicit_recovery_chan_rx, + Arc::new(DummySyncOracle::default()), + ); + + task::spawn(pov_recovery.run()); + + let recovery_response_tx; + + assert_matches!( + recovery_subsystem_rx.next().await, + Some(AvailabilityRecoveryMessage::RecoverAvailableData( + receipt, + session_index, + None, + None, + response_tx + )) => { + assert_eq!(receipt.hash(), candidate_hash); + assert_eq!(session_index, TEST_SESSION_INDEX); + // save it for later. + recovery_response_tx = response_tx; + } + ); + + // While candidate is pending recovery, it gets finalized. + let (unpin_sender, _unpin_receiver) = sc_utils::mpsc::tracing_unbounded("test_unpin", 10); + finality_notifications_tx + .unbounded_send(FinalityNotification::from_summary( + FinalizeSummary { header: header.clone(), finalized: vec![], stale_heads: vec![] }, + unpin_sender, + )) + .unwrap(); + + recovery_response_tx + .send(Ok(AvailableData { + pov: Arc::new(PoV { + block_data: ParachainBlockData::::new( + header.clone(), + vec![], + CompactProof { encoded_nodes: vec![] }, + ) + .encode() + .into(), + }), + validation_data: dummy_pvd(), + })) + .unwrap(); + + // No more recovery messages received. + assert_matches!(recovery_subsystem_rx.next().timeout(Duration::from_millis(100)).await, None); + + // candidate is imported + assert_matches!(import_requests_rx.next().await, Some(incoming_blocks) => { + assert_eq!(incoming_blocks.len(), 1); + assert_eq!(incoming_blocks[0].header, Some(header)); + }); + + // No more import requests received + assert_matches!(import_requests_rx.next().timeout(Duration::from_millis(100)).await, None); +} + +#[tokio::test] +async fn chained_recovery_success() { + sp_tracing::init_for_tests(); + + let (recovery_subsystem_tx, mut recovery_subsystem_rx) = + AvailabilityRecoverySubsystemHandle::new(); + let recovery_delay_range = + RecoveryDelayRange { min: Duration::from_millis(0), max: Duration::from_millis(0) }; + let (_explicit_recovery_chan_tx, explicit_recovery_chan_rx) = mpsc::channel(10); + let candidates = make_candidate_chain(1..4); + let headers = candidates + .iter() + .map(|candidate| Header::decode(&mut &candidate.commitments.head_data.0[..]).unwrap()) + .collect::>(); + let candidate_hashes = candidates.iter().map(|candidate| candidate.hash()).collect::>(); + + let relay_chain_client = Relaychain::new(vec![( + PHeader { + parent_hash: PHash::from_low_u64_be(0), + number: 1, + state_root: PHash::random(), + extrinsics_root: PHash::random(), + digest: Default::default(), + }, + // 3 pending candidates + candidates, + )]); + let mut known_blocks = HashMap::new(); + known_blocks.insert(GENESIS_HASH, BlockStatus::InChainWithState); + let known_blocks = Arc::new(Mutex::new(known_blocks)); + let (parachain_client, import_notifications_tx, _finality_notifications_tx) = + ParachainClient::new(vec![dummy_usage_info(0)], known_blocks.clone()); + let (parachain_import_queue, mut import_requests_rx) = ParachainImportQueue::new(); + + let pov_recovery = PoVRecovery::::new( + Box::new(recovery_subsystem_tx), + recovery_delay_range, + Arc::new(parachain_client), + Box::new(parachain_import_queue), + relay_chain_client, + ParaId::new(1000), + explicit_recovery_chan_rx, + Arc::new(DummySyncOracle::default()), + ); + + task::spawn(pov_recovery.run()); + + // Candidates are recovered in the right order. + for (candidate_hash, header) in candidate_hashes.into_iter().zip(headers.into_iter()) { + assert_matches!( + recovery_subsystem_rx.next().await, + Some(AvailabilityRecoveryMessage::RecoverAvailableData( + receipt, + session_index, + None, + None, + response_tx + )) => { + assert_eq!(receipt.hash(), candidate_hash); + assert_eq!(session_index, TEST_SESSION_INDEX); + response_tx + .send(Ok(AvailableData { + pov: Arc::new(PoV { + block_data: ParachainBlockData::::new( + header.clone(), + vec![], + CompactProof { encoded_nodes: vec![] }, + ) + .encode() + .into(), + }), + validation_data: dummy_pvd(), + })) + .unwrap(); + } + ); + + assert_matches!(import_requests_rx.next().await, Some(incoming_blocks) => { + assert_eq!(incoming_blocks.len(), 1); + assert_eq!(incoming_blocks[0].header, Some(header.clone())); + }); + + known_blocks + .lock() + .expect("Poisoned lock") + .insert(header.hash(), BlockStatus::InChainWithState); + + let (unpin_sender, _unpin_receiver) = sc_utils::mpsc::tracing_unbounded("test_unpin", 10); + import_notifications_tx + .unbounded_send(BlockImportNotification::new( + header.hash(), + BlockOrigin::ConsensusBroadcast, + header, + false, + None, + unpin_sender, + )) + .unwrap(); + } + + // No more recovery messages received. + assert_matches!(recovery_subsystem_rx.next().timeout(Duration::from_millis(100)).await, None); + + // No more import requests received + assert_matches!(import_requests_rx.next().timeout(Duration::from_millis(100)).await, None); +} + +#[tokio::test] +async fn chained_recovery_child_succeeds_before_parent() { + sp_tracing::init_for_tests(); + + let (recovery_subsystem_tx, mut recovery_subsystem_rx) = + AvailabilityRecoverySubsystemHandle::new(); + let recovery_delay_range = + RecoveryDelayRange { min: Duration::from_millis(0), max: Duration::from_millis(0) }; + let (_explicit_recovery_chan_tx, explicit_recovery_chan_rx) = mpsc::channel(10); + let candidates = make_candidate_chain(1..3); + let headers = candidates + .iter() + .map(|candidate| Header::decode(&mut &candidate.commitments.head_data.0[..]).unwrap()) + .collect::>(); + let candidate_hashes = candidates.iter().map(|candidate| candidate.hash()).collect::>(); + + let relay_chain_client = Relaychain::new(vec![( + PHeader { + parent_hash: PHash::from_low_u64_be(0), + number: 1, + state_root: PHash::random(), + extrinsics_root: PHash::random(), + digest: Default::default(), + }, + // 2 pending candidates + candidates, + )]); + let mut known_blocks = HashMap::new(); + known_blocks.insert(GENESIS_HASH, BlockStatus::InChainWithState); + let known_blocks = Arc::new(Mutex::new(known_blocks)); + let (parachain_client, _import_notifications_tx, _finality_notifications_tx) = + ParachainClient::new(vec![dummy_usage_info(0)], known_blocks.clone()); + let (parachain_import_queue, mut import_requests_rx) = ParachainImportQueue::new(); + + let pov_recovery = PoVRecovery::::new( + Box::new(recovery_subsystem_tx), + recovery_delay_range, + Arc::new(parachain_client), + Box::new(parachain_import_queue), + relay_chain_client, + ParaId::new(1000), + explicit_recovery_chan_rx, + Arc::new(DummySyncOracle::default()), + ); + + task::spawn(pov_recovery.run()); + + let mut recovery_responses_senders = vec![]; + + for candidate_hash in candidate_hashes.iter() { + assert_matches!( + recovery_subsystem_rx.next().await, + Some(AvailabilityRecoveryMessage::RecoverAvailableData( + receipt, + session_index, + None, + None, + response_tx + )) => { + assert_eq!(receipt.hash(), *candidate_hash); + assert_eq!(session_index, TEST_SESSION_INDEX); + recovery_responses_senders.push(response_tx); + } + ); + } + + // Send out the responses in reverse order. + for (recovery_response_sender, header) in + recovery_responses_senders.into_iter().zip(headers.iter()).rev() + { + recovery_response_sender + .send(Ok(AvailableData { + pov: Arc::new(PoV { + block_data: ParachainBlockData::::new( + header.clone(), + vec![], + CompactProof { encoded_nodes: vec![] }, + ) + .encode() + .into(), + }), + validation_data: dummy_pvd(), + })) + .unwrap(); + } + + assert_matches!(import_requests_rx.next().await, Some(incoming_blocks) => { + // The two import requests will be batched. + assert_eq!(incoming_blocks.len(), 2); + assert_eq!(incoming_blocks[0].header, Some(headers[0].clone())); + assert_eq!(incoming_blocks[1].header, Some(headers[1].clone())); + }); + + // No more recovery messages received. + assert_matches!(recovery_subsystem_rx.next().timeout(Duration::from_millis(100)).await, None); + + // No more import requests received + assert_matches!(import_requests_rx.next().timeout(Duration::from_millis(100)).await, None); +} diff --git a/cumulus/client/relay-chain-inprocess-interface/Cargo.toml b/cumulus/client/relay-chain-inprocess-interface/Cargo.toml index 7629b6c631a3a0195760eee7fd39e754c289dd3e..6f1b74191be79a3c90100a18df1b20b850e0f4b2 100644 --- a/cumulus/client/relay-chain-inprocess-interface/Cargo.toml +++ b/cumulus/client/relay-chain-inprocess-interface/Cargo.toml @@ -10,39 +10,39 @@ license = "GPL-3.0-or-later WITH Classpath-exception-2.0" workspace = true [dependencies] -async-trait = "0.1.79" -futures = "0.3.28" -futures-timer = "3.0.2" +async-trait = { workspace = true } +futures = { workspace = true } +futures-timer = { workspace = true } # Substrate -sc-cli = { path = "../../../substrate/client/cli" } -sc-client-api = { path = "../../../substrate/client/api" } -sc-telemetry = { path = "../../../substrate/client/telemetry" } -sc-tracing = { path = "../../../substrate/client/tracing" } -sc-sysinfo = { path = "../../../substrate/client/sysinfo" } -sp-api = { path = "../../../substrate/primitives/api" } -sp-consensus = { path = "../../../substrate/primitives/consensus/common" } -sp-core = { path = "../../../substrate/primitives/core" } -sp-runtime = { path = "../../../substrate/primitives/runtime" } -sp-state-machine = { path = "../../../substrate/primitives/state-machine" } +sc-cli = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-telemetry = { workspace = true, default-features = true } +sc-tracing = { workspace = true, default-features = true } +sc-sysinfo = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-state-machine = { workspace = true, default-features = true } # Polkadot -polkadot-cli = { path = "../../../polkadot/cli", default-features = false, features = ["cli"] } -polkadot-service = { path = "../../../polkadot/node/service" } +polkadot-cli = { features = ["cli"], workspace = true } +polkadot-service = { workspace = true, default-features = true } # Cumulus -cumulus-primitives-core = { path = "../../primitives/core" } -cumulus-relay-chain-interface = { path = "../relay-chain-interface" } +cumulus-primitives-core = { workspace = true, default-features = true } +cumulus-relay-chain-interface = { workspace = true, default-features = true } [dev-dependencies] # Substrate -sp-keyring = { path = "../../../substrate/primitives/keyring" } +sp-keyring = { workspace = true, default-features = true } # Polkadot -polkadot-primitives = { path = "../../../polkadot/primitives" } -polkadot-test-client = { path = "../../../polkadot/node/test/client" } -metered = { package = "prioritized-metered-channel", version = "0.6.1", default-features = false, features = ["futures_channel"] } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-test-client = { workspace = true } +metered = { features = ["futures_channel"], workspace = true } # Cumulus -cumulus-test-service = { path = "../../test/service" } +cumulus-test-service = { workspace = true } diff --git a/cumulus/client/relay-chain-inprocess-interface/src/lib.rs b/cumulus/client/relay-chain-inprocess-interface/src/lib.rs index 578b942776dcde99553e0a5af513b03acb3a80a1..7871623e8447a2645ef772a495d7f698660f7dc5 100644 --- a/cumulus/client/relay-chain-inprocess-interface/src/lib.rs +++ b/cumulus/client/relay-chain-inprocess-interface/src/lib.rs @@ -30,7 +30,7 @@ use futures::{FutureExt, Stream, StreamExt}; use polkadot_service::{ CollatorPair, Configuration, FullBackend, FullClient, Handle, NewFull, TaskManager, }; -use sc_cli::SubstrateCli; +use sc_cli::{RuntimeVersion, SubstrateCli}; use sc_client_api::{ blockchain::BlockStatus, Backend, BlockchainEvents, HeaderBackend, ImportNotifications, StorageProof, @@ -68,6 +68,10 @@ impl RelayChainInProcessInterface { #[async_trait] impl RelayChainInterface for RelayChainInProcessInterface { + async fn version(&self, relay_parent: PHash) -> RelayChainResult { + Ok(self.full_client.runtime_version_at(relay_parent)?) + } + async fn retrieve_dmq_contents( &self, para_id: ParaId, @@ -251,6 +255,14 @@ impl RelayChainInterface for RelayChainInProcessInterface { }); Ok(Box::pin(notifications_stream)) } + + async fn candidates_pending_availability( + &self, + hash: PHash, + para_id: ParaId, + ) -> RelayChainResult> { + Ok(self.full_client.runtime_api().candidates_pending_availability(hash, para_id)?) + } } pub enum BlockCheckStatus { diff --git a/cumulus/client/relay-chain-interface/Cargo.toml b/cumulus/client/relay-chain-interface/Cargo.toml index 5d612cdc0eef571b977dca8e907a02e8f9d876b1..a496fab050dd7fc3cba69c8a6812c5f07b27a6d4 100644 --- a/cumulus/client/relay-chain-interface/Cargo.toml +++ b/cumulus/client/relay-chain-interface/Cargo.toml @@ -10,17 +10,18 @@ license = "GPL-3.0-or-later WITH Classpath-exception-2.0" workspace = true [dependencies] -polkadot-overseer = { path = "../../../polkadot/node/overseer" } +polkadot-overseer = { workspace = true, default-features = true } -cumulus-primitives-core = { path = "../../primitives/core" } +cumulus-primitives-core = { workspace = true, default-features = true } -sp-api = { path = "../../../substrate/primitives/api" } -sp-blockchain = { path = "../../../substrate/primitives/blockchain" } -sp-state-machine = { path = "../../../substrate/primitives/state-machine" } -sc-client-api = { path = "../../../substrate/client/api" } +sp-api = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-state-machine = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sp-version = { workspace = true } -futures = "0.3.28" -async-trait = "0.1.79" +futures = { workspace = true } +async-trait = { workspace = true } thiserror = { workspace = true } -jsonrpsee-core = "0.22" -codec = { package = "parity-scale-codec", version = "3.6.12" } +jsonrpsee-core = { workspace = true } +codec = { workspace = true, default-features = true } diff --git a/cumulus/client/relay-chain-interface/src/lib.rs b/cumulus/client/relay-chain-interface/src/lib.rs index 7c7796b468c0a6f458eceded955d47e7ac8cbbf6..46e19b40f010cce4342f54cbe08e975a52fee185 100644 --- a/cumulus/client/relay-chain-interface/src/lib.rs +++ b/cumulus/client/relay-chain-interface/src/lib.rs @@ -16,10 +16,10 @@ use std::{collections::BTreeMap, pin::Pin, sync::Arc}; +use futures::Stream; use polkadot_overseer::prometheus::PrometheusError; use sc_client_api::StorageProof; - -use futures::Stream; +use sp_version::RuntimeVersion; use async_trait::async_trait; use codec::Error as CodecError; @@ -149,8 +149,12 @@ pub trait RelayChainInterface: Send + Sync { _: OccupiedCoreAssumption, ) -> RelayChainResult>; - /// Get the receipt of a candidate pending availability. This returns `Some` for any paras - /// assigned to occupied cores in `availability_cores` and `None` otherwise. + /// Get the receipt of the first candidate pending availability of this para_id. This returns + /// `Some` for any paras assigned to occupied cores in `availability_cores` and `None` + /// otherwise. + #[deprecated( + note = "`candidate_pending_availability` only returns one candidate and is deprecated. Use `candidates_pending_availability` instead." + )] async fn candidate_pending_availability( &self, block_id: PHash, @@ -203,6 +207,16 @@ pub trait RelayChainInterface: Send + Sync { para_id: ParaId, occupied_core_assumption: OccupiedCoreAssumption, ) -> RelayChainResult>; + + /// Get the receipts of all candidates pending availability for this para_id. + async fn candidates_pending_availability( + &self, + block_id: PHash, + para_id: ParaId, + ) -> RelayChainResult>; + + /// Get the runtime version of the relay chain. + async fn version(&self, relay_parent: PHash) -> RelayChainResult; } #[async_trait] @@ -237,6 +251,7 @@ where .await } + #[allow(deprecated)] async fn candidate_pending_availability( &self, block_id: PHash, @@ -321,4 +336,16 @@ where .validation_code_hash(relay_parent, para_id, occupied_core_assumption) .await } + + async fn candidates_pending_availability( + &self, + block_id: PHash, + para_id: ParaId, + ) -> RelayChainResult> { + (**self).candidates_pending_availability(block_id, para_id).await + } + + async fn version(&self, relay_parent: PHash) -> RelayChainResult { + (**self).version(relay_parent).await + } } diff --git a/cumulus/client/relay-chain-minimal-node/Cargo.toml b/cumulus/client/relay-chain-minimal-node/Cargo.toml index 0b541092a3de866fa68491694db51236ef72f641..1d89316d400bab5a0bb52a78e1890b95409b455d 100644 --- a/cumulus/client/relay-chain-minimal-node/Cargo.toml +++ b/cumulus/client/relay-chain-minimal-node/Cargo.toml @@ -11,44 +11,44 @@ workspace = true [dependencies] # polkadot deps -polkadot-primitives = { path = "../../../polkadot/primitives" } -polkadot-core-primitives = { path = "../../../polkadot/core-primitives" } -polkadot-overseer = { path = "../../../polkadot/node/overseer" } -polkadot-node-subsystem-util = { path = "../../../polkadot/node/subsystem-util" } -polkadot-node-network-protocol = { path = "../../../polkadot/node/network/protocol" } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-core-primitives = { workspace = true, default-features = true } +polkadot-overseer = { workspace = true, default-features = true } +polkadot-node-subsystem-util = { workspace = true, default-features = true } +polkadot-node-network-protocol = { workspace = true, default-features = true } -polkadot-availability-recovery = { path = "../../../polkadot/node/network/availability-recovery" } -polkadot-collator-protocol = { path = "../../../polkadot/node/network/collator-protocol" } -polkadot-network-bridge = { path = "../../../polkadot/node/network/bridge" } -polkadot-node-collation-generation = { path = "../../../polkadot/node/collation-generation" } -polkadot-node-core-runtime-api = { path = "../../../polkadot/node/core/runtime-api" } -polkadot-node-core-chain-api = { path = "../../../polkadot/node/core/chain-api" } -polkadot-node-core-prospective-parachains = { path = "../../../polkadot/node/core/prospective-parachains" } -polkadot-service = { path = "../../../polkadot/node/service" } +polkadot-availability-recovery = { workspace = true, default-features = true } +polkadot-collator-protocol = { workspace = true, default-features = true } +polkadot-network-bridge = { workspace = true, default-features = true } +polkadot-node-collation-generation = { workspace = true, default-features = true } +polkadot-node-core-runtime-api = { workspace = true, default-features = true } +polkadot-node-core-chain-api = { workspace = true, default-features = true } +polkadot-node-core-prospective-parachains = { workspace = true, default-features = true } +polkadot-service = { workspace = true, default-features = true } # substrate deps -sc-authority-discovery = { path = "../../../substrate/client/authority-discovery" } -sc-network = { path = "../../../substrate/client/network" } -sc-network-common = { path = "../../../substrate/client/network/common" } -sc-service = { path = "../../../substrate/client/service" } -sc-client-api = { path = "../../../substrate/client/api" } -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../../substrate/utils/prometheus" } -sc-tracing = { path = "../../../substrate/client/tracing" } -sc-utils = { path = "../../../substrate/client/utils" } -sp-api = { path = "../../../substrate/primitives/api" } -sp-consensus-babe = { path = "../../../substrate/primitives/consensus/babe" } -sp-consensus = { path = "../../../substrate/primitives/consensus/common" } -sp-runtime = { path = "../../../substrate/primitives/runtime" } -sp-blockchain = { path = "../../../substrate/primitives/blockchain" } -tokio = { version = "1.32.0", features = ["macros"] } +sc-authority-discovery = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sc-network-common = { workspace = true, default-features = true } +sc-service = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +prometheus-endpoint = { workspace = true, default-features = true } +sc-tracing = { workspace = true, default-features = true } +sc-utils = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-consensus-babe = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +tokio = { features = ["macros"], workspace = true, default-features = true } # cumulus deps -cumulus-relay-chain-interface = { path = "../relay-chain-interface" } -cumulus-relay-chain-rpc-interface = { path = "../relay-chain-rpc-interface" } -cumulus-primitives-core = { path = "../../primitives/core" } +cumulus-relay-chain-interface = { workspace = true, default-features = true } +cumulus-relay-chain-rpc-interface = { workspace = true, default-features = true } +cumulus-primitives-core = { workspace = true, default-features = true } -array-bytes = "6.2.2" -tracing = "0.1.37" -async-trait = "0.1.79" -futures = "0.3.28" -parking_lot = "0.12.1" +array-bytes = { workspace = true, default-features = true } +tracing = { workspace = true, default-features = true } +async-trait = { workspace = true } +futures = { workspace = true } +parking_lot = { workspace = true, default-features = true } diff --git a/cumulus/client/relay-chain-rpc-interface/Cargo.toml b/cumulus/client/relay-chain-rpc-interface/Cargo.toml index ea6bc2ede4c041620acc18a2fcccde38b03d2388..6c0730a56a264b9805b092df203671778719bc49 100644 --- a/cumulus/client/relay-chain-rpc-interface/Cargo.toml +++ b/cumulus/client/relay-chain-rpc-interface/Cargo.toml @@ -10,39 +10,39 @@ license = "GPL-3.0-or-later WITH Classpath-exception-2.0" workspace = true [dependencies] -polkadot-overseer = { path = "../../../polkadot/node/overseer" } +polkadot-overseer = { workspace = true, default-features = true } -cumulus-primitives-core = { path = "../../primitives/core" } -cumulus-relay-chain-interface = { path = "../relay-chain-interface" } +cumulus-primitives-core = { workspace = true, default-features = true } +cumulus-relay-chain-interface = { workspace = true, default-features = true } -sp-api = { path = "../../../substrate/primitives/api" } -sp-core = { path = "../../../substrate/primitives/core" } -sp-consensus-babe = { path = "../../../substrate/primitives/consensus/babe" } -sp-authority-discovery = { path = "../../../substrate/primitives/authority-discovery" } -sp-state-machine = { path = "../../../substrate/primitives/state-machine" } -sp-storage = { path = "../../../substrate/primitives/storage" } -sp-runtime = { path = "../../../substrate/primitives/runtime" } -sp-version = { path = "../../../substrate/primitives/version" } -sc-client-api = { path = "../../../substrate/client/api" } -sc-rpc-api = { path = "../../../substrate/client/rpc-api" } -sc-service = { path = "../../../substrate/client/service" } +sp-api = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-consensus-babe = { workspace = true, default-features = true } +sp-authority-discovery = { workspace = true, default-features = true } +sp-state-machine = { workspace = true, default-features = true } +sp-storage = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-version = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-rpc-api = { workspace = true, default-features = true } +sc-service = { workspace = true, default-features = true } -tokio = { version = "1.32.0", features = ["sync"] } -tokio-util = { version = "0.7.8", features = ["compat"] } +tokio = { features = ["sync"], workspace = true, default-features = true } +tokio-util = { features = ["compat"], workspace = true } -futures = "0.3.28" -futures-timer = "3.0.2" -codec = { package = "parity-scale-codec", version = "3.6.12" } -jsonrpsee = { version = "0.22", features = ["ws-client"] } -tracing = "0.1.37" -async-trait = "0.1.79" -url = "2.4.0" +futures = { workspace = true } +futures-timer = { workspace = true } +codec = { workspace = true, default-features = true } +jsonrpsee = { features = ["ws-client"], workspace = true } +tracing = { workspace = true, default-features = true } +async-trait = { workspace = true } +url = { workspace = true } serde_json = { workspace = true, default-features = true } serde = { workspace = true, default-features = true } -schnellru = "0.2.1" -smoldot = { version = "0.11.0", default_features = false, features = ["std"] } -smoldot-light = { version = "0.9.0", default_features = false, features = ["std"] } -either = "1.8.1" +schnellru = { workspace = true } +smoldot = { default_features = false, features = ["std"], workspace = true } +smoldot-light = { default_features = false, features = ["std"], workspace = true } +either = { workspace = true, default-features = true } thiserror = { workspace = true } -rand = "0.8.5" -pin-project = "1.1.3" +rand = { workspace = true, default-features = true } +pin-project = { workspace = true } diff --git a/cumulus/client/relay-chain-rpc-interface/src/lib.rs b/cumulus/client/relay-chain-rpc-interface/src/lib.rs index 3a4c186e301eab295aa3befbd3c5549636fdb2c0..bb7bfa5dc32268b87bfbe1788aad7b6604961276 100644 --- a/cumulus/client/relay-chain-rpc-interface/src/lib.rs +++ b/cumulus/client/relay-chain-rpc-interface/src/lib.rs @@ -33,6 +33,7 @@ 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 cumulus_primitives_core::relay_chain::BlockId; @@ -237,4 +238,18 @@ impl RelayChainInterface for RelayChainRpcInterface { let imported_headers_stream = self.rpc_client.get_best_heads_stream()?; Ok(imported_headers_stream.boxed()) } + + async fn candidates_pending_availability( + &self, + hash: RelayHash, + para_id: ParaId, + ) -> RelayChainResult> { + self.rpc_client + .parachain_host_candidates_pending_availability(hash, para_id) + .await + } + + async fn version(&self, relay_parent: RelayHash) -> RelayChainResult { + self.rpc_client.runtime_version(relay_parent).await + } } diff --git a/cumulus/client/relay-chain-rpc-interface/src/light_client_worker.rs b/cumulus/client/relay-chain-rpc-interface/src/light_client_worker.rs index 9a49b60281b3c51fa1426903a0e73157a6f04e0e..2347dbb85f78ed1d8017ba076f6d77e97664c021 100644 --- a/cumulus/client/relay-chain-rpc-interface/src/light_client_worker.rs +++ b/cumulus/client/relay-chain-rpc-interface/src/light_client_worker.rs @@ -20,7 +20,7 @@ use futures::{channel::mpsc::Sender, prelude::*, stream::FuturesUnordered}; use jsonrpsee::core::client::{ - Client as JsonRpseeClient, ClientBuilder, ClientT, Error, ReceivedMessage, TransportReceiverT, + Client as JsonRpseeClient, ClientBuilder, ClientT, ReceivedMessage, TransportReceiverT, TransportSenderT, }; use smoldot_light::{ChainId, Client as SmoldotClient, JsonRpcResponses}; @@ -124,7 +124,7 @@ pub struct LightClientRpcWorker { } fn handle_notification( - maybe_header: Option>, + maybe_header: Option>, senders: &mut Vec>, ) -> Result<(), ()> { match maybe_header { diff --git a/cumulus/client/service/Cargo.toml b/cumulus/client/service/Cargo.toml index e03e20fe5b416102aa99739cb00c0b39edf5b999..8e9e41ca89dc06401c04e36b5cc0db7ffb3e36d7 100644 --- a/cumulus/client/service/Cargo.toml +++ b/cumulus/client/service/Cargo.toml @@ -10,39 +10,39 @@ license = "GPL-3.0-or-later WITH Classpath-exception-2.0" workspace = true [dependencies] -futures = "0.3.28" +futures = { workspace = true } # Substrate -sc-client-api = { path = "../../../substrate/client/api" } -sc-consensus = { path = "../../../substrate/client/consensus/common" } -sc-transaction-pool = { path = "../../../substrate/client/transaction-pool" } -sc-rpc = { path = "../../../substrate/client/rpc" } -sc-service = { path = "../../../substrate/client/service" } -sc-sysinfo = { path = "../../../substrate/client/sysinfo" } -sc-telemetry = { path = "../../../substrate/client/telemetry" } -sc-network = { path = "../../../substrate/client/network" } -sc-network-sync = { path = "../../../substrate/client/network/sync" } -sc-utils = { path = "../../../substrate/client/utils" } -sc-network-transactions = { path = "../../../substrate/client/network/transactions" } -sp-api = { path = "../../../substrate/primitives/api" } -sp-blockchain = { path = "../../../substrate/primitives/blockchain" } -sp-consensus = { path = "../../../substrate/primitives/consensus/common" } -sp-core = { path = "../../../substrate/primitives/core" } -sp-runtime = { path = "../../../substrate/primitives/runtime" } -sp-transaction-pool = { path = "../../../substrate/primitives/transaction-pool" } -sp-io = { path = "../../../substrate/primitives/io" } +sc-client-api = { workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } +sc-transaction-pool = { workspace = true, default-features = true } +sc-rpc = { workspace = true, default-features = true } +sc-service = { workspace = true, default-features = true } +sc-sysinfo = { workspace = true, default-features = true } +sc-telemetry = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sc-network-sync = { workspace = true, default-features = true } +sc-utils = { workspace = true, default-features = true } +sc-network-transactions = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-transaction-pool = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } # Polkadot -polkadot-primitives = { path = "../../../polkadot/primitives" } +polkadot-primitives = { workspace = true, default-features = true } # Cumulus -cumulus-client-cli = { path = "../cli" } -cumulus-client-collator = { path = "../collator" } -cumulus-client-consensus-common = { path = "../consensus/common" } -cumulus-client-pov-recovery = { path = "../pov-recovery" } -cumulus-client-network = { path = "../network" } -cumulus-primitives-core = { path = "../../primitives/core" } -cumulus-primitives-proof-size-hostfunction = { path = "../../primitives/proof-size-hostfunction" } -cumulus-relay-chain-interface = { path = "../relay-chain-interface" } -cumulus-relay-chain-inprocess-interface = { path = "../relay-chain-inprocess-interface" } -cumulus-relay-chain-minimal-node = { path = "../relay-chain-minimal-node" } +cumulus-client-cli = { workspace = true, default-features = true } +cumulus-client-collator = { workspace = true, default-features = true } +cumulus-client-consensus-common = { workspace = true, default-features = true } +cumulus-client-pov-recovery = { workspace = true, default-features = true } +cumulus-client-network = { workspace = true, default-features = true } +cumulus-primitives-core = { workspace = true, default-features = true } +cumulus-primitives-proof-size-hostfunction = { workspace = true, default-features = true } +cumulus-relay-chain-interface = { workspace = true, default-features = true } +cumulus-relay-chain-inprocess-interface = { workspace = true, default-features = true } +cumulus-relay-chain-minimal-node = { workspace = true, default-features = true } diff --git a/cumulus/pallets/aura-ext/Cargo.toml b/cumulus/pallets/aura-ext/Cargo.toml index daff5ef8f482e82b80f341d5208cad51b23b7b1a..1b6ac4cf07dff2341c366a18e103f7e0ec49e2ac 100644 --- a/cumulus/pallets/aura-ext/Cargo.toml +++ b/cumulus/pallets/aura-ext/Cargo.toml @@ -10,26 +10,26 @@ license = "Apache-2.0" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } # Substrate -frame-support = { path = "../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -pallet-aura = { path = "../../../substrate/frame/aura", default-features = false } -pallet-timestamp = { path = "../../../substrate/frame/timestamp", default-features = false } -sp-application-crypto = { path = "../../../substrate/primitives/application-crypto", default-features = false } -sp-consensus-aura = { path = "../../../substrate/primitives/consensus/aura", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-aura = { workspace = true } +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 = { path = "../parachain-system", default-features = false } +cumulus-pallet-parachain-system = { workspace = true } [dev-dependencies] # Cumulus -cumulus-pallet-parachain-system = { path = "../parachain-system" } +cumulus-pallet-parachain-system = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/cumulus/pallets/collator-selection/Cargo.toml b/cumulus/pallets/collator-selection/Cargo.toml index f30802fa5d82ecb93e8610e7c7bb17a2a83cacb4..206700b7d606c81bef4f33cbfe6e705e6efb49ad 100644 --- a/cumulus/pallets/collator-selection/Cargo.toml +++ b/cumulus/pallets/collator-selection/Cargo.toml @@ -17,29 +17,29 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] log = { workspace = true } -codec = { default-features = false, features = ["derive"], package = "parity-scale-codec", version = "3.6.12" } -rand = { version = "0.8.5", features = ["std_rng"], default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +rand = { features = ["std_rng"], workspace = true } +scale-info = { features = ["derive"], workspace = true } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-staking = { path = "../../../substrate/primitives/staking", default-features = false } -frame-support = { path = "../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -pallet-authorship = { path = "../../../substrate/frame/authorship", default-features = false } -pallet-balances = { path = "../../../substrate/frame/balances", default-features = false } -pallet-session = { path = "../../../substrate/frame/session", default-features = false } +sp-std = { workspace = true } +sp-runtime = { workspace = true } +sp-staking = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-authorship = { workspace = true } +pallet-balances = { workspace = true } +pallet-session = { workspace = true } -frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-features = false, optional = true } +frame-benchmarking = { optional = true, workspace = true } [dev-dependencies] -sp-core = { path = "../../../substrate/primitives/core" } -sp-io = { path = "../../../substrate/primitives/io" } -sp-tracing = { path = "../../../substrate/primitives/tracing" } -sp-runtime = { path = "../../../substrate/primitives/runtime" } -pallet-timestamp = { path = "../../../substrate/frame/timestamp" } -sp-consensus-aura = { path = "../../../substrate/primitives/consensus/aura" } -pallet-aura = { path = "../../../substrate/frame/aura" } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +pallet-timestamp = { workspace = true, default-features = true } +sp-consensus-aura = { workspace = true, default-features = true } +pallet-aura = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/cumulus/pallets/collator-selection/src/mock.rs b/cumulus/pallets/collator-selection/src/mock.rs index 6521c954eac23f6663e59b593d77e093a626196d..459b1cb5fdf28c118751c3afccc4b882891d1cc3 100644 --- a/cumulus/pallets/collator-selection/src/mock.rs +++ b/cumulus/pallets/collator-selection/src/mock.rs @@ -53,23 +53,12 @@ impl system::Config for Test { parameter_types! { pub const ExistentialDeposit: u64 = 5; - pub const MaxReserves: u32 = 50; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type Balance = u64; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type WeightInfo = (); - type MaxLocks = (); - type MaxReserves = MaxReserves; - type ReserveIdentifier = [u8; 8]; - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeFreezeReason; - type FreezeIdentifier = (); - type MaxFreezes = ConstU32<0>; } pub struct Author4; diff --git a/cumulus/pallets/dmp-queue/Cargo.toml b/cumulus/pallets/dmp-queue/Cargo.toml index 687cda164fb0bd3d4aefb9d6b51f6735ef3a43c3..052a2547e788b0837cf224cb38095d40c20ed0fd 100644 --- a/cumulus/pallets/dmp-queue/Cargo.toml +++ b/cumulus/pallets/dmp-queue/Cargo.toml @@ -14,26 +14,26 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } -frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-support = { path = "../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-io = { path = "../../../substrate/primitives/io", default-features = false } +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 } # Polkadot -xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false } +xcm = { workspace = true } # Cumulus -cumulus-primitives-core = { path = "../../primitives/core", default-features = false } +cumulus-primitives-core = { workspace = true } [dev-dependencies] -sp-core = { path = "../../../substrate/primitives/core" } -sp-tracing = { path = "../../../substrate/primitives/tracing" } +sp-core = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/cumulus/pallets/parachain-system/Cargo.toml b/cumulus/pallets/parachain-system/Cargo.toml index 1a6a19f2ab4a2523074bd02aa96053a0f7236140..30a232f01b3e5ca82eab239626e2255a683972ee 100644 --- a/cumulus/pallets/parachain-system/Cargo.toml +++ b/cumulus/pallets/parachain-system/Cargo.toml @@ -10,62 +10,62 @@ license = "Apache-2.0" workspace = true [dependencies] -bytes = { version = "1.4.0", default-features = false } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -environmental = { version = "1.1.4", default-features = false } -impl-trait-for-tuples = "0.2.1" +bytes = { workspace = true } +codec = { features = ["derive"], workspace = true } +environmental = { workspace = true } +impl-trait-for-tuples = { workspace = true } log = { workspace = true } -trie-db = { version = "0.29.0", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +trie-db = { workspace = true } +scale-info = { features = ["derive"], workspace = true } # Substrate -frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-support = { path = "../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -pallet-message-queue = { path = "../../../substrate/frame/message-queue", default-features = false } -sp-core = { path = "../../../substrate/primitives/core", default-features = false } -sp-externalities = { path = "../../../substrate/primitives/externalities", default-features = false } -sp-inherents = { path = "../../../substrate/primitives/inherents", default-features = false } -sp-io = { path = "../../../substrate/primitives/io", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-state-machine = { path = "../../../substrate/primitives/state-machine", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } -sp-trie = { path = "../../../substrate/primitives/trie", default-features = false } -sp-version = { path = "../../../substrate/primitives/version", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-message-queue = { workspace = true } +sp-core = { workspace = true } +sp-externalities = { workspace = true } +sp-inherents = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-state-machine = { workspace = true } +sp-std = { workspace = true } +sp-trie = { workspace = true } +sp-version = { workspace = true } # Polkadot -polkadot-parachain-primitives = { path = "../../../polkadot/parachain", default-features = false, features = ["wasm-api"] } -polkadot-runtime-parachains = { path = "../../../polkadot/runtime/parachains", default-features = false } -polkadot-runtime-common = { path = "../../../polkadot/runtime/common", default-features = false, optional = true } -xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../polkadot/xcm/xcm-builder", default-features = false } +polkadot-parachain-primitives = { features = ["wasm-api"], workspace = true } +polkadot-runtime-parachains = { workspace = true } +polkadot-runtime-common = { optional = true, workspace = true } +xcm = { workspace = true } +xcm-builder = { workspace = true } # Cumulus -cumulus-pallet-parachain-system-proc-macro = { path = "proc-macro", default-features = false } -cumulus-primitives-core = { path = "../../primitives/core", default-features = false } -cumulus-primitives-parachain-inherent = { path = "../../primitives/parachain-inherent", default-features = false } -cumulus-primitives-proof-size-hostfunction = { path = "../../primitives/proof-size-hostfunction", default-features = false } +cumulus-pallet-parachain-system-proc-macro = { workspace = true } +cumulus-primitives-core = { workspace = true } +cumulus-primitives-parachain-inherent = { workspace = true } +cumulus-primitives-proof-size-hostfunction = { workspace = true } [dev-dependencies] -assert_matches = "1.5" -hex-literal = "0.4.1" -lazy_static = "1.4" -trie-standardmap = "0.16.0" -rand = "0.8.5" -futures = "0.3.28" +assert_matches = { workspace = true } +hex-literal = { workspace = true, default-features = true } +lazy_static = { workspace = true } +trie-standardmap = { workspace = true } +rand = { workspace = true, default-features = true } +futures = { workspace = true } # Substrate -sc-client-api = { path = "../../../substrate/client/api" } -sp-keyring = { path = "../../../substrate/primitives/keyring" } -sp-crypto-hashing = { path = "../../../substrate/primitives/crypto/hashing" } -sp-tracing = { path = "../../../substrate/primitives/tracing" } -sp-version = { path = "../../../substrate/primitives/version" } -sp-consensus-slots = { path = "../../../substrate/primitives/consensus/slots" } +sc-client-api = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +sp-crypto-hashing = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +sp-version = { workspace = true, default-features = true } +sp-consensus-slots = { workspace = true, default-features = true } # Cumulus -cumulus-test-client = { path = "../../test/client" } -cumulus-test-relay-sproof-builder = { path = "../../test/relay-sproof-builder" } -cumulus-test-runtime = { path = "../../test/runtime" } +cumulus-test-client = { workspace = true } +cumulus-test-relay-sproof-builder = { workspace = true, default-features = true } +cumulus-test-runtime = { workspace = true } [features] default = ["std"] diff --git a/cumulus/pallets/parachain-system/proc-macro/Cargo.toml b/cumulus/pallets/parachain-system/proc-macro/Cargo.toml index 0a90c30e0331261026125f429efe70eff07ac069..da6f0fd03efb79b03e4815433084ca8b79f6595d 100644 --- a/cumulus/pallets/parachain-system/proc-macro/Cargo.toml +++ b/cumulus/pallets/parachain-system/proc-macro/Cargo.toml @@ -14,9 +14,9 @@ proc-macro = true [dependencies] syn = { workspace = true } -proc-macro2 = "1.0.64" +proc-macro2 = { workspace = true } quote = { workspace = true } -proc-macro-crate = "3.0.0" +proc-macro-crate = { workspace = true } [features] default = ["std"] diff --git a/cumulus/pallets/session-benchmarking/Cargo.toml b/cumulus/pallets/session-benchmarking/Cargo.toml index 62c923de59f25d7fc6ba8db15df48e625e16e118..df671566cdc24b8fca9486d0444aad6a1688eedb 100644 --- a/cumulus/pallets/session-benchmarking/Cargo.toml +++ b/cumulus/pallets/session-benchmarking/Cargo.toml @@ -16,13 +16,13 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -frame-support = { path = "../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-features = false, optional = true } -pallet-session = { path = "../../../substrate/frame/session", default-features = false } +codec = { workspace = true } +sp-std = { workspace = true } +sp-runtime = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +frame-benchmarking = { optional = true, workspace = true } +pallet-session = { workspace = true } [features] default = ["std"] diff --git a/cumulus/pallets/solo-to-para/Cargo.toml b/cumulus/pallets/solo-to-para/Cargo.toml index 17b0fb2a01662d517a49d1bfd669ed071caf0ed7..ced1b24f1d2bf52f1f6db128affe3bd8595411ba 100644 --- a/cumulus/pallets/solo-to-para/Cargo.toml +++ b/cumulus/pallets/solo-to-para/Cargo.toml @@ -10,21 +10,21 @@ license = "Apache-2.0" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } # Substrate -frame-support = { path = "../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -pallet-sudo = { path = "../../../substrate/frame/sudo", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-sudo = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } # Polkadot -polkadot-primitives = { path = "../../../polkadot/primitives", default-features = false } +polkadot-primitives = { workspace = true } # Cumulus -cumulus-pallet-parachain-system = { path = "../parachain-system", default-features = false } +cumulus-pallet-parachain-system = { workspace = true } [features] default = ["std"] diff --git a/cumulus/pallets/xcm/Cargo.toml b/cumulus/pallets/xcm/Cargo.toml index 178d981702f2e6dc42d05556e20a86f50106b6ee..1f0cef70e3a72920d6c789acb9051ddf2a7ff8e8 100644 --- a/cumulus/pallets/xcm/Cargo.toml +++ b/cumulus/pallets/xcm/Cargo.toml @@ -10,18 +10,18 @@ description = "Pallet for stuff specific to parachains' usage of XCM" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } -sp-io = { path = "../../../substrate/primitives/io", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -frame-support = { path = "../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } +sp-std = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } -xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false } +xcm = { workspace = true } -cumulus-primitives-core = { path = "../../primitives/core", default-features = false } +cumulus-primitives-core = { workspace = true } [features] default = ["std"] diff --git a/cumulus/pallets/xcmp-queue/Cargo.toml b/cumulus/pallets/xcmp-queue/Cargo.toml index 87602978521fc363539b2aeb81f5b485dbe409ea..c542fa373b5ed352edc4e00ea032b6dd64c97415 100644 --- a/cumulus/pallets/xcmp-queue/Cargo.toml +++ b/cumulus/pallets/xcmp-queue/Cargo.toml @@ -10,45 +10,45 @@ license = "Apache-2.0" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"], default-features = false } +codec = { features = ["derive"], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } # Substrate -frame-support = { path = "../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -sp-io = { path = "../../../substrate/primitives/io", default-features = false } -sp-core = { path = "../../../substrate/primitives/core", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } -pallet-message-queue = { path = "../../../substrate/frame/message-queue", default-features = false } +frame-support = { workspace = true } +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 -polkadot-runtime-common = { path = "../../../polkadot/runtime/common", default-features = false } -polkadot-runtime-parachains = { path = "../../../polkadot/runtime/parachains", default-features = false } -xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../polkadot/xcm/xcm-executor", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../polkadot/xcm/xcm-builder", default-features = false } +polkadot-runtime-common = { workspace = true } +polkadot-runtime-parachains = { workspace = true } +xcm = { workspace = true } +xcm-executor = { workspace = true } +xcm-builder = { workspace = true } # Cumulus -cumulus-primitives-core = { path = "../../primitives/core", default-features = false } +cumulus-primitives-core = { workspace = true } # Optional import for benchmarking -frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-features = false, optional = true } -bounded-collections = { version = "0.2.0", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +bounded-collections = { workspace = true } # Bridges -bp-xcm-bridge-hub-router = { path = "../../../bridges/primitives/xcm-bridge-hub-router", default-features = false, optional = true } +bp-xcm-bridge-hub-router = { optional = true, workspace = true } [dev-dependencies] # Substrate -sp-core = { path = "../../../substrate/primitives/core" } -pallet-balances = { path = "../../../substrate/frame/balances" } -frame-support = { path = "../../../substrate/frame/support", features = ["experimental"] } +sp-core = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +frame-support = { features = ["experimental"], workspace = true, default-features = true } # Cumulus -cumulus-pallet-parachain-system = { path = "../parachain-system" } +cumulus-pallet-parachain-system = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/cumulus/pallets/xcmp-queue/src/lib.rs b/cumulus/pallets/xcmp-queue/src/lib.rs index 5310e474215cd5c27e560ed33822f2b1f76aa19f..5c124fbc4463b60ee4fefedc6e9e784fc9a4de30 100644 --- a/cumulus/pallets/xcmp-queue/src/lib.rs +++ b/cumulus/pallets/xcmp-queue/src/lib.rs @@ -491,7 +491,7 @@ impl Pallet { let channel_info = T::ChannelInfo::get_channel_info(recipient).ok_or(MessageSendError::NoChannel)?; // Max message size refers to aggregates, or pages. Not to individual fragments. - let max_message_size = channel_info.max_message_size as usize; + let max_message_size = channel_info.max_message_size.min(T::MaxPageSize::get()) as usize; let format_size = format.encoded_size(); // We check the encoded fragment length plus the format size against the max message size // because the format is concatenated if a new page is needed. @@ -522,7 +522,7 @@ impl Pallet { // We return the size of the last page inside of the option, to not calculate it again. let appended_to_last_page = have_active .then(|| { - >::mutate( + >::try_mutate( recipient, channel_details.last_index - 1, |page| { @@ -532,17 +532,18 @@ impl Pallet { ) != Ok(format) { defensive!("Bad format in outbound queue; dropping message"); - return None + return Err(()) } if page.len() + encoded_fragment.len() > max_message_size { - return None + return Err(()) } for frag in encoded_fragment.iter() { - page.try_push(*frag).ok()?; + page.try_push(*frag)?; } - Some(page.len()) + Ok(page.len()) }, ) + .ok() }) .flatten(); diff --git a/cumulus/pallets/xcmp-queue/src/mock.rs b/cumulus/pallets/xcmp-queue/src/mock.rs index e166a78ee822097ebadb613ed81dd344a6574bf0..7fb96de7a4eaae7e7f78fae66179a26a3a6c5866 100644 --- a/cumulus/pallets/xcmp-queue/src/mock.rs +++ b/cumulus/pallets/xcmp-queue/src/mock.rs @@ -85,25 +85,14 @@ impl frame_system::Config for Test { parameter_types! { pub const ExistentialDeposit: u64 = 5; - pub const MaxReserves: u32 = 50; } pub type Balance = u64; +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type WeightInfo = (); - type MaxLocks = (); - type MaxReserves = MaxReserves; - type ReserveIdentifier = [u8; 8]; - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeFreezeReason; - type FreezeIdentifier = (); - type MaxFreezes = ConstU32<0>; } impl cumulus_pallet_parachain_system::Config for Test { diff --git a/cumulus/pallets/xcmp-queue/src/tests.rs b/cumulus/pallets/xcmp-queue/src/tests.rs index cdf41e27f0b27aa99a8fc73fd42f98b02ee0e48e..5b02baf2310a368c3b49269e4c594a81d47a3a01 100644 --- a/cumulus/pallets/xcmp-queue/src/tests.rs +++ b/cumulus/pallets/xcmp-queue/src/tests.rs @@ -28,6 +28,7 @@ use frame_support::{ use mock::{new_test_ext, ParachainSystem, RuntimeOrigin as Origin, Test, XcmpQueue}; use sp_runtime::traits::{BadOrigin, Zero}; use std::iter::{once, repeat}; +use xcm_builder::InspectMessageQueues; #[test] fn empty_concatenated_works() { @@ -854,7 +855,6 @@ fn verify_fee_factor_increase_and_decrease() { #[test] fn get_messages_works() { new_test_ext().execute_with(|| { - use xcm_builder::InspectMessageQueues; let sibling_para_id = ParaId::from(2001); ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(sibling_para_id); let destination: Location = (Parent, Parachain(sibling_para_id.into())).into(); @@ -890,3 +890,32 @@ fn get_messages_works() { ); }); } + +/// We try to send a fragment that will not fit into the currently active page. This should +/// therefore not modify the current page but instead create a new one. +#[test] +fn page_not_modified_when_fragment_does_not_fit() { + new_test_ext().execute_with(|| { + let sibling = ParaId::from(2001); + ParachainSystem::open_outbound_hrmp_channel_for_benchmarks_or_tests(sibling); + + let destination: Location = (Parent, Parachain(sibling.into())).into(); + let message = Xcm(vec![ClearOrigin; 600]); + + loop { + let old_page_zero = OutboundXcmpMessages::::get(sibling, 0); + assert_ok!(send_xcm::(destination.clone(), message.clone())); + + // If a new page was created by this send_xcm call, then page_zero was not also + // modified: + let num_pages = OutboundXcmpMessages::::iter_prefix(sibling).count(); + if num_pages == 2 { + let new_page_zero = OutboundXcmpMessages::::get(sibling, 0); + assert_eq!(old_page_zero, new_page_zero); + break + } else if num_pages > 2 { + panic!("Too many pages created"); + } + } + }); +} diff --git a/cumulus/parachains/chain-specs/collectives-polkadot.json b/cumulus/parachains/chain-specs/collectives-polkadot.json index a0d5ddff6ebb1d4808a48c5af16d3a60bb648ad8..a6ba01ffa394dfdba05e65014006f10eb68ea858 100644 --- a/cumulus/parachains/chain-specs/collectives-polkadot.json +++ b/cumulus/parachains/chain-specs/collectives-polkadot.json @@ -23,9 +23,8 @@ "/dns/polkadot-collectives-boot-ng.dwellir.com/tcp/443/wss/p2p/12D3KooWDMFYCNRAQcSRNV7xu2xv8319goSEbSHW4TnXRz6EpPKc", "/dns/collectives-polkadot-bootnode.radiumblock.com/tcp/30333/p2p/12D3KooWDumvnNwPbBg5inBEapgjKU7ECdMHHgwfYeGWUkzYUE1c", "/dns/collectives-polkadot-bootnode.radiumblock.com/tcp/30336/wss/p2p/12D3KooWDumvnNwPbBg5inBEapgjKU7ECdMHHgwfYeGWUkzYUE1c", - "/dns/pch13.rotko.net/tcp/33573/p2p/12D3KooWRXudHoazPZ9osMfdY38e8CBxQLD4RhrVeHpRSNNpcDtH", - "/dns/pch13.rotko.net/tcp/34573/ws/p2p/12D3KooWRXudHoazPZ9osMfdY38e8CBxQLD4RhrVeHpRSNNpcDtH", - "/dns/pch13.rotko.net/tcp/35573/wss/p2p/12D3KooWRXudHoazPZ9osMfdY38e8CBxQLD4RhrVeHpRSNNpcDtH", + "/dns/pch16.rotko.net/tcp/33576/p2p/12D3KooWKrm3XmuGzJH17Wcn4HRDGsEjLZGDgN77q3ZhwnnQP7y1", + "/dns/pch16.rotko.net/tcp/35576/wss/p2p/12D3KooWKrm3XmuGzJH17Wcn4HRDGsEjLZGDgN77q3ZhwnnQP7y1", "/dns/collectives-polkadot.bootnodes.polkadotters.com/tcp/30526/p2p/12D3KooWNohUjvJtGKUa8Vhy8C1ZBB5N8JATB6e7rdLVCioeb3ff", "/dns/collectives-polkadot.bootnodes.polkadotters.com/tcp/30528/wss/p2p/12D3KooWNohUjvJtGKUa8Vhy8C1ZBB5N8JATB6e7rdLVCioeb3ff", "/dns/boot-polkadot-collectives.luckyfriday.io/tcp/443/wss/p2p/12D3KooWCzifnPooTt4kvTnXT7FTKTymVL7xn7DURQLsS2AKpf6w" diff --git a/cumulus/parachains/chain-specs/people-kusama.json b/cumulus/parachains/chain-specs/people-kusama.json index 00a38b675def73cee48e38e084938e158932bbe2..3352cb25a2898f5442b1e28b340def69fc4168f2 100644 --- a/cumulus/parachains/chain-specs/people-kusama.json +++ b/cumulus/parachains/chain-specs/people-kusama.json @@ -8,7 +8,25 @@ "/dns/kusama-people-connect-0.polkadot.io/tcp/443/wss/p2p/12D3KooWQaqG5TNmDfRWrtH7tMsN7YeqwVkSfoZT4GkemSzezNi1", "/dns/kusama-people-connect-1.polkadot.io/tcp/443/wss/p2p/12D3KooWKhYoQH9LdSyvY3SVZY9gFf6ZV1bFh6317TRehUP3r5fm", "/dns/people-kusama.bootnode.amforc.com/tcp/29999/wss/p2p/12D3KooWPjzgKZe5jdG6TY4gwcFq8QxyyhqsYbQo6N29pwGePWLA", - "/dns/people-kusama.bootnode.amforc.com/tcp/30004/p2p/12D3KooWPjzgKZe5jdG6TY4gwcFq8QxyyhqsYbQo6N29pwGePWLA" + "/dns/people-kusama.bootnode.amforc.com/tcp/30004/p2p/12D3KooWPjzgKZe5jdG6TY4gwcFq8QxyyhqsYbQo6N29pwGePWLA", + "/dns/boot.gatotech.network/tcp/33240/p2p/12D3KooWLi9TzaKX4zniJpiM521PnYG4EocpdqjPpJUhXq9QGkRX", + "/dns/boot.gatotech.network/tcp/35240/wss/p2p/12D3KooWLi9TzaKX4zniJpiM521PnYG4EocpdqjPpJUhXq9QGkRX", + "/dns/people-kusama-bootnode.radiumblock.com/tcp/30333/p2p/12D3KooWGP1C9iWTHnZyeaSjYZ7LdK8douXWc1n1dBv25XEASHaj", + "/dns/people-kusama-bootnode.radiumblock.com/tcp/30336/wss/p2p/12D3KooWGP1C9iWTHnZyeaSjYZ7LdK8douXWc1n1dBv25XEASHaj", + "/dns/kppl16.rotko.net/tcp/33756/p2p/12D3KooWSKQwgoydfbN6mNN2aNwdqfkR2ExAnTRs8mmdrPQTtDLo", + "/dns/kppl16.rotko.net/tcp/35756/wss/p2p/12D3KooWSKQwgoydfbN6mNN2aNwdqfkR2ExAnTRs8mmdrPQTtDLo", + "/dns/people-kusama-boot-ng.dwellir.com/tcp/30359/p2p/12D3KooWM6T8MMibxLZhhpq6F612CZ4FgnfDSJSkWDMiVUDe1aGb", + "/dns/people-kusama-boot-ng.dwellir.com/tcp/443/wss/p2p/12D3KooWM6T8MMibxLZhhpq6F612CZ4FgnfDSJSkWDMiVUDe1aGb", + "/dns/people-kusama-bootnode.turboflakes.io/tcp/30645/p2p/12D3KooWCR2Q8J2NFFfuofDak4zSgWkuBq7orP96HFaxLgAoDUBV", + "/dns/people-kusama-bootnode.turboflakes.io/tcp/30745/wss/p2p/12D3KooWCR2Q8J2NFFfuofDak4zSgWkuBq7orP96HFaxLgAoDUBV", + "/dns/boot-node.helikon.io/tcp/7510/p2p/12D3KooWM1X4setrMWjwnV8iDkAtYhqFHNkGozdWdq6sawWh5Yhv", + "/dns/boot-node.helikon.io/tcp/7512/wss/p2p/12D3KooWM1X4setrMWjwnV8iDkAtYhqFHNkGozdWdq6sawWh5Yhv", + "/dns/people-kusama.bootnodes.polkadotters.com/tcp/30377/p2p/12D3KooWHy7TAuK6EoVij2tfaeh3KkaEJxhTmumbEom3HfRnSEsp", + "/dns/people-kusama.bootnodes.polkadotters.com/tcp/30379/wss/p2p/12D3KooWHy7TAuK6EoVij2tfaeh3KkaEJxhTmumbEom3HfRnSEsp", + "/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" ], "telemetryEndpoints": null, "protocolId": null, diff --git a/cumulus/parachains/common/Cargo.toml b/cumulus/parachains/common/Cargo.toml index 2b943b6dca55989a891895b4abb3195970978b06..6eac9a09672675c3cb46d1eb49392bb0651eb7dd 100644 --- a/cumulus/parachains/common/Cargo.toml +++ b/cumulus/parachains/common/Cargo.toml @@ -13,42 +13,42 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"], default-features = false } +codec = { features = ["derive"], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } # Substrate -frame-support = { path = "../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -pallet-asset-tx-payment = { path = "../../../substrate/frame/transaction-payment/asset-tx-payment", default-features = false } -pallet-assets = { path = "../../../substrate/frame/assets", default-features = false } -pallet-authorship = { path = "../../../substrate/frame/authorship", default-features = false } -pallet-balances = { path = "../../../substrate/frame/balances", default-features = false } -pallet-message-queue = { path = "../../../substrate/frame/message-queue", default-features = false } -sp-consensus-aura = { path = "../../../substrate/primitives/consensus/aura", default-features = false } -sp-core = { path = "../../../substrate/primitives/core", default-features = false } -sp-io = { path = "../../../substrate/primitives/io", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-asset-tx-payment = { workspace = true } +pallet-assets = { workspace = true } +pallet-authorship = { workspace = true } +pallet-balances = { workspace = true } +pallet-message-queue = { workspace = true } +sp-consensus-aura = { workspace = true } +sp-core = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } # Polkadot -pallet-xcm = { path = "../../../polkadot/xcm/pallet-xcm", default-features = false } -polkadot-primitives = { path = "../../../polkadot/primitives", default-features = false } -xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../polkadot/xcm/xcm-executor", default-features = false } +pallet-xcm = { workspace = true } +polkadot-primitives = { workspace = true } +xcm = { workspace = true } +xcm-executor = { workspace = true } # Cumulus -pallet-collator-selection = { path = "../../pallets/collator-selection", default-features = false } -cumulus-primitives-core = { path = "../../primitives/core", default-features = false } -cumulus-primitives-utility = { path = "../../primitives/utility", default-features = false } -parachain-info = { package = "staging-parachain-info", path = "../pallets/parachain-info", default-features = false } +pallet-collator-selection = { workspace = true } +cumulus-primitives-core = { workspace = true } +cumulus-primitives-utility = { workspace = true } +parachain-info = { workspace = true } [dev-dependencies] -pallet-authorship = { path = "../../../substrate/frame/authorship", default-features = false } -sp-io = { path = "../../../substrate/primitives/io", default-features = false } +pallet-authorship = { workspace = true } +sp-io = { workspace = true } [build-dependencies] -substrate-wasm-builder = { path = "../../../substrate/utils/wasm-builder" } +substrate-wasm-builder = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/cumulus/parachains/common/src/impls.rs b/cumulus/parachains/common/src/impls.rs index ed9c5c483fa74282306d20c20a6c6313bd940f5a..16cda1a4ed83850f4e67765a5e7092dad4a24305 100644 --- a/cumulus/parachains/common/src/impls.rs +++ b/cumulus/parachains/common/src/impls.rs @@ -202,7 +202,7 @@ mod tests { use frame_system::{limits, EnsureRoot}; use pallet_collator_selection::IdentityCollator; use polkadot_primitives::AccountId; - use sp_core::{ConstU64, H256}; + use sp_core::H256; use sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, BuildStorage, Perbill, @@ -224,7 +224,6 @@ mod tests { parameter_types! { pub BlockLength: limits::BlockLength = limits::BlockLength::max(2 * 1024); pub const AvailableBlockRatio: Perbill = Perbill::one(); - pub const MaxReserves: u32 = 50; } #[derive_impl(frame_system::config_preludes::TestDefaultConfig)] @@ -253,20 +252,9 @@ mod tests { type MaxConsumers = frame_support::traits::ConstU32<16>; } + #[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type Balance = u64; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ConstU64<1>; type AccountStore = System; - type MaxLocks = (); - type WeightInfo = (); - type MaxReserves = MaxReserves; - type ReserveIdentifier = [u8; 8]; - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeFreezeReason; - type FreezeIdentifier = (); - type MaxFreezes = ConstU32<1>; } pub struct OneAuthor; diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-rococo/Cargo.toml b/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-rococo/Cargo.toml index 8100e681348836fb28c9236b9ba20d27f117d71b..7bd91ae6774c61f93b12a91af298e64777980ac1 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-rococo/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-rococo/Cargo.toml @@ -13,16 +13,16 @@ workspace = true [dependencies] # Substrate -sp-core = { path = "../../../../../../../../substrate/primitives/core", default-features = false } -frame-support = { path = "../../../../../../../../substrate/frame/support", default-features = false } +sp-core = { workspace = true } +frame-support = { workspace = true } # Cumulus -parachains-common = { path = "../../../../../../common" } -cumulus-primitives-core = { path = "../../../../../../../primitives/core", default-features = false } -emulated-integration-tests-common = { path = "../../../../common", default-features = false } -asset-hub-rococo-runtime = { path = "../../../../../../runtimes/assets/asset-hub-rococo" } -rococo-emulated-chain = { path = "../../../relays/rococo" } -testnet-parachains-constants = { path = "../../../../../../runtimes/constants", features = ["rococo"] } +parachains-common = { workspace = true, default-features = true } +cumulus-primitives-core = { workspace = true } +emulated-integration-tests-common = { workspace = true } +asset-hub-rococo-runtime = { workspace = true, default-features = true } +rococo-emulated-chain = { workspace = true } +testnet-parachains-constants = { features = ["rococo"], workspace = true, default-features = true } # Polkadot -xcm = { package = "staging-xcm", path = "../../../../../../../../polkadot/xcm", default-features = false } +xcm = { workspace = true } diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-westend/Cargo.toml b/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-westend/Cargo.toml index e0abaa66c5cabba445b91c19436f9a4ce3642386..86d4ce3e7ac829e959aa3169adbd22a257cc26a5 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-westend/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/assets/asset-hub-westend/Cargo.toml @@ -13,16 +13,16 @@ workspace = true [dependencies] # Substrate -sp-core = { path = "../../../../../../../../substrate/primitives/core", default-features = false } -frame-support = { path = "../../../../../../../../substrate/frame/support", default-features = false } +sp-core = { workspace = true } +frame-support = { workspace = true } # Cumulus -parachains-common = { path = "../../../../../../common" } -cumulus-primitives-core = { path = "../../../../../../../primitives/core", default-features = false } -emulated-integration-tests-common = { path = "../../../../common", default-features = false } -asset-hub-westend-runtime = { path = "../../../../../../runtimes/assets/asset-hub-westend" } -westend-emulated-chain = { path = "../../../relays/westend" } -testnet-parachains-constants = { path = "../../../../../../runtimes/constants", features = ["westend"] } +parachains-common = { workspace = true, default-features = true } +cumulus-primitives-core = { workspace = true } +emulated-integration-tests-common = { workspace = true } +asset-hub-westend-runtime = { workspace = true } +westend-emulated-chain = { workspace = true, default-features = true } +testnet-parachains-constants = { features = ["westend"], workspace = true, default-features = true } # Polkadot -xcm = { package = "staging-xcm", path = "../../../../../../../../polkadot/xcm", default-features = false } +xcm = { workspace = true } diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-rococo/Cargo.toml b/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-rococo/Cargo.toml index 789f10a35f268c62e0cc9fa153c99e7e5282ee8d..f3c0799ad0f6acf14b3e99d4e27e46921c4e9cb9 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-rococo/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-rococo/Cargo.toml @@ -13,12 +13,12 @@ workspace = true [dependencies] # Substrate -sp-core = { path = "../../../../../../../../substrate/primitives/core", default-features = false } -frame-support = { path = "../../../../../../../../substrate/frame/support", default-features = false } +sp-core = { workspace = true } +frame-support = { workspace = true } # Cumulus -parachains-common = { path = "../../../../../../common" } -emulated-integration-tests-common = { path = "../../../../common", default-features = false } -bridge-hub-rococo-runtime = { path = "../../../../../../runtimes/bridge-hubs/bridge-hub-rococo" } -bridge-hub-common = { path = "../../../../../../runtimes/bridge-hubs/common", default-features = false } -testnet-parachains-constants = { path = "../../../../../../runtimes/constants", features = ["rococo"] } +parachains-common = { workspace = true, default-features = true } +emulated-integration-tests-common = { workspace = true } +bridge-hub-rococo-runtime = { workspace = true, default-features = true } +bridge-hub-common = { workspace = true } +testnet-parachains-constants = { features = ["rococo"], workspace = true, default-features = true } diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-westend/Cargo.toml b/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-westend/Cargo.toml index d82971cf55aeddf20032be952b8a980014434f6b..ebcec9641e7d9f122f5b6737769bc140d9c877a5 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-westend/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/bridges/bridge-hub-westend/Cargo.toml @@ -13,12 +13,12 @@ workspace = true [dependencies] # Substrate -sp-core = { path = "../../../../../../../../substrate/primitives/core", default-features = false } -frame-support = { path = "../../../../../../../../substrate/frame/support", default-features = false } +sp-core = { workspace = true } +frame-support = { workspace = true } # Cumulus -parachains-common = { path = "../../../../../../common" } -emulated-integration-tests-common = { path = "../../../../common", default-features = false } -bridge-hub-westend-runtime = { path = "../../../../../../runtimes/bridge-hubs/bridge-hub-westend" } -bridge-hub-common = { path = "../../../../../../runtimes/bridge-hubs/common", default-features = false } -testnet-parachains-constants = { path = "../../../../../../runtimes/constants", features = ["westend"] } +parachains-common = { workspace = true, default-features = true } +emulated-integration-tests-common = { workspace = true } +bridge-hub-westend-runtime = { workspace = true, default-features = true } +bridge-hub-common = { workspace = true } +testnet-parachains-constants = { features = ["westend"], workspace = true, default-features = true } diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/collectives/collectives-westend/Cargo.toml b/cumulus/parachains/integration-tests/emulated/chains/parachains/collectives/collectives-westend/Cargo.toml index 4c2a7d3c274dce6eade9c9d42be00301bd6dc462..87dfd73ab05bab063bedeebae9feb03bcc4af46f 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/parachains/collectives/collectives-westend/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/collectives/collectives-westend/Cargo.toml @@ -13,12 +13,12 @@ workspace = true [dependencies] # Substrate -sp-core = { path = "../../../../../../../../substrate/primitives/core", default-features = false } -frame-support = { path = "../../../../../../../../substrate/frame/support", default-features = false } +sp-core = { workspace = true } +frame-support = { workspace = true } # Cumulus -parachains-common = { path = "../../../../../../common" } -cumulus-primitives-core = { path = "../../../../../../../primitives/core", default-features = false } -emulated-integration-tests-common = { path = "../../../../common", default-features = false } -collectives-westend-runtime = { path = "../../../../../../runtimes/collectives/collectives-westend" } -testnet-parachains-constants = { path = "../../../../../../runtimes/constants", features = ["westend"] } +parachains-common = { workspace = true, default-features = true } +cumulus-primitives-core = { workspace = true } +emulated-integration-tests-common = { workspace = true } +collectives-westend-runtime = { workspace = true } +testnet-parachains-constants = { features = ["westend"], workspace = true, default-features = true } diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/people/people-rococo/Cargo.toml b/cumulus/parachains/integration-tests/emulated/chains/parachains/people/people-rococo/Cargo.toml index f7fe93d27775a28cb560d8791a3b0d8ed49c9d68..1549d6a2ab6ba1de05d9233ff7bc29951501a43d 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/parachains/people/people-rococo/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/people/people-rococo/Cargo.toml @@ -10,12 +10,12 @@ publish = false [dependencies] # Substrate -sp-core = { path = "../../../../../../../../substrate/primitives/core", default-features = false } -frame-support = { path = "../../../../../../../../substrate/frame/support", default-features = false } +sp-core = { workspace = true } +frame-support = { workspace = true } # Cumulus -parachains-common = { path = "../../../../../../common" } -cumulus-primitives-core = { path = "../../../../../../../primitives/core", default-features = false } -emulated-integration-tests-common = { path = "../../../../common", default-features = false } -people-rococo-runtime = { path = "../../../../../../runtimes/people/people-rococo" } -testnet-parachains-constants = { path = "../../../../../../runtimes/constants", features = ["rococo"] } +parachains-common = { workspace = true, default-features = true } +cumulus-primitives-core = { workspace = true } +emulated-integration-tests-common = { workspace = true } +people-rococo-runtime = { workspace = true } +testnet-parachains-constants = { features = ["rococo"], workspace = true, default-features = true } diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/people/people-westend/Cargo.toml b/cumulus/parachains/integration-tests/emulated/chains/parachains/people/people-westend/Cargo.toml index 57a767e0c2a3eb7d23df7f8d95fd78128c996f35..9c5ac0bca9de7ae2f201aba958b8220b9a24a013 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/parachains/people/people-westend/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/people/people-westend/Cargo.toml @@ -10,12 +10,12 @@ publish = false [dependencies] # Substrate -sp-core = { path = "../../../../../../../../substrate/primitives/core", default-features = false } -frame-support = { path = "../../../../../../../../substrate/frame/support", default-features = false } +sp-core = { workspace = true } +frame-support = { workspace = true } # Cumulus -parachains-common = { path = "../../../../../../common" } -cumulus-primitives-core = { path = "../../../../../../../primitives/core", default-features = false } -emulated-integration-tests-common = { path = "../../../../common", default-features = false } -people-westend-runtime = { path = "../../../../../../runtimes/people/people-westend" } -testnet-parachains-constants = { path = "../../../../../../runtimes/constants", features = ["westend"] } +parachains-common = { workspace = true, default-features = true } +cumulus-primitives-core = { workspace = true } +emulated-integration-tests-common = { workspace = true } +people-westend-runtime = { workspace = true } +testnet-parachains-constants = { features = ["westend"], workspace = true, default-features = true } diff --git a/cumulus/parachains/integration-tests/emulated/chains/parachains/testing/penpal/Cargo.toml b/cumulus/parachains/integration-tests/emulated/chains/parachains/testing/penpal/Cargo.toml index 2ac508273c6158ddae08615d8574102f98e3e788..9e6b14b585984d9b384f835f1b51f8a3e2e658a8 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/parachains/testing/penpal/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/chains/parachains/testing/penpal/Cargo.toml @@ -13,14 +13,14 @@ workspace = true [dependencies] # Substrate -sp-core = { path = "../../../../../../../../substrate/primitives/core", default-features = false } -frame-support = { path = "../../../../../../../../substrate/frame/support", default-features = false } +sp-core = { workspace = true } +frame-support = { workspace = true } # Polkadot -xcm = { package = "staging-xcm", path = "../../../../../../../../polkadot/xcm", default-features = false } +xcm = { workspace = true } # Cumulus -parachains-common = { path = "../../../../../../common" } -cumulus-primitives-core = { path = "../../../../../../../primitives/core", default-features = false } -emulated-integration-tests-common = { path = "../../../../common", default-features = false } -penpal-runtime = { path = "../../../../../../runtimes/testing/penpal" } +parachains-common = { workspace = true, default-features = true } +cumulus-primitives-core = { workspace = true } +emulated-integration-tests-common = { workspace = true } +penpal-runtime = { workspace = true } diff --git a/cumulus/parachains/integration-tests/emulated/chains/relays/rococo/Cargo.toml b/cumulus/parachains/integration-tests/emulated/chains/relays/rococo/Cargo.toml index 113036b4c00ea697507166a1f1da8d44458bacdd..9376687947e6c3683d5c1c58fdaf77452fd01449 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/relays/rococo/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/chains/relays/rococo/Cargo.toml @@ -13,17 +13,17 @@ workspace = true [dependencies] # Substrate -sp-core = { path = "../../../../../../../substrate/primitives/core", default-features = false } -sp-authority-discovery = { path = "../../../../../../../substrate/primitives/authority-discovery", default-features = false } -sp-consensus-babe = { path = "../../../../../../../substrate/primitives/consensus/babe", default-features = false } -sp-consensus-beefy = { path = "../../../../../../../substrate/primitives/consensus/beefy" } -sc-consensus-grandpa = { path = "../../../../../../../substrate/client/consensus/grandpa", default-features = false } +sp-core = { workspace = true } +sp-authority-discovery = { workspace = true } +sp-consensus-babe = { workspace = true } +sp-consensus-beefy = { workspace = true, default-features = true } +sc-consensus-grandpa = { workspace = true } # Polkadot -polkadot-primitives = { path = "../../../../../../../polkadot/primitives", default-features = false } -rococo-runtime-constants = { path = "../../../../../../../polkadot/runtime/rococo/constants", default-features = false } -rococo-runtime = { path = "../../../../../../../polkadot/runtime/rococo" } +polkadot-primitives = { workspace = true } +rococo-runtime-constants = { workspace = true } +rococo-runtime = { workspace = true } # Cumulus -parachains-common = { path = "../../../../../common" } -emulated-integration-tests-common = { path = "../../../common", default-features = false } +parachains-common = { workspace = true, default-features = true } +emulated-integration-tests-common = { workspace = true } diff --git a/cumulus/parachains/integration-tests/emulated/chains/relays/westend/Cargo.toml b/cumulus/parachains/integration-tests/emulated/chains/relays/westend/Cargo.toml index b952477c47a7c33277d9cd6bf09ea7a2ba1dd799..de285d9885a2f78fdea1a27ea8b8d9dc3840d300 100644 --- a/cumulus/parachains/integration-tests/emulated/chains/relays/westend/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/chains/relays/westend/Cargo.toml @@ -13,21 +13,21 @@ workspace = true [dependencies] # Substrate -sp-core = { path = "../../../../../../../substrate/primitives/core", default-features = false } -sp-runtime = { path = "../../../../../../../substrate/primitives/runtime", default-features = false } -sp-authority-discovery = { path = "../../../../../../../substrate/primitives/authority-discovery", default-features = false } -sp-consensus-babe = { path = "../../../../../../../substrate/primitives/consensus/babe", default-features = false } -sp-consensus-beefy = { path = "../../../../../../../substrate/primitives/consensus/beefy" } -sc-consensus-grandpa = { path = "../../../../../../../substrate/client/consensus/grandpa", default-features = false } -pallet-staking = { path = "../../../../../../../substrate/frame/staking", default-features = false } +sp-core = { workspace = true } +sp-runtime = { workspace = true } +sp-authority-discovery = { workspace = true } +sp-consensus-babe = { workspace = true } +sp-consensus-beefy = { workspace = true, default-features = true } +sc-consensus-grandpa = { workspace = true } +pallet-staking = { workspace = true } # Polkadot -polkadot-primitives = { path = "../../../../../../../polkadot/primitives", default-features = false } -westend-runtime-constants = { path = "../../../../../../../polkadot/runtime/westend/constants", default-features = false } -westend-runtime = { path = "../../../../../../../polkadot/runtime/westend" } -xcm = { package = "staging-xcm", path = "../../../../../../../polkadot/xcm", default-features = false } -xcm-fee-payment-runtime-api = { path = "../../../../../../../polkadot/xcm/xcm-fee-payment-runtime-api", default-features = false } +polkadot-primitives = { workspace = true } +westend-runtime-constants = { workspace = true } +westend-runtime = { workspace = true } +xcm = { workspace = true } +xcm-runtime-apis = { workspace = true } # Cumulus -parachains-common = { path = "../../../../../common" } -emulated-integration-tests-common = { path = "../../../common", default-features = false } +parachains-common = { workspace = true, default-features = true } +emulated-integration-tests-common = { workspace = true } diff --git a/cumulus/parachains/integration-tests/emulated/common/Cargo.toml b/cumulus/parachains/integration-tests/emulated/common/Cargo.toml index d9ec813232309998e8e50557138773d14c65c04b..7152f1dbc272bd8eef49e2343b2c5cbbeb9f1ba4 100644 --- a/cumulus/parachains/integration-tests/emulated/common/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/common/Cargo.toml @@ -10,37 +10,37 @@ description = "Common resources for integration testing with xcm-emulator" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -paste = "1.0.14" +codec = { workspace = true } +paste = { workspace = true, default-features = true } # Substrate -sp-consensus-beefy = { path = "../../../../../substrate/primitives/consensus/beefy" } -sc-consensus-grandpa = { path = "../../../../../substrate/client/consensus/grandpa" } -sp-authority-discovery = { path = "../../../../../substrate/primitives/authority-discovery" } -sp-runtime = { path = "../../../../../substrate/primitives/runtime" } -frame-support = { path = "../../../../../substrate/frame/support" } -sp-core = { path = "../../../../../substrate/primitives/core" } -sp-consensus-babe = { path = "../../../../../substrate/primitives/consensus/babe" } -pallet-assets = { path = "../../../../../substrate/frame/assets" } -pallet-balances = { path = "../../../../../substrate/frame/balances" } -pallet-message-queue = { path = "../../../../../substrate/frame/message-queue" } +sp-consensus-beefy = { workspace = true, default-features = true } +sc-consensus-grandpa = { workspace = true, default-features = true } +sp-authority-discovery = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +frame-support = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-consensus-babe = { workspace = true, default-features = true } +pallet-assets = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +pallet-message-queue = { workspace = true, default-features = true } # Polkadot -polkadot-primitives = { path = "../../../../../polkadot/primitives" } -polkadot-parachain-primitives = { path = "../../../../../polkadot/parachain" } -polkadot-runtime-parachains = { path = "../../../../../polkadot/runtime/parachains" } -xcm = { package = "staging-xcm", path = "../../../../../polkadot/xcm" } -pallet-xcm = { path = "../../../../../polkadot/xcm/pallet-xcm" } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-parachain-primitives = { workspace = true, default-features = true } +polkadot-runtime-parachains = { workspace = true, default-features = true } +xcm = { workspace = true, default-features = true } +pallet-xcm = { workspace = true, default-features = true } # Cumulus -parachains-common = { path = "../../../common" } -cumulus-primitives-core = { path = "../../../../primitives/core" } -xcm-emulator = { path = "../../../../xcm/xcm-emulator" } -cumulus-pallet-xcmp-queue = { path = "../../../../pallets/xcmp-queue" } -cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system" } -asset-test-utils = { path = "../../../runtimes/assets/test-utils" } +parachains-common = { workspace = true, default-features = true } +cumulus-primitives-core = { workspace = true, default-features = true } +xcm-emulator = { workspace = true, default-features = true } +cumulus-pallet-xcmp-queue = { workspace = true, default-features = true } +cumulus-pallet-parachain-system = { workspace = true, default-features = true } +asset-test-utils = { workspace = true, default-features = true } # Bridges -bp-messages = { path = "../../../../../bridges/primitives/messages" } -pallet-bridge-messages = { path = "../../../../../bridges/modules/messages" } -bridge-runtime-common = { path = "../../../../../bridges/bin/runtime-common" } +bp-messages = { workspace = true, default-features = true } +pallet-bridge-messages = { workspace = true, default-features = true } +bridge-runtime-common = { workspace = true, default-features = true } 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 eb0a8a850d06928d67147dc14a11f566d1ad7c9d..298be7362ec3a4e63bb4139b1050d1b0223c9382 100644 --- a/cumulus/parachains/integration-tests/emulated/networks/rococo-system/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/networks/rococo-system/Cargo.toml @@ -12,9 +12,9 @@ workspace = true [dependencies] # Cumulus -emulated-integration-tests-common = { path = "../../common", default-features = false } -rococo-emulated-chain = { path = "../../chains/relays/rococo" } -asset-hub-rococo-emulated-chain = { path = "../../chains/parachains/assets/asset-hub-rococo" } -bridge-hub-rococo-emulated-chain = { path = "../../chains/parachains/bridges/bridge-hub-rococo" } -people-rococo-emulated-chain = { path = "../../chains/parachains/people/people-rococo" } -penpal-emulated-chain = { path = "../../chains/parachains/testing/penpal" } +emulated-integration-tests-common = { workspace = true } +rococo-emulated-chain = { workspace = true } +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 } diff --git a/cumulus/parachains/integration-tests/emulated/networks/rococo-westend-system/Cargo.toml b/cumulus/parachains/integration-tests/emulated/networks/rococo-westend-system/Cargo.toml index 744cbe4f8c1e31ed5a9b122a5b5939509234236a..cd0cb272b7f5ea9bea09835b7cf4612ad9c377be 100644 --- a/cumulus/parachains/integration-tests/emulated/networks/rococo-westend-system/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/networks/rococo-westend-system/Cargo.toml @@ -12,11 +12,11 @@ workspace = true [dependencies] # Cumulus -emulated-integration-tests-common = { path = "../../common", default-features = false } -rococo-emulated-chain = { path = "../../chains/relays/rococo" } -westend-emulated-chain = { path = "../../chains/relays/westend" } -asset-hub-rococo-emulated-chain = { path = "../../chains/parachains/assets/asset-hub-rococo" } -asset-hub-westend-emulated-chain = { path = "../../chains/parachains/assets/asset-hub-westend" } -bridge-hub-rococo-emulated-chain = { path = "../../chains/parachains/bridges/bridge-hub-rococo" } -bridge-hub-westend-emulated-chain = { path = "../../chains/parachains/bridges/bridge-hub-westend" } -penpal-emulated-chain = { path = "../../chains/parachains/testing/penpal" } +emulated-integration-tests-common = { workspace = true } +rococo-emulated-chain = { workspace = true } +westend-emulated-chain = { workspace = true, default-features = true } +asset-hub-rococo-emulated-chain = { workspace = true } +asset-hub-westend-emulated-chain = { workspace = true } +bridge-hub-rococo-emulated-chain = { workspace = true } +bridge-hub-westend-emulated-chain = { workspace = true } +penpal-emulated-chain = { workspace = true } 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 64bc91f442d1b27166fbc4f0a2dc22798c97ff39..37c14aa30352922b6f9f44ab89c6501484c3212d 100644 --- a/cumulus/parachains/integration-tests/emulated/networks/westend-system/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/networks/westend-system/Cargo.toml @@ -12,10 +12,10 @@ workspace = true [dependencies] # Cumulus -emulated-integration-tests-common = { path = "../../common", default-features = false } -westend-emulated-chain = { path = "../../chains/relays/westend", default-features = false } -asset-hub-westend-emulated-chain = { path = "../../chains/parachains/assets/asset-hub-westend" } -bridge-hub-westend-emulated-chain = { path = "../../chains/parachains/bridges/bridge-hub-westend" } -collectives-westend-emulated-chain = { path = "../../chains/parachains/collectives/collectives-westend" } -penpal-emulated-chain = { path = "../../chains/parachains/testing/penpal" } -people-westend-emulated-chain = { path = "../../chains/parachains/people/people-westend" } +emulated-integration-tests-common = { workspace = true } +westend-emulated-chain = { workspace = true } +asset-hub-westend-emulated-chain = { workspace = true } +bridge-hub-westend-emulated-chain = { workspace = true } +collectives-westend-emulated-chain = { workspace = true } +penpal-emulated-chain = { workspace = true } +people-westend-emulated-chain = { workspace = true } diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/Cargo.toml b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/Cargo.toml index 9abecbecc48a725448cfb17508351d5e76f848de..19d3bb3cb29ef7d09f99f79bc4a41d416477619f 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-rococo/Cargo.toml @@ -11,32 +11,32 @@ publish = false workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -assert_matches = "1.5.0" +codec = { workspace = true } +assert_matches = { workspace = true } # Substrate -sp-runtime = { path = "../../../../../../../substrate/primitives/runtime", default-features = false } -frame-support = { path = "../../../../../../../substrate/frame/support", default-features = false } -pallet-balances = { path = "../../../../../../../substrate/frame/balances", default-features = false } -pallet-assets = { path = "../../../../../../../substrate/frame/assets", default-features = false } -pallet-asset-conversion = { path = "../../../../../../../substrate/frame/asset-conversion", default-features = false } -pallet-message-queue = { path = "../../../../../../../substrate/frame/message-queue", default-features = false } -pallet-treasury = { path = "../../../../../../../substrate/frame/treasury", default-features = false } -pallet-utility = { path = "../../../../../../../substrate/frame/utility", default-features = false } +sp-runtime = { workspace = true } +frame-support = { workspace = true } +pallet-balances = { workspace = true } +pallet-assets = { workspace = true } +pallet-asset-conversion = { workspace = true } +pallet-message-queue = { workspace = true } +pallet-treasury = { workspace = true } +pallet-utility = { workspace = true } # Polkadot -xcm = { package = "staging-xcm", path = "../../../../../../../polkadot/xcm", default-features = false } -pallet-xcm = { path = "../../../../../../../polkadot/xcm/pallet-xcm", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../../../../polkadot/xcm/xcm-executor", default-features = false } -rococo-runtime = { path = "../../../../../../../polkadot/runtime/rococo" } -polkadot-runtime-common = { path = "../../../../../../../polkadot/runtime/common" } -rococo-runtime-constants = { path = "../../../../../../../polkadot/runtime/rococo/constants" } +xcm = { workspace = true } +pallet-xcm = { workspace = true } +xcm-executor = { workspace = true } +rococo-runtime = { workspace = true } +polkadot-runtime-common = { workspace = true, default-features = true } +rococo-runtime-constants = { workspace = true, default-features = true } # Cumulus -asset-test-utils = { path = "../../../../../runtimes/assets/test-utils" } -cumulus-pallet-parachain-system = { path = "../../../../../../pallets/parachain-system", default-features = false } -parachains-common = { path = "../../../../../common" } -asset-hub-rococo-runtime = { path = "../../../../../runtimes/assets/asset-hub-rococo" } -penpal-runtime = { path = "../../../../../runtimes/testing/penpal" } -emulated-integration-tests-common = { path = "../../../common", default-features = false } -rococo-system-emulated-network = { path = "../../../networks/rococo-system" } +asset-test-utils = { workspace = true, default-features = true } +cumulus-pallet-parachain-system = { workspace = true } +parachains-common = { workspace = true, default-features = true } +asset-hub-rococo-runtime = { workspace = true, default-features = true } +penpal-runtime = { workspace = true } +emulated-integration-tests-common = { workspace = true } +rococo-system-emulated-network = { workspace = true } diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/Cargo.toml b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/Cargo.toml index e0f29cd801c346a064a4773efa5754b0e2f399f4..2f4cc5ea39c185dae3079e30313bef3ba9c23694 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/Cargo.toml @@ -11,38 +11,38 @@ publish = false workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -assert_matches = "1.5.0" +codec = { workspace = true } +assert_matches = { workspace = true } # Substrate -sp-runtime = { path = "../../../../../../../substrate/primitives/runtime", default-features = false } -sp-keyring = { path = "../../../../../../../substrate/primitives/keyring", default-features = false } -sp-core = { path = "../../../../../../../substrate/primitives/core", default-features = false } -frame-metadata-hash-extension = { path = "../../../../../../../substrate/frame/metadata-hash-extension" } -frame-support = { path = "../../../../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../../../../substrate/frame/system", default-features = false } -pallet-balances = { path = "../../../../../../../substrate/frame/balances", default-features = false } -pallet-assets = { path = "../../../../../../../substrate/frame/assets", default-features = false } -pallet-asset-conversion = { path = "../../../../../../../substrate/frame/asset-conversion", default-features = false } -pallet-treasury = { path = "../../../../../../../substrate/frame/treasury", default-features = false } -pallet-message-queue = { path = "../../../../../../../substrate/frame/message-queue", default-features = false } -pallet-transaction-payment = { path = "../../../../../../../substrate/frame/transaction-payment", default-features = false } -pallet-asset-tx-payment = { path = "../../../../../../../substrate/frame/transaction-payment/asset-tx-payment", default-features = false } +sp-runtime = { workspace = true } +sp-keyring = { workspace = true } +sp-core = { workspace = true } +frame-metadata-hash-extension = { workspace = true, default-features = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-balances = { workspace = true } +pallet-assets = { workspace = true } +pallet-asset-conversion = { workspace = true } +pallet-treasury = { workspace = true } +pallet-message-queue = { workspace = true } +pallet-transaction-payment = { workspace = true } +pallet-asset-tx-payment = { workspace = true } # Polkadot -polkadot-runtime-common = { path = "../../../../../../../polkadot/runtime/common" } -xcm = { package = "staging-xcm", path = "../../../../../../../polkadot/xcm", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../../../../polkadot/xcm/xcm-executor", default-features = false } -pallet-xcm = { path = "../../../../../../../polkadot/xcm/pallet-xcm", default-features = false } -xcm-fee-payment-runtime-api = { path = "../../../../../../../polkadot/xcm/xcm-fee-payment-runtime-api", default-features = false } -westend-runtime = { path = "../../../../../../../polkadot/runtime/westend" } +polkadot-runtime-common = { workspace = true, default-features = true } +xcm = { workspace = true } +xcm-executor = { workspace = true } +pallet-xcm = { workspace = true } +xcm-runtime-apis = { workspace = true } +westend-runtime = { workspace = true } # Cumulus -parachains-common = { path = "../../../../../common" } -penpal-runtime = { path = "../../../../../runtimes/testing/penpal" } -asset-hub-westend-runtime = { path = "../../../../../runtimes/assets/asset-hub-westend" } -asset-test-utils = { path = "../../../../../runtimes/assets/test-utils" } -cumulus-pallet-xcmp-queue = { path = "../../../../../../pallets/xcmp-queue", default-features = false } -cumulus-pallet-parachain-system = { path = "../../../../../../pallets/parachain-system", default-features = false } -emulated-integration-tests-common = { path = "../../../common", default-features = false } -westend-system-emulated-network = { path = "../../../networks/westend-system" } +parachains-common = { workspace = true, default-features = true } +penpal-runtime = { workspace = true } +asset-hub-westend-runtime = { workspace = true } +asset-test-utils = { workspace = true, default-features = true } +cumulus-pallet-xcmp-queue = { workspace = true } +cumulus-pallet-parachain-system = { workspace = true } +emulated-integration-tests-common = { workspace = true } +westend-system-emulated-network = { workspace = true } diff --git a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/xcm_fee_estimation.rs b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/xcm_fee_estimation.rs index dc89ef1f7a44e6afc218de787bc47d452ae50fa8..c01aa7825336348f5077c89a73c61e7b128a6200 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/xcm_fee_estimation.rs +++ b/cumulus/parachains/integration-tests/emulated/tests/assets/asset-hub-westend/src/tests/xcm_fee_estimation.rs @@ -18,7 +18,7 @@ use crate::imports::*; use frame_system::RawOrigin; -use xcm_fee_payment_runtime_api::{ +use xcm_runtime_apis::{ dry_run::runtime_decl_for_dry_run_api::DryRunApiV1, fees::runtime_decl_for_xcm_payment_api::XcmPaymentApiV1, }; diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/Cargo.toml b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/Cargo.toml index bed5af92f6e55b37f7f12518dbe1ed1b290dd5aa..23dee370bf33d2a68da14c334a6d04a0a7694750 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-rococo/Cargo.toml @@ -11,40 +11,40 @@ publish = false workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -hex-literal = "0.4.1" +codec = { workspace = true } +scale-info = { features = ["derive"], workspace = true } +hex-literal = { workspace = true, default-features = true } # Substrate -sp-core = { path = "../../../../../../../substrate/primitives/core", default-features = false } -frame-support = { path = "../../../../../../../substrate/frame/support", default-features = false } -pallet-assets = { path = "../../../../../../../substrate/frame/assets", default-features = false } -pallet-asset-conversion = { path = "../../../../../../../substrate/frame/asset-conversion", default-features = false } -pallet-balances = { path = "../../../../../../../substrate/frame/balances", default-features = false } -pallet-message-queue = { path = "../../../../../../../substrate/frame/message-queue" } -sp-runtime = { path = "../../../../../../../substrate/primitives/runtime", default-features = false } +sp-core = { workspace = true } +frame-support = { workspace = true } +pallet-assets = { workspace = true } +pallet-asset-conversion = { workspace = true } +pallet-balances = { workspace = true } +pallet-message-queue = { workspace = true, default-features = true } +sp-runtime = { workspace = true } # Polkadot -xcm = { package = "staging-xcm", path = "../../../../../../../polkadot/xcm", default-features = false } -pallet-xcm = { path = "../../../../../../../polkadot/xcm/pallet-xcm", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../../../../polkadot/xcm/xcm-executor", default-features = false } +xcm = { workspace = true } +pallet-xcm = { workspace = true } +xcm-executor = { workspace = true } # Bridges -pallet-bridge-messages = { path = "../../../../../../../bridges/modules/messages", default-features = false } +pallet-bridge-messages = { workspace = true } # Cumulus -parachains-common = { path = "../../../../../common" } -testnet-parachains-constants = { path = "../../../../../runtimes/constants", features = ["rococo"] } -cumulus-pallet-xcmp-queue = { path = "../../../../../../pallets/xcmp-queue", default-features = false } -bridge-hub-rococo-runtime = { path = "../../../../../runtimes/bridge-hubs/bridge-hub-rococo", default-features = false } -emulated-integration-tests-common = { path = "../../../common", default-features = false } -rococo-westend-system-emulated-network = { path = "../../../networks/rococo-westend-system" } -rococo-system-emulated-network = { path = "../../../networks/rococo-system" } -asset-hub-rococo-runtime = { path = "../../../../../runtimes/assets/asset-hub-rococo", default-features = false } +parachains-common = { workspace = true, default-features = true } +testnet-parachains-constants = { features = ["rococo"], workspace = true, default-features = true } +cumulus-pallet-xcmp-queue = { workspace = true } +bridge-hub-rococo-runtime = { workspace = true } +emulated-integration-tests-common = { workspace = true } +rococo-westend-system-emulated-network = { workspace = true } +rococo-system-emulated-network = { workspace = true } +asset-hub-rococo-runtime = { workspace = true } # Snowbridge -snowbridge-core = { path = "../../../../../../../bridges/snowbridge/primitives/core", default-features = false } -snowbridge-router-primitives = { path = "../../../../../../../bridges/snowbridge/primitives/router", default-features = false } -snowbridge-pallet-system = { path = "../../../../../../../bridges/snowbridge/pallets/system", default-features = false } -snowbridge-pallet-outbound-queue = { path = "../../../../../../../bridges/snowbridge/pallets/outbound-queue", default-features = false } -snowbridge-pallet-inbound-queue-fixtures = { path = "../../../../../../../bridges/snowbridge/pallets/inbound-queue/fixtures" } +snowbridge-core = { workspace = true } +snowbridge-router-primitives = { workspace = true } +snowbridge-pallet-system = { workspace = true } +snowbridge-pallet-outbound-queue = { workspace = true } +snowbridge-pallet-inbound-queue-fixtures = { workspace = true, default-features = true } diff --git a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/Cargo.toml b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/Cargo.toml index 6aebf8862d62e794a24e6926ff487d1956ed792b..9ea8d0b81bdb774b14b2f6f11a3ed7c551f2e080 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/tests/bridges/bridge-hub-westend/Cargo.toml @@ -13,24 +13,24 @@ workspace = true [dependencies] # Substrate -frame-support = { path = "../../../../../../../substrate/frame/support", default-features = false } -pallet-assets = { path = "../../../../../../../substrate/frame/assets", default-features = false } -pallet-asset-conversion = { path = "../../../../../../../substrate/frame/asset-conversion", default-features = false } -pallet-balances = { path = "../../../../../../../substrate/frame/balances", default-features = false } -pallet-message-queue = { path = "../../../../../../../substrate/frame/message-queue" } -sp-runtime = { path = "../../../../../../../substrate/primitives/runtime", default-features = false } +frame-support = { workspace = true } +pallet-assets = { workspace = true } +pallet-asset-conversion = { workspace = true } +pallet-balances = { workspace = true } +pallet-message-queue = { workspace = true, default-features = true } +sp-runtime = { workspace = true } # Polkadot -xcm = { package = "staging-xcm", path = "../../../../../../../polkadot/xcm", default-features = false } -pallet-xcm = { path = "../../../../../../../polkadot/xcm/pallet-xcm", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../../../../polkadot/xcm/xcm-executor", default-features = false } +xcm = { workspace = true } +pallet-xcm = { workspace = true } +xcm-executor = { workspace = true } # Bridges -pallet-bridge-messages = { path = "../../../../../../../bridges/modules/messages", default-features = false } +pallet-bridge-messages = { workspace = true } # Cumulus -parachains-common = { path = "../../../../../common" } -cumulus-pallet-xcmp-queue = { path = "../../../../../../pallets/xcmp-queue", default-features = false } -bridge-hub-westend-runtime = { path = "../../../../../runtimes/bridge-hubs/bridge-hub-westend", default-features = false } -emulated-integration-tests-common = { path = "../../../common", default-features = false } -rococo-westend-system-emulated-network = { path = "../../../networks/rococo-westend-system" } +parachains-common = { workspace = true, default-features = true } +cumulus-pallet-xcmp-queue = { workspace = true } +bridge-hub-westend-runtime = { workspace = true } +emulated-integration-tests-common = { workspace = true } +rococo-westend-system-emulated-network = { workspace = true } diff --git a/cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend/Cargo.toml b/cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend/Cargo.toml index 297f68de6218317017a36c9535ad581aa86e2883..c546132fa63b2553ab4e487a40de35772f4bff24 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/tests/collectives/collectives-westend/Cargo.toml @@ -11,33 +11,33 @@ publish = false workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -assert_matches = "1.5.0" +codec = { workspace = true } +assert_matches = { workspace = true } # Substrate -sp-runtime = { path = "../../../../../../../substrate/primitives/runtime", default-features = false } -frame-support = { path = "../../../../../../../substrate/frame/support", default-features = false } -pallet-balances = { path = "../../../../../../../substrate/frame/balances", default-features = false } -pallet-asset-rate = { path = "../../../../../../../substrate/frame/asset-rate", default-features = false } -pallet-assets = { path = "../../../../../../../substrate/frame/assets", default-features = false } -pallet-treasury = { path = "../../../../../../../substrate/frame/treasury", default-features = false } -pallet-message-queue = { path = "../../../../../../../substrate/frame/message-queue", default-features = false } -pallet-utility = { path = "../../../../../../../substrate/frame/utility", default-features = false } +sp-runtime = { workspace = true } +frame-support = { workspace = true } +pallet-balances = { workspace = true } +pallet-asset-rate = { workspace = true } +pallet-assets = { workspace = true } +pallet-treasury = { workspace = true } +pallet-message-queue = { workspace = true } +pallet-utility = { workspace = true } # Polkadot -polkadot-runtime-common = { path = "../../../../../../../polkadot/runtime/common" } -xcm = { package = "staging-xcm", path = "../../../../../../../polkadot/xcm", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../../../../polkadot/xcm/xcm-executor", default-features = false } -pallet-xcm = { path = "../../../../../../../polkadot/xcm/pallet-xcm", default-features = false } -westend-runtime = { path = "../../../../../../../polkadot/runtime/westend" } -westend-runtime-constants = { path = "../../../../../../../polkadot/runtime/westend/constants" } +polkadot-runtime-common = { workspace = true, default-features = true } +xcm = { workspace = true } +xcm-executor = { workspace = true } +pallet-xcm = { workspace = true } +westend-runtime = { workspace = true } +westend-runtime-constants = { workspace = true, default-features = true } # Cumulus -parachains-common = { path = "../../../../../../parachains/common" } -testnet-parachains-constants = { path = "../../../../../runtimes/constants", features = ["westend"] } -asset-hub-westend-runtime = { path = "../../../../../runtimes/assets/asset-hub-westend" } -collectives-westend-runtime = { path = "../../../../../runtimes/collectives/collectives-westend" } -cumulus-pallet-xcmp-queue = { default-features = false, path = "../../../../../../pallets/xcmp-queue" } -cumulus-pallet-parachain-system = { default-features = false, path = "../../../../../../pallets/parachain-system" } -emulated-integration-tests-common = { path = "../../../common", default-features = false } -westend-system-emulated-network = { path = "../../../networks/westend-system" } +parachains-common = { workspace = true, default-features = true } +testnet-parachains-constants = { features = ["westend"], workspace = true, default-features = true } +asset-hub-westend-runtime = { workspace = true } +collectives-westend-runtime = { workspace = true } +cumulus-pallet-xcmp-queue = { workspace = true } +cumulus-pallet-parachain-system = { workspace = true } +emulated-integration-tests-common = { workspace = true } +westend-system-emulated-network = { workspace = true } diff --git a/cumulus/parachains/integration-tests/emulated/tests/people/people-rococo/Cargo.toml b/cumulus/parachains/integration-tests/emulated/tests/people/people-rococo/Cargo.toml index 29a939951e597a939de5ed9d244193ac8455e4d5..5221b782ac64e423035ebbdda86d1d2ede840902 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/people/people-rococo/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/tests/people/people-rococo/Cargo.toml @@ -8,25 +8,25 @@ description = "People Rococo runtime integration tests with xcm-emulator" publish = false [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } +codec = { workspace = true } # Substrate -sp-runtime = { path = "../../../../../../../substrate/primitives/runtime", default-features = false } -frame-support = { path = "../../../../../../../substrate/frame/support", default-features = false } -pallet-balances = { path = "../../../../../../../substrate/frame/balances", default-features = false } -pallet-message-queue = { path = "../../../../../../../substrate/frame/message-queue", default-features = false } -pallet-identity = { path = "../../../../../../../substrate/frame/identity", default-features = false } +sp-runtime = { workspace = true } +frame-support = { workspace = true } +pallet-balances = { workspace = true } +pallet-message-queue = { workspace = true } +pallet-identity = { workspace = true } # Polkadot -xcm = { package = "staging-xcm", path = "../../../../../../../polkadot/xcm", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../../../../polkadot/xcm/xcm-executor", default-features = false } -rococo-runtime = { path = "../../../../../../../polkadot/runtime/rococo" } -rococo-runtime-constants = { path = "../../../../../../../polkadot/runtime/rococo/constants" } -polkadot-runtime-common = { path = "../../../../../../../polkadot/runtime/common" } +xcm = { workspace = true } +xcm-executor = { workspace = true } +rococo-runtime = { workspace = true } +rococo-runtime-constants = { workspace = true, default-features = true } +polkadot-runtime-common = { workspace = true, default-features = true } # Cumulus -asset-test-utils = { path = "../../../../../runtimes/assets/test-utils" } -parachains-common = { path = "../../../../../common" } -people-rococo-runtime = { path = "../../../../../runtimes/people/people-rococo" } -emulated-integration-tests-common = { path = "../../../common", default-features = false } -rococo-system-emulated-network = { path = "../../../networks/rococo-system" } +asset-test-utils = { workspace = true, default-features = true } +parachains-common = { workspace = true, default-features = true } +people-rococo-runtime = { workspace = true } +emulated-integration-tests-common = { workspace = true } +rococo-system-emulated-network = { workspace = true } diff --git a/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/Cargo.toml b/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/Cargo.toml index 6eab6f52aa72172ecc19fa891109fc9df859ec3c..58dbf82f222f10774ae702e9ce53fd589739efd8 100644 --- a/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/tests/people/people-westend/Cargo.toml @@ -8,25 +8,25 @@ description = "People Westend runtime integration tests with xcm-emulator" publish = false [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } +codec = { workspace = true } # Substrate -sp-runtime = { path = "../../../../../../../substrate/primitives/runtime", default-features = false } -frame-support = { path = "../../../../../../../substrate/frame/support", default-features = false } -pallet-balances = { path = "../../../../../../../substrate/frame/balances", default-features = false } -pallet-message-queue = { path = "../../../../../../../substrate/frame/message-queue", default-features = false } -pallet-identity = { path = "../../../../../../../substrate/frame/identity", default-features = false } +sp-runtime = { workspace = true } +frame-support = { workspace = true } +pallet-balances = { workspace = true } +pallet-message-queue = { workspace = true } +pallet-identity = { workspace = true } # Polkadot -xcm = { package = "staging-xcm", path = "../../../../../../../polkadot/xcm", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../../../../polkadot/xcm/xcm-executor", default-features = false } -westend-runtime = { path = "../../../../../../../polkadot/runtime/westend" } -westend-runtime-constants = { path = "../../../../../../../polkadot/runtime/westend/constants" } -polkadot-runtime-common = { path = "../../../../../../../polkadot/runtime/common" } +xcm = { workspace = true } +xcm-executor = { workspace = true } +westend-runtime = { workspace = true } +westend-runtime-constants = { workspace = true, default-features = true } +polkadot-runtime-common = { workspace = true, default-features = true } # Cumulus -asset-test-utils = { path = "../../../../../runtimes/assets/test-utils" } -parachains-common = { path = "../../../../../common" } -people-westend-runtime = { path = "../../../../../runtimes/people/people-westend" } -emulated-integration-tests-common = { path = "../../../common", default-features = false } -westend-system-emulated-network = { path = "../../../networks/westend-system" } +asset-test-utils = { workspace = true, default-features = true } +parachains-common = { workspace = true, default-features = true } +people-westend-runtime = { workspace = true } +emulated-integration-tests-common = { workspace = true } +westend-system-emulated-network = { workspace = true } diff --git a/cumulus/parachains/pallets/collective-content/Cargo.toml b/cumulus/parachains/pallets/collective-content/Cargo.toml index 92e0a54631394154634900829c708431b2931b67..61cbe7850090195af08bccfd3f0b172dcbb85b60 100644 --- a/cumulus/parachains/pallets/collective-content/Cargo.toml +++ b/cumulus/parachains/pallets/collective-content/Cargo.toml @@ -10,19 +10,19 @@ license = "Apache-2.0" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive", "max-encoded-len"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive", "max-encoded-len"], workspace = true } +scale-info = { features = ["derive"], workspace = true } -frame-benchmarking = { path = "../../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-support = { path = "../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../substrate/frame/system", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } -sp-core = { path = "../../../../substrate/primitives/core", default-features = false } -sp-runtime = { path = "../../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../../substrate/primitives/std", default-features = false } +sp-core = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -sp-io = { path = "../../../../substrate/primitives/io", default-features = false } +sp-io = { workspace = true } [features] default = ["std"] diff --git a/cumulus/parachains/pallets/parachain-info/Cargo.toml b/cumulus/parachains/pallets/parachain-info/Cargo.toml index 01ee12bf4e719a9fde63fa4adb43bc6ff4e5c3ea..7369c3a2c157624b7af48f860c73ba61716a1038 100644 --- a/cumulus/parachains/pallets/parachain-info/Cargo.toml +++ b/cumulus/parachains/pallets/parachain-info/Cargo.toml @@ -10,16 +10,16 @@ description = "Pallet to store the parachain ID" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } -frame-support = { path = "../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../substrate/frame/system", default-features = false } +frame-support = { workspace = true } +frame-system = { workspace = true } -sp-runtime = { path = "../../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../../substrate/primitives/std", default-features = false } +sp-runtime = { workspace = true } +sp-std = { workspace = true } -cumulus-primitives-core = { path = "../../../primitives/core", default-features = false } +cumulus-primitives-core = { workspace = true } [features] default = ["std"] diff --git a/cumulus/parachains/pallets/ping/Cargo.toml b/cumulus/parachains/pallets/ping/Cargo.toml index f51946e9ebd5d2c5fd471683a217fe2dbe8f2f61..f74328207b84387f969bcf94d81d6bef705f877a 100644 --- a/cumulus/parachains/pallets/ping/Cargo.toml +++ b/cumulus/parachains/pallets/ping/Cargo.toml @@ -10,18 +10,18 @@ description = "Ping Pallet for Cumulus XCM/UMP testing." workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } -sp-std = { path = "../../../../substrate/primitives/std", default-features = false } -sp-runtime = { path = "../../../../substrate/primitives/runtime", default-features = false } -frame-support = { path = "../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../substrate/frame/system", default-features = false } +sp-std = { workspace = true } +sp-runtime = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } -xcm = { package = "staging-xcm", path = "../../../../polkadot/xcm", default-features = false } +xcm = { workspace = true } -cumulus-primitives-core = { path = "../../../primitives/core", default-features = false } -cumulus-pallet-xcm = { path = "../../../pallets/xcm", default-features = false } +cumulus-primitives-core = { workspace = true } +cumulus-pallet-xcm = { workspace = true } [features] default = ["std"] diff --git a/cumulus/parachains/runtimes/assets/asset-hub-rococo/Cargo.toml b/cumulus/parachains/runtimes/assets/asset-hub-rococo/Cargo.toml index a880730ddacfdde9fcbda95fefb457af031b3da7..9ef0aa0072c96a3077c2a9d1c8b3793521938ff5 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/Cargo.toml +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/Cargo.toml @@ -10,96 +10,97 @@ license = "Apache-2.0" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive", "max-encoded-len"] } -hex-literal = { version = "0.4.1" } +codec = { features = ["derive", "max-encoded-len"], workspace = true } +hex-literal = { workspace = true, default-features = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } # Substrate -frame-benchmarking = { path = "../../../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-executive = { path = "../../../../../substrate/frame/executive", default-features = false } -frame-metadata-hash-extension = { path = "../../../../../substrate/frame/metadata-hash-extension", default-features = false } -frame-support = { path = "../../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../../substrate/frame/system", default-features = false } -frame-system-benchmarking = { path = "../../../../../substrate/frame/system/benchmarking", default-features = false, optional = true } -frame-system-rpc-runtime-api = { path = "../../../../../substrate/frame/system/rpc/runtime-api", default-features = false } -frame-try-runtime = { path = "../../../../../substrate/frame/try-runtime", default-features = false, optional = true } -pallet-asset-conversion-tx-payment = { path = "../../../../../substrate/frame/transaction-payment/asset-conversion-tx-payment", default-features = false } -pallet-assets = { path = "../../../../../substrate/frame/assets", default-features = false } -pallet-asset-conversion-ops = { path = "../../../../../substrate/frame/asset-conversion/ops", default-features = false } -pallet-asset-conversion = { path = "../../../../../substrate/frame/asset-conversion", default-features = false } -pallet-aura = { path = "../../../../../substrate/frame/aura", default-features = false } -pallet-authorship = { path = "../../../../../substrate/frame/authorship", default-features = false } -pallet-balances = { path = "../../../../../substrate/frame/balances", default-features = false } -pallet-message-queue = { path = "../../../../../substrate/frame/message-queue", default-features = false } -pallet-multisig = { path = "../../../../../substrate/frame/multisig", default-features = false } -pallet-nft-fractionalization = { path = "../../../../../substrate/frame/nft-fractionalization", default-features = false } -pallet-nfts = { path = "../../../../../substrate/frame/nfts", default-features = false } -pallet-nfts-runtime-api = { path = "../../../../../substrate/frame/nfts/runtime-api", default-features = false } -pallet-proxy = { path = "../../../../../substrate/frame/proxy", default-features = false } -pallet-session = { path = "../../../../../substrate/frame/session", default-features = false } -pallet-timestamp = { path = "../../../../../substrate/frame/timestamp", default-features = false } -pallet-transaction-payment = { path = "../../../../../substrate/frame/transaction-payment", default-features = false } -pallet-transaction-payment-rpc-runtime-api = { path = "../../../../../substrate/frame/transaction-payment/rpc/runtime-api", default-features = false } -pallet-uniques = { path = "../../../../../substrate/frame/uniques", default-features = false } -pallet-utility = { path = "../../../../../substrate/frame/utility", default-features = false } -sp-api = { path = "../../../../../substrate/primitives/api", default-features = false } -sp-block-builder = { path = "../../../../../substrate/primitives/block-builder", default-features = false } -sp-consensus-aura = { path = "../../../../../substrate/primitives/consensus/aura", default-features = false } -sp-core = { path = "../../../../../substrate/primitives/core", default-features = false } -sp-inherents = { path = "../../../../../substrate/primitives/inherents", default-features = false } -sp-genesis-builder = { path = "../../../../../substrate/primitives/genesis-builder", default-features = false } -sp-offchain = { path = "../../../../../substrate/primitives/offchain", default-features = false } -sp-runtime = { path = "../../../../../substrate/primitives/runtime", default-features = false } -sp-session = { path = "../../../../../substrate/primitives/session", default-features = false } -sp-std = { path = "../../../../../substrate/primitives/std", default-features = false } -sp-storage = { path = "../../../../../substrate/primitives/storage", default-features = false } -sp-transaction-pool = { path = "../../../../../substrate/primitives/transaction-pool", default-features = false } -sp-version = { path = "../../../../../substrate/primitives/version", default-features = false } -sp-weights = { path = "../../../../../substrate/primitives/weights", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +frame-executive = { workspace = true } +frame-metadata-hash-extension = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +frame-system-benchmarking = { optional = true, workspace = true } +frame-system-rpc-runtime-api = { workspace = true } +frame-try-runtime = { optional = true, workspace = true } +pallet-asset-conversion-tx-payment = { workspace = true } +pallet-assets = { workspace = true } +pallet-asset-conversion-ops = { workspace = true } +pallet-asset-conversion = { workspace = true } +pallet-assets-freezer = { workspace = true } +pallet-aura = { workspace = true } +pallet-authorship = { workspace = true } +pallet-balances = { workspace = true } +pallet-message-queue = { workspace = true } +pallet-multisig = { workspace = true } +pallet-nft-fractionalization = { workspace = true } +pallet-nfts = { workspace = true } +pallet-nfts-runtime-api = { workspace = true } +pallet-proxy = { workspace = true } +pallet-session = { workspace = true } +pallet-timestamp = { workspace = true } +pallet-transaction-payment = { workspace = true } +pallet-transaction-payment-rpc-runtime-api = { workspace = true } +pallet-uniques = { workspace = true } +pallet-utility = { workspace = true } +sp-api = { workspace = true } +sp-block-builder = { workspace = true } +sp-consensus-aura = { workspace = true } +sp-core = { workspace = true } +sp-inherents = { workspace = true } +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 } +sp-weights = { workspace = true } # num-traits feature needed for dex integer sq root: -primitive-types = { version = "0.12.1", default-features = false, features = ["codec", "num-traits", "scale-info"] } +primitive-types = { features = ["codec", "num-traits", "scale-info"], workspace = true } # Polkadot -rococo-runtime-constants = { path = "../../../../../polkadot/runtime/rococo/constants", default-features = false } -pallet-xcm = { path = "../../../../../polkadot/xcm/pallet-xcm", default-features = false } -pallet-xcm-benchmarks = { path = "../../../../../polkadot/xcm/pallet-xcm-benchmarks", default-features = false, optional = true } -polkadot-parachain-primitives = { path = "../../../../../polkadot/parachain", default-features = false } -polkadot-runtime-common = { path = "../../../../../polkadot/runtime/common", default-features = false } -xcm = { package = "staging-xcm", path = "../../../../../polkadot/xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../../../polkadot/xcm/xcm-builder", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../../polkadot/xcm/xcm-executor", default-features = false } -xcm-fee-payment-runtime-api = { path = "../../../../../polkadot/xcm/xcm-fee-payment-runtime-api", default-features = false } +rococo-runtime-constants = { workspace = true } +pallet-xcm = { workspace = true } +pallet-xcm-benchmarks = { optional = true, workspace = true } +polkadot-parachain-primitives = { workspace = true } +polkadot-runtime-common = { workspace = true } +xcm = { workspace = true } +xcm-builder = { workspace = true } +xcm-executor = { workspace = true } +xcm-runtime-apis = { workspace = true } # Cumulus -cumulus-pallet-aura-ext = { path = "../../../../pallets/aura-ext", default-features = false } -cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false } -cumulus-pallet-session-benchmarking = { path = "../../../../pallets/session-benchmarking", default-features = false } -cumulus-pallet-xcm = { path = "../../../../pallets/xcm", default-features = false } -cumulus-pallet-xcmp-queue = { path = "../../../../pallets/xcmp-queue", default-features = false, features = ["bridging"] } -cumulus-primitives-aura = { path = "../../../../primitives/aura", default-features = false } -cumulus-primitives-core = { path = "../../../../primitives/core", default-features = false } -cumulus-primitives-utility = { path = "../../../../primitives/utility", default-features = false } -cumulus-primitives-storage-weight-reclaim = { path = "../../../../primitives/storage-weight-reclaim", default-features = false } -pallet-collator-selection = { path = "../../../../pallets/collator-selection", default-features = false } -parachain-info = { package = "staging-parachain-info", path = "../../../pallets/parachain-info", default-features = false } -parachains-common = { path = "../../../common", default-features = false } -testnet-parachains-constants = { path = "../../constants", default-features = false, features = ["rococo"] } -assets-common = { path = "../common", default-features = false } +cumulus-pallet-aura-ext = { workspace = true } +cumulus-pallet-parachain-system = { workspace = true } +cumulus-pallet-session-benchmarking = { workspace = true } +cumulus-pallet-xcm = { workspace = true } +cumulus-pallet-xcmp-queue = { features = ["bridging"], workspace = true } +cumulus-primitives-aura = { workspace = true } +cumulus-primitives-core = { workspace = true } +cumulus-primitives-utility = { workspace = true } +cumulus-primitives-storage-weight-reclaim = { workspace = true } +pallet-collator-selection = { workspace = true } +parachain-info = { workspace = true } +parachains-common = { workspace = true } +testnet-parachains-constants = { features = ["rococo"], workspace = true } +assets-common = { workspace = true } # Bridges -pallet-xcm-bridge-hub-router = { path = "../../../../../bridges/modules/xcm-bridge-hub-router", default-features = false } -bp-asset-hub-rococo = { path = "../../../../../bridges/chains/chain-asset-hub-rococo", default-features = false } -bp-asset-hub-westend = { path = "../../../../../bridges/chains/chain-asset-hub-westend", default-features = false } -bp-bridge-hub-rococo = { path = "../../../../../bridges/chains/chain-bridge-hub-rococo", default-features = false } -bp-bridge-hub-westend = { path = "../../../../../bridges/chains/chain-bridge-hub-westend", default-features = false } -snowbridge-router-primitives = { path = "../../../../../bridges/snowbridge/primitives/router", default-features = false } +pallet-xcm-bridge-hub-router = { workspace = true } +bp-asset-hub-rococo = { workspace = true } +bp-asset-hub-westend = { workspace = true } +bp-bridge-hub-rococo = { workspace = true } +bp-bridge-hub-westend = { workspace = true } +snowbridge-router-primitives = { workspace = true } [dev-dependencies] -asset-test-utils = { path = "../test-utils" } +asset-test-utils = { workspace = true, default-features = true } [build-dependencies] -substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } +substrate-wasm-builder = { optional = true, workspace = true, default-features = true } [features] default = ["std"] @@ -116,6 +117,7 @@ runtime-benchmarks = [ "frame-system/runtime-benchmarks", "pallet-asset-conversion-ops/runtime-benchmarks", "pallet-asset-conversion/runtime-benchmarks", + "pallet-assets-freezer/runtime-benchmarks", "pallet-assets/runtime-benchmarks", "pallet-balances/runtime-benchmarks", "pallet-collator-selection/runtime-benchmarks", @@ -137,7 +139,7 @@ runtime-benchmarks = [ "sp-runtime/runtime-benchmarks", "xcm-builder/runtime-benchmarks", "xcm-executor/runtime-benchmarks", - "xcm-fee-payment-runtime-api/runtime-benchmarks", + "xcm-runtime-apis/runtime-benchmarks", ] try-runtime = [ "cumulus-pallet-aura-ext/try-runtime", @@ -151,6 +153,7 @@ try-runtime = [ "pallet-asset-conversion-ops/try-runtime", "pallet-asset-conversion-tx-payment/try-runtime", "pallet-asset-conversion/try-runtime", + "pallet-assets-freezer/try-runtime", "pallet-assets/try-runtime", "pallet-aura/try-runtime", "pallet-authorship/try-runtime", @@ -200,6 +203,7 @@ std = [ "pallet-asset-conversion-ops/std", "pallet-asset-conversion-tx-payment/std", "pallet-asset-conversion/std", + "pallet-assets-freezer/std", "pallet-assets/std", "pallet-aura/std", "pallet-authorship/std", @@ -246,7 +250,7 @@ std = [ "testnet-parachains-constants/std", "xcm-builder/std", "xcm-executor/std", - "xcm-fee-payment-runtime-api/std", + "xcm-runtime-apis/std", "xcm/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 d75b07bd2b9fce6cd52c0aa3d93e3aa3d0dff39f..836939f1af4debdd3a513c55b95690ad5f634a78 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-rococo/src/lib.rs @@ -100,7 +100,7 @@ use xcm::{ latest::prelude::{AssetId, BodyId}, VersionedAssetId, VersionedAssets, VersionedLocation, VersionedXcm, }; -use xcm_fee_payment_runtime_api::{ +use xcm_runtime_apis::{ dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects}, fees::Error as XcmPaymentApiError, }; @@ -118,7 +118,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("statemine"), impl_name: create_runtime_str!("statemine"), authoring_version: 1, - spec_version: 1_012_000, + spec_version: 1_013_000, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 16, @@ -257,7 +257,7 @@ impl pallet_assets::Config for Runtime { type MetadataDepositPerByte = MetadataDepositPerByte; type ApprovalDeposit = ApprovalDeposit; type StringLimit = AssetsStringLimit; - type Freezer = (); + type Freezer = AssetsFreezer; type Extra = (); type WeightInfo = weights::pallet_assets_local::WeightInfo; type CallbackHandle = (); @@ -267,6 +267,13 @@ impl pallet_assets::Config for Runtime { type BenchmarkHelper = (); } +// Allow Freezes for the `Assets` pallet +pub type AssetsFreezerInstance = pallet_assets_freezer::Instance1; +impl pallet_assets_freezer::Config for Runtime { + type RuntimeFreezeReason = RuntimeFreezeReason; + type RuntimeEvent = RuntimeEvent; +} + parameter_types! { pub const AssetConversionPalletId: PalletId = PalletId(*b"py/ascon"); pub const LiquidityWithdrawalFee: Permill = Permill::from_percent(0); @@ -295,7 +302,7 @@ impl pallet_assets::Config for Runtime { type MetadataDepositPerByte = ConstU128<0>; type ApprovalDeposit = ApprovalDeposit; type StringLimit = ConstU32<50>; - type Freezer = (); + type Freezer = PoolAssetsFreezer; type Extra = (); type WeightInfo = weights::pallet_assets_pool::WeightInfo; type CallbackHandle = (); @@ -303,6 +310,13 @@ impl pallet_assets::Config for Runtime { type BenchmarkHelper = (); } +// Allow Freezes for the `PoolAssets` pallet +pub type PoolAssetsFreezerInstance = pallet_assets_freezer::Instance3; +impl pallet_assets_freezer::Config for Runtime { + type RuntimeFreezeReason = RuntimeFreezeReason; + type RuntimeEvent = RuntimeEvent; +} + /// Union fungibles implementation for `Assets` and `ForeignAssets`. pub type LocalAndForeignAssets = fungibles::UnionOf< Assets, @@ -411,7 +425,7 @@ impl pallet_assets::Config for Runtime { type MetadataDepositPerByte = ForeignAssetsMetadataDepositPerByte; type ApprovalDeposit = ForeignAssetsApprovalDeposit; type StringLimit = ForeignAssetsAssetsStringLimit; - type Freezer = (); + type Freezer = ForeignAssetsFreezer; type Extra = (); type WeightInfo = weights::pallet_assets_foreign::WeightInfo; type CallbackHandle = (); @@ -421,6 +435,13 @@ impl pallet_assets::Config for Runtime { type BenchmarkHelper = xcm_config::XcmBenchmarkHelper; } +// Allow Freezes for the `ForeignAssets` pallet +pub type ForeignAssetsFreezerInstance = pallet_assets_freezer::Instance2; +impl pallet_assets_freezer::Config for Runtime { + type RuntimeFreezeReason = RuntimeFreezeReason; + type RuntimeEvent = RuntimeEvent; +} + parameter_types! { // One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes. pub const DepositBase: Balance = deposit(1, 88); @@ -953,6 +974,9 @@ construct_runtime!( NftFractionalization: pallet_nft_fractionalization = 54, PoolAssets: pallet_assets:: = 55, AssetConversion: pallet_asset_conversion = 56, + AssetsFreezer: pallet_assets_freezer:: = 57, + ForeignAssetsFreezer: pallet_assets_freezer:: = 58, + PoolAssetsFreezer: pallet_assets_freezer:: = 59, // TODO: the pallet instance should be removed once all pools have migrated // to the new account IDs. @@ -1298,7 +1322,7 @@ impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::fees::XcmPaymentApi for Runtime { + impl xcm_runtime_apis::fees::XcmPaymentApi for Runtime { fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result, XcmPaymentApiError> { let acceptable_assets = vec![AssetId(xcm_config::TokenLocation::get())]; PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets) @@ -1311,11 +1335,11 @@ impl_runtime_apis! { Ok(WeightToFee::weight_to_fee(&weight)) }, Ok(asset_id) => { - log::trace!(target: "xcm::xcm_fee_payment_runtime_api", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); + log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); Err(XcmPaymentApiError::AssetNotFound) }, Err(_) => { - log::trace!(target: "xcm::xcm_fee_payment_runtime_api", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!"); + log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!"); Err(XcmPaymentApiError::VersionedConversionFailed) } } @@ -1330,7 +1354,7 @@ impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::dry_run::DryRunApi for Runtime { + impl xcm_runtime_apis::dry_run::DryRunApi for Runtime { fn dry_run_call(origin: OriginCaller, call: RuntimeCall) -> Result, XcmDryRunApiError> { PolkadotXcm::dry_run_call::(origin, call) } @@ -1340,6 +1364,18 @@ impl_runtime_apis! { } } + impl xcm_runtime_apis::conversions::LocationToAccountApi for Runtime { + fn convert_location(location: VersionedLocation) -> Result< + AccountId, + xcm_runtime_apis::conversions::Error + > { + xcm_runtime_apis::conversions::LocationToAccountHelper::< + AccountId, + xcm_config::LocationToAccountId, + >::convert_location(location) + } + } + impl cumulus_primitives_core::CollectCollationInfo for Runtime { fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { ParachainSystem::collect_collation_info(header) diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/Cargo.toml b/cumulus/parachains/runtimes/assets/asset-hub-westend/Cargo.toml index 953f6a8b4009a5ab86cc7d1177dfbb993d291c8d..7e618d950b19a86a46903d3b8351c1c1be542cb9 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/Cargo.toml +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/Cargo.toml @@ -10,95 +10,96 @@ license = "Apache-2.0" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive", "max-encoded-len"] } -hex-literal = { version = "0.4.1" } +codec = { features = ["derive", "max-encoded-len"], workspace = true } +hex-literal = { workspace = true, default-features = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } # Substrate -frame-benchmarking = { path = "../../../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-executive = { path = "../../../../../substrate/frame/executive", default-features = false } -frame-metadata-hash-extension = { path = "../../../../../substrate/frame/metadata-hash-extension", default-features = false } -frame-support = { path = "../../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../../substrate/frame/system", default-features = false } -frame-system-benchmarking = { path = "../../../../../substrate/frame/system/benchmarking", default-features = false, optional = true } -frame-system-rpc-runtime-api = { path = "../../../../../substrate/frame/system/rpc/runtime-api", default-features = false } -frame-try-runtime = { path = "../../../../../substrate/frame/try-runtime", default-features = false, optional = true } -pallet-asset-conversion-ops = { path = "../../../../../substrate/frame/asset-conversion/ops", default-features = false } -pallet-asset-conversion-tx-payment = { path = "../../../../../substrate/frame/transaction-payment/asset-conversion-tx-payment", default-features = false } -pallet-assets = { path = "../../../../../substrate/frame/assets", default-features = false } -pallet-asset-conversion = { path = "../../../../../substrate/frame/asset-conversion", default-features = false } -pallet-aura = { path = "../../../../../substrate/frame/aura", default-features = false } -pallet-authorship = { path = "../../../../../substrate/frame/authorship", default-features = false } -pallet-balances = { path = "../../../../../substrate/frame/balances", default-features = false } -pallet-multisig = { path = "../../../../../substrate/frame/multisig", default-features = false } -pallet-nft-fractionalization = { path = "../../../../../substrate/frame/nft-fractionalization", default-features = false } -pallet-nfts = { path = "../../../../../substrate/frame/nfts", default-features = false } -pallet-nfts-runtime-api = { path = "../../../../../substrate/frame/nfts/runtime-api", default-features = false } -pallet-proxy = { path = "../../../../../substrate/frame/proxy", default-features = false } -pallet-session = { path = "../../../../../substrate/frame/session", default-features = false } -pallet-state-trie-migration = { path = "../../../../../substrate/frame/state-trie-migration", default-features = false } -pallet-timestamp = { path = "../../../../../substrate/frame/timestamp", default-features = false } -pallet-transaction-payment = { path = "../../../../../substrate/frame/transaction-payment", default-features = false } -pallet-transaction-payment-rpc-runtime-api = { path = "../../../../../substrate/frame/transaction-payment/rpc/runtime-api", default-features = false } -pallet-uniques = { path = "../../../../../substrate/frame/uniques", default-features = false } -pallet-utility = { path = "../../../../../substrate/frame/utility", default-features = false } -sp-api = { path = "../../../../../substrate/primitives/api", default-features = false } -sp-block-builder = { path = "../../../../../substrate/primitives/block-builder", default-features = false } -sp-consensus-aura = { path = "../../../../../substrate/primitives/consensus/aura", default-features = false } -sp-core = { path = "../../../../../substrate/primitives/core", default-features = false } -sp-genesis-builder = { path = "../../../../../substrate/primitives/genesis-builder", default-features = false } -sp-inherents = { path = "../../../../../substrate/primitives/inherents", default-features = false } -sp-offchain = { path = "../../../../../substrate/primitives/offchain", default-features = false } -sp-runtime = { path = "../../../../../substrate/primitives/runtime", default-features = false } -sp-session = { path = "../../../../../substrate/primitives/session", default-features = false } -sp-std = { path = "../../../../../substrate/primitives/std", default-features = false } -sp-storage = { path = "../../../../../substrate/primitives/storage", default-features = false } -sp-transaction-pool = { path = "../../../../../substrate/primitives/transaction-pool", default-features = false } -sp-version = { path = "../../../../../substrate/primitives/version", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +frame-executive = { workspace = true } +frame-metadata-hash-extension = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +frame-system-benchmarking = { optional = true, workspace = true } +frame-system-rpc-runtime-api = { workspace = true } +frame-try-runtime = { optional = true, workspace = true } +pallet-asset-conversion-ops = { workspace = true } +pallet-asset-conversion-tx-payment = { workspace = true } +pallet-assets = { workspace = true } +pallet-asset-conversion = { workspace = true } +pallet-assets-freezer = { workspace = true } +pallet-aura = { workspace = true } +pallet-authorship = { workspace = true } +pallet-balances = { workspace = true } +pallet-multisig = { workspace = true } +pallet-nft-fractionalization = { workspace = true } +pallet-nfts = { workspace = true } +pallet-nfts-runtime-api = { workspace = true } +pallet-proxy = { workspace = true } +pallet-session = { workspace = true } +pallet-state-trie-migration = { workspace = true } +pallet-timestamp = { workspace = true } +pallet-transaction-payment = { workspace = true } +pallet-transaction-payment-rpc-runtime-api = { workspace = true } +pallet-uniques = { workspace = true } +pallet-utility = { workspace = true } +sp-api = { workspace = true } +sp-block-builder = { workspace = true } +sp-consensus-aura = { workspace = true } +sp-core = { workspace = true } +sp-genesis-builder = { workspace = true } +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 } # num-traits feature needed for dex integer sq root: -primitive-types = { version = "0.12.1", default-features = false, features = ["codec", "num-traits", "scale-info"] } +primitive-types = { features = ["codec", "num-traits", "scale-info"], workspace = true } # Polkadot -pallet-xcm = { path = "../../../../../polkadot/xcm/pallet-xcm", default-features = false } -pallet-xcm-benchmarks = { path = "../../../../../polkadot/xcm/pallet-xcm-benchmarks", default-features = false, optional = true } -polkadot-parachain-primitives = { path = "../../../../../polkadot/parachain", default-features = false } -polkadot-runtime-common = { path = "../../../../../polkadot/runtime/common", default-features = false } -westend-runtime-constants = { path = "../../../../../polkadot/runtime/westend/constants", default-features = false } -xcm = { package = "staging-xcm", path = "../../../../../polkadot/xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../../../polkadot/xcm/xcm-builder", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../../polkadot/xcm/xcm-executor", default-features = false } -xcm-fee-payment-runtime-api = { path = "../../../../../polkadot/xcm/xcm-fee-payment-runtime-api", default-features = false } +pallet-xcm = { workspace = true } +pallet-xcm-benchmarks = { optional = true, workspace = true } +polkadot-parachain-primitives = { workspace = true } +polkadot-runtime-common = { workspace = true } +westend-runtime-constants = { workspace = true } +xcm = { workspace = true } +xcm-builder = { workspace = true } +xcm-executor = { workspace = true } +xcm-runtime-apis = { workspace = true } # Cumulus -cumulus-pallet-aura-ext = { path = "../../../../pallets/aura-ext", default-features = false } -pallet-message-queue = { path = "../../../../../substrate/frame/message-queue", default-features = false } -cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false } -cumulus-pallet-session-benchmarking = { path = "../../../../pallets/session-benchmarking", default-features = false } -cumulus-pallet-xcm = { path = "../../../../pallets/xcm", default-features = false } -cumulus-pallet-xcmp-queue = { path = "../../../../pallets/xcmp-queue", default-features = false, features = ["bridging"] } -cumulus-primitives-aura = { path = "../../../../primitives/aura", default-features = false } -cumulus-primitives-core = { path = "../../../../primitives/core", default-features = false } -cumulus-primitives-utility = { path = "../../../../primitives/utility", default-features = false } -cumulus-primitives-storage-weight-reclaim = { path = "../../../../primitives/storage-weight-reclaim", default-features = false } -pallet-collator-selection = { path = "../../../../pallets/collator-selection", default-features = false } -parachain-info = { package = "staging-parachain-info", path = "../../../pallets/parachain-info", default-features = false } -parachains-common = { path = "../../../common", default-features = false } -testnet-parachains-constants = { path = "../../constants", default-features = false, features = ["westend"] } -assets-common = { path = "../common", default-features = false } +cumulus-pallet-aura-ext = { workspace = true } +pallet-message-queue = { workspace = true } +cumulus-pallet-parachain-system = { workspace = true } +cumulus-pallet-session-benchmarking = { workspace = true } +cumulus-pallet-xcm = { workspace = true } +cumulus-pallet-xcmp-queue = { features = ["bridging"], workspace = true } +cumulus-primitives-aura = { workspace = true } +cumulus-primitives-core = { workspace = true } +cumulus-primitives-utility = { workspace = true } +cumulus-primitives-storage-weight-reclaim = { workspace = true } +pallet-collator-selection = { workspace = true } +parachain-info = { workspace = true } +parachains-common = { workspace = true } +testnet-parachains-constants = { features = ["westend"], workspace = true } +assets-common = { workspace = true } # Bridges -pallet-xcm-bridge-hub-router = { path = "../../../../../bridges/modules/xcm-bridge-hub-router", default-features = false } -bp-asset-hub-rococo = { path = "../../../../../bridges/chains/chain-asset-hub-rococo", default-features = false } -bp-asset-hub-westend = { path = "../../../../../bridges/chains/chain-asset-hub-westend", default-features = false } -bp-bridge-hub-rococo = { path = "../../../../../bridges/chains/chain-bridge-hub-rococo", default-features = false } -bp-bridge-hub-westend = { path = "../../../../../bridges/chains/chain-bridge-hub-westend", default-features = false } +pallet-xcm-bridge-hub-router = { workspace = true } +bp-asset-hub-rococo = { workspace = true } +bp-asset-hub-westend = { workspace = true } +bp-bridge-hub-rococo = { workspace = true } +bp-bridge-hub-westend = { workspace = true } [dev-dependencies] -asset-test-utils = { path = "../test-utils" } +asset-test-utils = { workspace = true, default-features = true } [build-dependencies] -substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } +substrate-wasm-builder = { optional = true, workspace = true, default-features = true } [features] default = ["std"] @@ -115,6 +116,7 @@ runtime-benchmarks = [ "frame-system/runtime-benchmarks", "pallet-asset-conversion-ops/runtime-benchmarks", "pallet-asset-conversion/runtime-benchmarks", + "pallet-assets-freezer/runtime-benchmarks", "pallet-assets/runtime-benchmarks", "pallet-balances/runtime-benchmarks", "pallet-collator-selection/runtime-benchmarks", @@ -136,7 +138,7 @@ runtime-benchmarks = [ "sp-runtime/runtime-benchmarks", "xcm-builder/runtime-benchmarks", "xcm-executor/runtime-benchmarks", - "xcm-fee-payment-runtime-api/runtime-benchmarks", + "xcm-runtime-apis/runtime-benchmarks", ] try-runtime = [ "cumulus-pallet-aura-ext/try-runtime", @@ -150,6 +152,7 @@ try-runtime = [ "pallet-asset-conversion-ops/try-runtime", "pallet-asset-conversion-tx-payment/try-runtime", "pallet-asset-conversion/try-runtime", + "pallet-assets-freezer/try-runtime", "pallet-assets/try-runtime", "pallet-aura/try-runtime", "pallet-authorship/try-runtime", @@ -200,6 +203,7 @@ std = [ "pallet-asset-conversion-ops/std", "pallet-asset-conversion-tx-payment/std", "pallet-asset-conversion/std", + "pallet-assets-freezer/std", "pallet-assets/std", "pallet-aura/std", "pallet-authorship/std", @@ -245,7 +249,7 @@ std = [ "westend-runtime-constants/std", "xcm-builder/std", "xcm-executor/std", - "xcm-fee-payment-runtime-api/std", + "xcm-runtime-apis/std", "xcm/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 e9c2b10f719daaea30219146096da76d4147fdac..14cae3b53967f1fe1738fe2eeaf879a011a01e82 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs @@ -85,10 +85,10 @@ pub use sp_runtime::BuildStorage; use assets_common::{foreign_creators::ForeignCreators, matching::FromSiblingParachain}; use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate}; -use xcm::prelude::{VersionedAssetId, VersionedAssets, VersionedLocation, VersionedXcm}; - -// We exclude `Assets` since it's the name of a pallet -use xcm::latest::prelude::AssetId; +use xcm::{ + latest::prelude::AssetId, + prelude::{VersionedAssetId, VersionedAssets, VersionedLocation, VersionedXcm}, +}; #[cfg(feature = "runtime-benchmarks")] use xcm::latest::prelude::{ @@ -96,7 +96,7 @@ use xcm::latest::prelude::{ NetworkId, NonFungible, Parent, ParentThen, Response, XCM_VERSION, }; -use xcm_fee_payment_runtime_api::{ +use xcm_runtime_apis::{ dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects}, fees::Error as XcmPaymentApiError, }; @@ -117,7 +117,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("westmint"), impl_name: create_runtime_str!("westmint"), authoring_version: 1, - spec_version: 1_012_000, + spec_version: 1_013_000, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 16, @@ -255,7 +255,7 @@ impl pallet_assets::Config for Runtime { type MetadataDepositPerByte = MetadataDepositPerByte; type ApprovalDeposit = ApprovalDeposit; type StringLimit = AssetsStringLimit; - type Freezer = (); + type Freezer = AssetsFreezer; type Extra = (); type WeightInfo = weights::pallet_assets_local::WeightInfo; type CallbackHandle = (); @@ -265,6 +265,13 @@ impl pallet_assets::Config for Runtime { type BenchmarkHelper = (); } +// Allow Freezes for the `Assets` pallet +pub type AssetsFreezerInstance = pallet_assets_freezer::Instance1; +impl pallet_assets_freezer::Config for Runtime { + type RuntimeFreezeReason = RuntimeFreezeReason; + type RuntimeEvent = RuntimeEvent; +} + parameter_types! { pub const AssetConversionPalletId: PalletId = PalletId(*b"py/ascon"); pub const LiquidityWithdrawalFee: Permill = Permill::from_percent(0); @@ -292,7 +299,7 @@ impl pallet_assets::Config for Runtime { type MetadataDepositPerByte = ConstU128<0>; type ApprovalDeposit = ConstU128<0>; type StringLimit = ConstU32<50>; - type Freezer = (); + type Freezer = PoolAssetsFreezer; type Extra = (); type WeightInfo = weights::pallet_assets_pool::WeightInfo; type CallbackHandle = (); @@ -300,6 +307,13 @@ impl pallet_assets::Config for Runtime { type BenchmarkHelper = (); } +// Allow Freezes for the `PoolAssets` pallet +pub type PoolAssetsFreezerInstance = pallet_assets_freezer::Instance3; +impl pallet_assets_freezer::Config for Runtime { + type RuntimeFreezeReason = RuntimeFreezeReason; + type RuntimeEvent = RuntimeEvent; +} + /// Union fungibles implementation for `Assets` and `ForeignAssets`. pub type LocalAndForeignAssets = fungibles::UnionOf< Assets, @@ -405,7 +419,7 @@ impl pallet_assets::Config for Runtime { type MetadataDepositPerByte = ForeignAssetsMetadataDepositPerByte; type ApprovalDeposit = ForeignAssetsApprovalDeposit; type StringLimit = ForeignAssetsAssetsStringLimit; - type Freezer = (); + type Freezer = ForeignAssetsFreezer; type Extra = (); type WeightInfo = weights::pallet_assets_foreign::WeightInfo; type CallbackHandle = (); @@ -415,6 +429,13 @@ impl pallet_assets::Config for Runtime { type BenchmarkHelper = xcm_config::XcmBenchmarkHelper; } +// Allow Freezes for the `ForeignAssets` pallet +pub type ForeignAssetsFreezerInstance = pallet_assets_freezer::Instance2; +impl pallet_assets_freezer::Config for Runtime { + type RuntimeFreezeReason = RuntimeFreezeReason; + type RuntimeEvent = RuntimeEvent; +} + parameter_types! { // One storage item; key size is 32; value is size 4+4+16+32 bytes = 56 bytes. pub const DepositBase: Balance = deposit(1, 88); @@ -943,6 +964,9 @@ construct_runtime!( NftFractionalization: pallet_nft_fractionalization = 54, PoolAssets: pallet_assets:: = 55, AssetConversion: pallet_asset_conversion = 56, + AssetsFreezer: pallet_assets_freezer:: = 57, + ForeignAssetsFreezer: pallet_assets_freezer:: = 58, + PoolAssetsFreezer: pallet_assets_freezer:: = 59, StateTrieMigration: pallet_state_trie_migration = 70, @@ -1326,7 +1350,7 @@ impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::fees::XcmPaymentApi for Runtime { + impl xcm_runtime_apis::fees::XcmPaymentApi for Runtime { fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result, XcmPaymentApiError> { let acceptable_assets = vec![AssetId(xcm_config::WestendLocation::get())]; PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets) @@ -1339,11 +1363,11 @@ impl_runtime_apis! { Ok(WeightToFee::weight_to_fee(&weight)) }, Ok(asset_id) => { - log::trace!(target: "xcm::xcm_fee_payment_runtime_api", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); + log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); Err(XcmPaymentApiError::AssetNotFound) }, Err(_) => { - log::trace!(target: "xcm::xcm_fee_payment_runtime_api", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!"); + log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!"); Err(XcmPaymentApiError::VersionedConversionFailed) } } @@ -1358,7 +1382,7 @@ impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::dry_run::DryRunApi for Runtime { + impl xcm_runtime_apis::dry_run::DryRunApi for Runtime { fn dry_run_call(origin: OriginCaller, call: RuntimeCall) -> Result, XcmDryRunApiError> { PolkadotXcm::dry_run_call::(origin, call) } @@ -1368,6 +1392,18 @@ impl_runtime_apis! { } } + impl xcm_runtime_apis::conversions::LocationToAccountApi for Runtime { + fn convert_location(location: VersionedLocation) -> Result< + AccountId, + xcm_runtime_apis::conversions::Error + > { + xcm_runtime_apis::conversions::LocationToAccountHelper::< + AccountId, + xcm_config::LocationToAccountId, + >::convert_location(location) + } + } + impl pallet_transaction_payment_rpc_runtime_api::TransactionPaymentCallApi for Runtime { diff --git a/cumulus/parachains/runtimes/assets/common/Cargo.toml b/cumulus/parachains/runtimes/assets/common/Cargo.toml index 4664e0cb9a7f817ed419936dfa9e5d0ac52f599e..94612506f510e3677db444c61c05db46f84cdc0e 100644 --- a/cumulus/parachains/runtimes/assets/common/Cargo.toml +++ b/cumulus/parachains/runtimes/assets/common/Cargo.toml @@ -10,30 +10,30 @@ license = "Apache-2.0" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } log = { workspace = true } -impl-trait-for-tuples = "0.2.2" +impl-trait-for-tuples = { workspace = true } # Substrate -frame-support = { path = "../../../../../substrate/frame/support", default-features = false } -sp-api = { path = "../../../../../substrate/primitives/api", default-features = false } -sp-std = { path = "../../../../../substrate/primitives/std", default-features = false } -sp-runtime = { path = "../../../../../substrate/primitives/runtime", default-features = false } -pallet-asset-conversion = { path = "../../../../../substrate/frame/asset-conversion", default-features = false } +frame-support = { workspace = true } +sp-api = { workspace = true } +sp-std = { workspace = true } +sp-runtime = { workspace = true } +pallet-asset-conversion = { workspace = true } # Polkadot -pallet-xcm = { path = "../../../../../polkadot/xcm/pallet-xcm", default-features = false } -xcm = { package = "staging-xcm", path = "../../../../../polkadot/xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../../../polkadot/xcm/xcm-builder", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../../polkadot/xcm/xcm-executor", default-features = false } +pallet-xcm = { workspace = true } +xcm = { workspace = true } +xcm-builder = { workspace = true } +xcm-executor = { workspace = true } # Cumulus -parachains-common = { path = "../../../common", default-features = false } -cumulus-primitives-core = { path = "../../../../primitives/core", default-features = false } +parachains-common = { workspace = true } +cumulus-primitives-core = { workspace = true } [build-dependencies] -substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder" } +substrate-wasm-builder = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/cumulus/parachains/runtimes/assets/test-utils/Cargo.toml b/cumulus/parachains/runtimes/assets/test-utils/Cargo.toml index af5b4a64680724abcbf0d659ba8a7b2b45cd0e80..a7aad361e84e1b4c8555f57be2dafacab760c15d 100644 --- a/cumulus/parachains/runtimes/assets/test-utils/Cargo.toml +++ b/cumulus/parachains/runtimes/assets/test-utils/Cargo.toml @@ -10,42 +10,42 @@ license = "Apache-2.0" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive", "max-encoded-len"] } +codec = { features = ["derive", "max-encoded-len"], workspace = true } # Substrate -frame-support = { path = "../../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../../substrate/frame/system", default-features = false } -pallet-assets = { path = "../../../../../substrate/frame/assets", default-features = false } -pallet-balances = { path = "../../../../../substrate/frame/balances", default-features = false } -pallet-timestamp = { path = "../../../../../substrate/frame/timestamp", default-features = false } -pallet-session = { path = "../../../../../substrate/frame/session", default-features = false } -sp-io = { path = "../../../../../substrate/primitives/io", default-features = false } -sp-runtime = { path = "../../../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../../../substrate/primitives/std", default-features = false } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-assets = { workspace = true } +pallet-balances = { workspace = true } +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 = { path = "../../../../pallets/parachain-system", default-features = false } -cumulus-pallet-xcmp-queue = { path = "../../../../pallets/xcmp-queue", default-features = false } -pallet-collator-selection = { path = "../../../../pallets/collator-selection", default-features = false } -parachains-common = { path = "../../../common", default-features = false } -cumulus-primitives-core = { path = "../../../../primitives/core", default-features = false } -parachain-info = { package = "staging-parachain-info", path = "../../../pallets/parachain-info", default-features = false } -parachains-runtimes-test-utils = { path = "../../test-utils", default-features = false } +cumulus-pallet-parachain-system = { workspace = true } +cumulus-pallet-xcmp-queue = { workspace = true } +pallet-collator-selection = { workspace = true } +parachains-common = { workspace = true } +cumulus-primitives-core = { workspace = true } +parachain-info = { workspace = true } +parachains-runtimes-test-utils = { workspace = true } # Polkadot -xcm = { package = "staging-xcm", path = "../../../../../polkadot/xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../../../polkadot/xcm/xcm-builder", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../../polkadot/xcm/xcm-executor", default-features = false } -pallet-xcm = { path = "../../../../../polkadot/xcm/pallet-xcm", default-features = false } +xcm = { workspace = true } +xcm-builder = { workspace = true } +xcm-executor = { workspace = true } +pallet-xcm = { workspace = true } # Bridges -pallet-xcm-bridge-hub-router = { path = "../../../../../bridges/modules/xcm-bridge-hub-router", default-features = false } +pallet-xcm-bridge-hub-router = { workspace = true } [dev-dependencies] -hex-literal = "0.4.1" +hex-literal = { workspace = true, default-features = true } [build-dependencies] -substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder" } +substrate-wasm-builder = { workspace = true, default-features = true } [features] default = ["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 253a21f5d0baba1218de3469766a7eb065cb8f3d..1ac31efaf912d7a115a704d37bb3d3e76a2db854 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/Cargo.toml +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/Cargo.toml @@ -10,125 +10,124 @@ license = "Apache-2.0" workspace = true [build-dependencies] -substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } +substrate-wasm-builder = { optional = true, workspace = true, default-features = true } [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", -] } -hex-literal = { version = "0.4.1" } +], workspace = true } +hex-literal = { workspace = true, default-features = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = [ +scale-info = { features = [ "derive", -] } +], workspace = true } serde = { optional = true, features = ["derive"], workspace = true, default-features = true } -tuplex = { version = "0.1", default-features = false } # Substrate -frame-benchmarking = { path = "../../../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-executive = { path = "../../../../../substrate/frame/executive", default-features = false } -frame-support = { path = "../../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../../substrate/frame/system", default-features = false } -frame-system-benchmarking = { path = "../../../../../substrate/frame/system/benchmarking", default-features = false, optional = true } -frame-system-rpc-runtime-api = { path = "../../../../../substrate/frame/system/rpc/runtime-api", default-features = false } -frame-try-runtime = { path = "../../../../../substrate/frame/try-runtime", default-features = false, optional = true } -pallet-aura = { path = "../../../../../substrate/frame/aura", default-features = false } -pallet-authorship = { path = "../../../../../substrate/frame/authorship", default-features = false } -pallet-balances = { path = "../../../../../substrate/frame/balances", default-features = false } -pallet-session = { path = "../../../../../substrate/frame/session", default-features = false } -pallet-message-queue = { path = "../../../../../substrate/frame/message-queue", default-features = false } -pallet-multisig = { path = "../../../../../substrate/frame/multisig", default-features = false } -pallet-timestamp = { path = "../../../../../substrate/frame/timestamp", default-features = false } -pallet-transaction-payment = { path = "../../../../../substrate/frame/transaction-payment", default-features = false } -pallet-transaction-payment-rpc-runtime-api = { path = "../../../../../substrate/frame/transaction-payment/rpc/runtime-api", default-features = false } -pallet-utility = { path = "../../../../../substrate/frame/utility", default-features = false } -sp-api = { path = "../../../../../substrate/primitives/api", default-features = false } -sp-block-builder = { path = "../../../../../substrate/primitives/block-builder", default-features = false } -sp-consensus-aura = { path = "../../../../../substrate/primitives/consensus/aura", default-features = false } -sp-core = { path = "../../../../../substrate/primitives/core", default-features = false } -sp-genesis-builder = { path = "../../../../../substrate/primitives/genesis-builder", default-features = false } -sp-inherents = { path = "../../../../../substrate/primitives/inherents", default-features = false } -sp-io = { path = "../../../../../substrate/primitives/io", default-features = false } -sp-offchain = { path = "../../../../../substrate/primitives/offchain", default-features = false } -sp-runtime = { path = "../../../../../substrate/primitives/runtime", default-features = false } -sp-session = { path = "../../../../../substrate/primitives/session", default-features = false } -sp-std = { path = "../../../../../substrate/primitives/std", default-features = false } -sp-storage = { path = "../../../../../substrate/primitives/storage", default-features = false } -sp-transaction-pool = { path = "../../../../../substrate/primitives/transaction-pool", default-features = false } -sp-version = { path = "../../../../../substrate/primitives/version", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +frame-executive = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +frame-system-benchmarking = { optional = true, workspace = true } +frame-system-rpc-runtime-api = { workspace = true } +frame-try-runtime = { optional = true, workspace = true } +pallet-aura = { workspace = true } +pallet-authorship = { workspace = true } +pallet-balances = { workspace = true } +pallet-session = { workspace = true } +pallet-message-queue = { workspace = true } +pallet-multisig = { workspace = true } +pallet-timestamp = { workspace = true } +pallet-transaction-payment = { workspace = true } +pallet-transaction-payment-rpc-runtime-api = { workspace = true } +pallet-utility = { workspace = true } +sp-api = { workspace = true } +sp-block-builder = { workspace = true } +sp-consensus-aura = { workspace = true } +sp-core = { workspace = true } +sp-genesis-builder = { workspace = true } +sp-inherents = { workspace = true } +sp-io = { 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 } # Polkadot -rococo-runtime-constants = { path = "../../../../../polkadot/runtime/rococo/constants", default-features = false } -pallet-xcm = { path = "../../../../../polkadot/xcm/pallet-xcm", default-features = false } -pallet-xcm-benchmarks = { path = "../../../../../polkadot/xcm/pallet-xcm-benchmarks", default-features = false, optional = true } -polkadot-parachain-primitives = { path = "../../../../../polkadot/parachain", default-features = false } -polkadot-runtime-common = { path = "../../../../../polkadot/runtime/common", default-features = false } -xcm = { package = "staging-xcm", path = "../../../../../polkadot/xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../../../polkadot/xcm/xcm-builder", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../../polkadot/xcm/xcm-executor", default-features = false } -xcm-fee-payment-runtime-api = { path = "../../../../../polkadot/xcm/xcm-fee-payment-runtime-api", default-features = false } +rococo-runtime-constants = { workspace = true } +pallet-xcm = { workspace = true } +pallet-xcm-benchmarks = { optional = true, workspace = true } +polkadot-parachain-primitives = { workspace = true } +polkadot-runtime-common = { workspace = true } +xcm = { workspace = true } +xcm-builder = { workspace = true } +xcm-executor = { workspace = true } +xcm-runtime-apis = { workspace = true } # Cumulus -cumulus-pallet-aura-ext = { path = "../../../../pallets/aura-ext", default-features = false } -cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false } -cumulus-pallet-session-benchmarking = { path = "../../../../pallets/session-benchmarking", default-features = false } -cumulus-pallet-xcm = { path = "../../../../pallets/xcm", default-features = false } -cumulus-pallet-xcmp-queue = { path = "../../../../pallets/xcmp-queue", default-features = false, features = [ +cumulus-pallet-aura-ext = { workspace = true } +cumulus-pallet-parachain-system = { workspace = true } +cumulus-pallet-session-benchmarking = { workspace = true } +cumulus-pallet-xcm = { workspace = true } +cumulus-pallet-xcmp-queue = { features = [ "bridging", -] } -cumulus-primitives-aura = { path = "../../../../primitives/aura", default-features = false } -cumulus-primitives-core = { path = "../../../../primitives/core", default-features = false } -cumulus-primitives-storage-weight-reclaim = { path = "../../../../primitives/storage-weight-reclaim", default-features = false } -cumulus-primitives-utility = { path = "../../../../primitives/utility", default-features = false } -pallet-collator-selection = { path = "../../../../pallets/collator-selection", default-features = false } -parachain-info = { package = "staging-parachain-info", path = "../../../pallets/parachain-info", default-features = false } -parachains-common = { path = "../../../common", default-features = false } -testnet-parachains-constants = { path = "../../constants", default-features = false, features = ["rococo"] } +], workspace = true } +cumulus-primitives-aura = { workspace = true } +cumulus-primitives-core = { workspace = true } +cumulus-primitives-storage-weight-reclaim = { workspace = true } +cumulus-primitives-utility = { workspace = true } +pallet-collator-selection = { workspace = true } +parachain-info = { workspace = true } +parachains-common = { workspace = true } +testnet-parachains-constants = { features = ["rococo"], workspace = true } # Bridges -bp-asset-hub-rococo = { path = "../../../../../bridges/chains/chain-asset-hub-rococo", default-features = false } -bp-asset-hub-westend = { path = "../../../../../bridges/chains/chain-asset-hub-westend", default-features = false } -bp-bridge-hub-polkadot = { path = "../../../../../bridges/chains/chain-bridge-hub-polkadot", default-features = false } -bp-bridge-hub-rococo = { path = "../../../../../bridges/chains/chain-bridge-hub-rococo", default-features = false } -bp-bridge-hub-westend = { path = "../../../../../bridges/chains/chain-bridge-hub-westend", default-features = false } -bp-header-chain = { path = "../../../../../bridges/primitives/header-chain", default-features = false } -bp-messages = { path = "../../../../../bridges/primitives/messages", default-features = false } -bp-parachains = { path = "../../../../../bridges/primitives/parachains", default-features = false } -bp-polkadot-bulletin = { path = "../../../../../bridges/chains/chain-polkadot-bulletin", default-features = false } -bp-polkadot-core = { path = "../../../../../bridges/primitives/polkadot-core", default-features = false } -bp-relayers = { path = "../../../../../bridges/primitives/relayers", default-features = false } -bp-runtime = { path = "../../../../../bridges/primitives/runtime", default-features = false } -bp-rococo = { path = "../../../../../bridges/chains/chain-rococo", default-features = false } -bp-westend = { path = "../../../../../bridges/chains/chain-westend", default-features = false } -pallet-bridge-grandpa = { path = "../../../../../bridges/modules/grandpa", default-features = false } -pallet-bridge-messages = { path = "../../../../../bridges/modules/messages", default-features = false } -pallet-bridge-parachains = { path = "../../../../../bridges/modules/parachains", default-features = false } -pallet-bridge-relayers = { path = "../../../../../bridges/modules/relayers", default-features = false } -pallet-xcm-bridge-hub = { path = "../../../../../bridges/modules/xcm-bridge-hub", default-features = false } -bridge-runtime-common = { path = "../../../../../bridges/bin/runtime-common", default-features = false } +bp-asset-hub-rococo = { workspace = true } +bp-asset-hub-westend = { workspace = true } +bp-bridge-hub-polkadot = { workspace = true } +bp-bridge-hub-rococo = { workspace = true } +bp-bridge-hub-westend = { workspace = true } +bp-header-chain = { workspace = true } +bp-messages = { workspace = true } +bp-parachains = { workspace = true } +bp-polkadot-bulletin = { workspace = true } +bp-polkadot-core = { workspace = true } +bp-relayers = { workspace = true } +bp-runtime = { workspace = true } +bp-rococo = { workspace = true } +bp-westend = { workspace = true } +pallet-bridge-grandpa = { workspace = true } +pallet-bridge-messages = { workspace = true } +pallet-bridge-parachains = { workspace = true } +pallet-bridge-relayers = { workspace = true } +pallet-xcm-bridge-hub = { workspace = true } +bridge-runtime-common = { workspace = true } # Ethereum Bridge (Snowbridge) -snowbridge-beacon-primitives = { path = "../../../../../bridges/snowbridge/primitives/beacon", default-features = false } -snowbridge-pallet-system = { path = "../../../../../bridges/snowbridge/pallets/system", default-features = false } -snowbridge-system-runtime-api = { path = "../../../../../bridges/snowbridge/pallets/system/runtime-api", default-features = false } -snowbridge-core = { path = "../../../../../bridges/snowbridge/primitives/core", default-features = false } -snowbridge-pallet-ethereum-client = { path = "../../../../../bridges/snowbridge/pallets/ethereum-client", default-features = false } -snowbridge-pallet-inbound-queue = { path = "../../../../../bridges/snowbridge/pallets/inbound-queue", default-features = false } -snowbridge-pallet-outbound-queue = { path = "../../../../../bridges/snowbridge/pallets/outbound-queue", default-features = false } -snowbridge-outbound-queue-runtime-api = { path = "../../../../../bridges/snowbridge/pallets/outbound-queue/runtime-api", default-features = false } -snowbridge-router-primitives = { path = "../../../../../bridges/snowbridge/primitives/router", default-features = false } -snowbridge-runtime-common = { path = "../../../../../bridges/snowbridge/runtime/runtime-common", default-features = false } +snowbridge-beacon-primitives = { workspace = true } +snowbridge-pallet-system = { workspace = true } +snowbridge-system-runtime-api = { workspace = true } +snowbridge-core = { workspace = true } +snowbridge-pallet-ethereum-client = { workspace = true } +snowbridge-pallet-inbound-queue = { workspace = true } +snowbridge-pallet-outbound-queue = { workspace = true } +snowbridge-outbound-queue-runtime-api = { workspace = true } +snowbridge-router-primitives = { workspace = true } +snowbridge-runtime-common = { workspace = true } -bridge-hub-common = { path = "../common", default-features = false } +bridge-hub-common = { workspace = true } [dev-dependencies] -static_assertions = "1.1" -bridge-hub-test-utils = { path = "../test-utils" } -bridge-runtime-common = { path = "../../../../../bridges/bin/runtime-common", features = [ +static_assertions = { workspace = true, default-features = true } +bridge-hub-test-utils = { workspace = true, default-features = true } +bridge-runtime-common = { features = [ "integrity-test", -] } -sp-keyring = { path = "../../../../../substrate/primitives/keyring" } -snowbridge-runtime-test-common = { path = "../../../../../bridges/snowbridge/runtime/test-common" } +], workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +snowbridge-runtime-test-common = { workspace = true, default-features = true } [features] default = ["std"] @@ -218,10 +217,9 @@ std = [ "sp-version/std", "substrate-wasm-builder", "testnet-parachains-constants/std", - "tuplex/std", "xcm-builder/std", "xcm-executor/std", - "xcm-fee-payment-runtime-api/std", + "xcm-runtime-apis/std", "xcm/std", ] @@ -264,7 +262,7 @@ runtime-benchmarks = [ "sp-runtime/runtime-benchmarks", "xcm-builder/runtime-benchmarks", "xcm-executor/runtime-benchmarks", - "xcm-fee-payment-runtime-api/runtime-benchmarks", + "xcm-runtime-apis/runtime-benchmarks", ] try-runtime = [ 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 e7868bcbc78d0af4b56f13a5fe844ccc2a368813..9aa1eeb1a4bbdb62213e60e84e49aa01e431cee2 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 @@ -98,7 +98,7 @@ pub use sp_runtime::BuildStorage; use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate}; use rococo_runtime_constants::system_parachain::{ASSET_HUB_ID, BRIDGE_HUB_ID}; use xcm::prelude::*; -use xcm_fee_payment_runtime_api::{ +use xcm_runtime_apis::{ dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects}, fees::Error as XcmPaymentApiError, }; @@ -214,7 +214,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("bridge-hub-rococo"), impl_name: create_runtime_str!("bridge-hub-rococo"), authoring_version: 1, - spec_version: 1_012_000, + spec_version: 1_013_000, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 5, @@ -966,7 +966,7 @@ impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::fees::XcmPaymentApi for Runtime { + impl xcm_runtime_apis::fees::XcmPaymentApi for Runtime { fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result, XcmPaymentApiError> { let acceptable_assets = vec![AssetId(xcm_config::TokenLocation::get())]; PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets) @@ -979,11 +979,11 @@ impl_runtime_apis! { Ok(WeightToFee::weight_to_fee(&weight)) }, Ok(asset_id) => { - log::trace!(target: "xcm::xcm_fee_payment_runtime_api", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); + log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); Err(XcmPaymentApiError::AssetNotFound) }, Err(_) => { - log::trace!(target: "xcm::xcm_fee_payment_runtime_api", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!"); + log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!"); Err(XcmPaymentApiError::VersionedConversionFailed) } } @@ -998,7 +998,7 @@ impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::dry_run::DryRunApi for Runtime { + impl xcm_runtime_apis::dry_run::DryRunApi for Runtime { fn dry_run_call(origin: OriginCaller, call: RuntimeCall) -> Result, XcmDryRunApiError> { PolkadotXcm::dry_run_call::(origin, call) } @@ -1008,6 +1008,18 @@ impl_runtime_apis! { } } + impl xcm_runtime_apis::conversions::LocationToAccountApi for Runtime { + fn convert_location(location: VersionedLocation) -> Result< + AccountId, + xcm_runtime_apis::conversions::Error + > { + xcm_runtime_apis::conversions::LocationToAccountHelper::< + AccountId, + xcm_config::LocationToAccountId, + >::convert_location(location) + } + } + impl cumulus_primitives_core::CollectCollationInfo for Runtime { fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { ParachainSystem::collect_collation_info(header) 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 0f16d629fc26051e53d3cabef19290fb4e8cff5e..c18d5036e06ad5772b24d4d53b8618bf054ef66a 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/Cargo.toml +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-westend/Cargo.toml @@ -10,102 +10,101 @@ license = "Apache-2.0" workspace = true [build-dependencies] -substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } +substrate-wasm-builder = { optional = true, workspace = true, default-features = true } [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -hex-literal = { version = "0.4.1" } +codec = { features = ["derive"], workspace = true } +hex-literal = { workspace = true, default-features = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } serde = { optional = true, features = ["derive"], workspace = true, default-features = true } -tuplex = { version = "0.1", default-features = false } # Substrate -frame-benchmarking = { path = "../../../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-executive = { path = "../../../../../substrate/frame/executive", default-features = false } -frame-support = { path = "../../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../../substrate/frame/system", default-features = false } -frame-system-benchmarking = { path = "../../../../../substrate/frame/system/benchmarking", default-features = false, optional = true } -frame-system-rpc-runtime-api = { path = "../../../../../substrate/frame/system/rpc/runtime-api", default-features = false } -frame-try-runtime = { path = "../../../../../substrate/frame/try-runtime", default-features = false, optional = true } -pallet-aura = { path = "../../../../../substrate/frame/aura", default-features = false } -pallet-authorship = { path = "../../../../../substrate/frame/authorship", default-features = false } -pallet-balances = { path = "../../../../../substrate/frame/balances", default-features = false } -pallet-session = { path = "../../../../../substrate/frame/session", default-features = false } -pallet-message-queue = { path = "../../../../../substrate/frame/message-queue", default-features = false } -pallet-multisig = { path = "../../../../../substrate/frame/multisig", default-features = false } -pallet-timestamp = { path = "../../../../../substrate/frame/timestamp", default-features = false } -pallet-transaction-payment = { path = "../../../../../substrate/frame/transaction-payment", default-features = false } -pallet-transaction-payment-rpc-runtime-api = { path = "../../../../../substrate/frame/transaction-payment/rpc/runtime-api", default-features = false } -pallet-utility = { path = "../../../../../substrate/frame/utility", default-features = false } -sp-api = { path = "../../../../../substrate/primitives/api", default-features = false } -sp-block-builder = { path = "../../../../../substrate/primitives/block-builder", default-features = false } -sp-consensus-aura = { path = "../../../../../substrate/primitives/consensus/aura", default-features = false } -sp-core = { path = "../../../../../substrate/primitives/core", default-features = false } -sp-genesis-builder = { path = "../../../../../substrate/primitives/genesis-builder", default-features = false } -sp-inherents = { path = "../../../../../substrate/primitives/inherents", default-features = false } -sp-io = { path = "../../../../../substrate/primitives/io", default-features = false } -sp-offchain = { path = "../../../../../substrate/primitives/offchain", default-features = false } -sp-runtime = { path = "../../../../../substrate/primitives/runtime", default-features = false } -sp-session = { path = "../../../../../substrate/primitives/session", default-features = false } -sp-std = { path = "../../../../../substrate/primitives/std", default-features = false } -sp-storage = { path = "../../../../../substrate/primitives/storage", default-features = false } -sp-transaction-pool = { path = "../../../../../substrate/primitives/transaction-pool", default-features = false } -sp-version = { path = "../../../../../substrate/primitives/version", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +frame-executive = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +frame-system-benchmarking = { optional = true, workspace = true } +frame-system-rpc-runtime-api = { workspace = true } +frame-try-runtime = { optional = true, workspace = true } +pallet-aura = { workspace = true } +pallet-authorship = { workspace = true } +pallet-balances = { workspace = true } +pallet-session = { workspace = true } +pallet-message-queue = { workspace = true } +pallet-multisig = { workspace = true } +pallet-timestamp = { workspace = true } +pallet-transaction-payment = { workspace = true } +pallet-transaction-payment-rpc-runtime-api = { workspace = true } +pallet-utility = { workspace = true } +sp-api = { workspace = true } +sp-block-builder = { workspace = true } +sp-consensus-aura = { workspace = true } +sp-core = { workspace = true } +sp-genesis-builder = { workspace = true } +sp-inherents = { workspace = true } +sp-io = { 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 } # Polkadot -westend-runtime-constants = { path = "../../../../../polkadot/runtime/westend/constants", default-features = false } -pallet-xcm = { path = "../../../../../polkadot/xcm/pallet-xcm", default-features = false } -pallet-xcm-benchmarks = { path = "../../../../../polkadot/xcm/pallet-xcm-benchmarks", default-features = false, optional = true } -polkadot-parachain-primitives = { path = "../../../../../polkadot/parachain", default-features = false } -polkadot-runtime-common = { path = "../../../../../polkadot/runtime/common", default-features = false } -xcm = { package = "staging-xcm", path = "../../../../../polkadot/xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../../../polkadot/xcm/xcm-builder", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../../polkadot/xcm/xcm-executor", default-features = false } -xcm-fee-payment-runtime-api = { path = "../../../../../polkadot/xcm/xcm-fee-payment-runtime-api", default-features = false } +westend-runtime-constants = { workspace = true } +pallet-xcm = { workspace = true } +pallet-xcm-benchmarks = { optional = true, workspace = true } +polkadot-parachain-primitives = { workspace = true } +polkadot-runtime-common = { workspace = true } +xcm = { workspace = true } +xcm-builder = { workspace = true } +xcm-executor = { workspace = true } +xcm-runtime-apis = { workspace = true } # Cumulus -cumulus-pallet-aura-ext = { path = "../../../../pallets/aura-ext", default-features = false } -cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false } -cumulus-pallet-session-benchmarking = { path = "../../../../pallets/session-benchmarking", default-features = false } -cumulus-pallet-xcm = { path = "../../../../pallets/xcm", default-features = false } -cumulus-pallet-xcmp-queue = { path = "../../../../pallets/xcmp-queue", default-features = false, features = ["bridging"] } -cumulus-primitives-aura = { path = "../../../../primitives/aura", default-features = false } -cumulus-primitives-core = { path = "../../../../primitives/core", default-features = false } -cumulus-primitives-utility = { path = "../../../../primitives/utility", default-features = false } -cumulus-primitives-storage-weight-reclaim = { path = "../../../../primitives/storage-weight-reclaim", default-features = false } +cumulus-pallet-aura-ext = { workspace = true } +cumulus-pallet-parachain-system = { workspace = true } +cumulus-pallet-session-benchmarking = { workspace = true } +cumulus-pallet-xcm = { workspace = true } +cumulus-pallet-xcmp-queue = { features = ["bridging"], workspace = true } +cumulus-primitives-aura = { workspace = true } +cumulus-primitives-core = { workspace = true } +cumulus-primitives-utility = { workspace = true } +cumulus-primitives-storage-weight-reclaim = { workspace = true } -pallet-collator-selection = { path = "../../../../pallets/collator-selection", default-features = false } -parachain-info = { package = "staging-parachain-info", path = "../../../pallets/parachain-info", default-features = false } -parachains-common = { path = "../../../common", default-features = false } -testnet-parachains-constants = { path = "../../constants", default-features = false, features = ["westend"] } +pallet-collator-selection = { workspace = true } +parachain-info = { workspace = true } +parachains-common = { workspace = true } +testnet-parachains-constants = { features = ["westend"], workspace = true } # Bridges -bp-asset-hub-rococo = { path = "../../../../../bridges/chains/chain-asset-hub-rococo", default-features = false } -bp-asset-hub-westend = { path = "../../../../../bridges/chains/chain-asset-hub-westend", default-features = false } -bp-bridge-hub-rococo = { path = "../../../../../bridges/chains/chain-bridge-hub-rococo", default-features = false } -bp-bridge-hub-westend = { path = "../../../../../bridges/chains/chain-bridge-hub-westend", default-features = false } -bp-header-chain = { path = "../../../../../bridges/primitives/header-chain", default-features = false } -bp-messages = { path = "../../../../../bridges/primitives/messages", default-features = false } -bp-parachains = { path = "../../../../../bridges/primitives/parachains", default-features = false } -bp-polkadot-core = { path = "../../../../../bridges/primitives/polkadot-core", default-features = false } -bp-relayers = { path = "../../../../../bridges/primitives/relayers", default-features = false } -bp-runtime = { path = "../../../../../bridges/primitives/runtime", default-features = false } -bp-rococo = { path = "../../../../../bridges/chains/chain-rococo", default-features = false } -bp-westend = { path = "../../../../../bridges/chains/chain-westend", default-features = false } -pallet-bridge-grandpa = { path = "../../../../../bridges/modules/grandpa", default-features = false } -pallet-bridge-messages = { path = "../../../../../bridges/modules/messages", default-features = false } -pallet-bridge-parachains = { path = "../../../../../bridges/modules/parachains", default-features = false } -pallet-bridge-relayers = { path = "../../../../../bridges/modules/relayers", default-features = false } -pallet-xcm-bridge-hub = { path = "../../../../../bridges/modules/xcm-bridge-hub", default-features = false } -bridge-runtime-common = { path = "../../../../../bridges/bin/runtime-common", default-features = false } -bridge-hub-common = { path = "../common", default-features = false } +bp-asset-hub-rococo = { workspace = true } +bp-asset-hub-westend = { workspace = true } +bp-bridge-hub-rococo = { workspace = true } +bp-bridge-hub-westend = { workspace = true } +bp-header-chain = { workspace = true } +bp-messages = { workspace = true } +bp-parachains = { workspace = true } +bp-polkadot-core = { workspace = true } +bp-relayers = { workspace = true } +bp-runtime = { workspace = true } +bp-rococo = { workspace = true } +bp-westend = { workspace = true } +pallet-bridge-grandpa = { workspace = true } +pallet-bridge-messages = { workspace = true } +pallet-bridge-parachains = { workspace = true } +pallet-bridge-relayers = { workspace = true } +pallet-xcm-bridge-hub = { workspace = true } +bridge-runtime-common = { workspace = true } +bridge-hub-common = { workspace = true } [dev-dependencies] -static_assertions = "1.1" -bridge-hub-test-utils = { path = "../test-utils" } -bridge-runtime-common = { path = "../../../../../bridges/bin/runtime-common", features = ["integrity-test"] } -sp-keyring = { path = "../../../../../substrate/primitives/keyring" } +static_assertions = { workspace = true, default-features = true } +bridge-hub-test-utils = { workspace = true, default-features = true } +bridge-runtime-common = { features = ["integrity-test"], workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } [features] default = ["std"] @@ -182,11 +181,10 @@ std = [ "sp-version/std", "substrate-wasm-builder", "testnet-parachains-constants/std", - "tuplex/std", "westend-runtime-constants/std", "xcm-builder/std", "xcm-executor/std", - "xcm-fee-payment-runtime-api/std", + "xcm-runtime-apis/std", "xcm/std", ] @@ -221,7 +219,7 @@ runtime-benchmarks = [ "sp-runtime/runtime-benchmarks", "xcm-builder/runtime-benchmarks", "xcm-executor/runtime-benchmarks", - "xcm-fee-payment-runtime-api/runtime-benchmarks", + "xcm-runtime-apis/runtime-benchmarks", ] try-runtime = [ 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 e26d490f9ac1115b465d707980afc31cb5dfd402..5d4e41bd706db2e806da7db96973618634d2d663 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 @@ -75,7 +75,7 @@ pub use sp_consensus_aura::sr25519::AuthorityId as AuraId; pub use sp_runtime::{MultiAddress, Perbill, Permill}; use xcm_config::{XcmOriginToTransactDispatchOrigin, XcmRouter}; -use xcm_fee_payment_runtime_api::{ +use xcm_runtime_apis::{ dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects}, fees::Error as XcmPaymentApiError, }; @@ -189,7 +189,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("bridge-hub-westend"), impl_name: create_runtime_str!("bridge-hub-westend"), authoring_version: 1, - spec_version: 1_012_000, + spec_version: 1_013_000, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 5, @@ -716,7 +716,7 @@ impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::fees::XcmPaymentApi for Runtime { + impl xcm_runtime_apis::fees::XcmPaymentApi for Runtime { fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result, XcmPaymentApiError> { let acceptable_assets = vec![AssetId(xcm_config::WestendLocation::get())]; PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets) @@ -729,11 +729,11 @@ impl_runtime_apis! { Ok(WeightToFee::weight_to_fee(&weight)) }, Ok(asset_id) => { - log::trace!(target: "xcm::xcm_fee_payment_runtime_api", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); + log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); Err(XcmPaymentApiError::AssetNotFound) }, Err(_) => { - log::trace!(target: "xcm::xcm_fee_payment_runtime_api", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!"); + log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!"); Err(XcmPaymentApiError::VersionedConversionFailed) } } @@ -748,7 +748,7 @@ impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::dry_run::DryRunApi for Runtime { + impl xcm_runtime_apis::dry_run::DryRunApi for Runtime { fn dry_run_call(origin: OriginCaller, call: RuntimeCall) -> Result, XcmDryRunApiError> { PolkadotXcm::dry_run_call::(origin, call) } @@ -758,6 +758,18 @@ impl_runtime_apis! { } } + impl xcm_runtime_apis::conversions::LocationToAccountApi for Runtime { + fn convert_location(location: VersionedLocation) -> Result< + AccountId, + xcm_runtime_apis::conversions::Error + > { + xcm_runtime_apis::conversions::LocationToAccountHelper::< + AccountId, + xcm_config::LocationToAccountId, + >::convert_location(location) + } + } + impl cumulus_primitives_core::CollectCollationInfo for Runtime { fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { ParachainSystem::collect_collation_info(header) diff --git a/cumulus/parachains/runtimes/bridge-hubs/common/Cargo.toml b/cumulus/parachains/runtimes/bridge-hubs/common/Cargo.toml index aece34613e6a6c4dfe100e84b0317a96ad7ee97c..fd0eed1c05a1a65e9f5c41d1880f57b708e85119 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/common/Cargo.toml +++ b/cumulus/parachains/runtimes/bridge-hubs/common/Cargo.toml @@ -7,16 +7,16 @@ description = "Bridge hub common utilities" license = "Apache-2.0" [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-support = { path = "../../../../../substrate/frame/support", default-features = false } -sp-std = { path = "../../../../../substrate/primitives/std", default-features = false } -sp-core = { path = "../../../../../substrate/primitives/core", default-features = false } -sp-runtime = { path = "../../../../../substrate/primitives/runtime", default-features = false } -cumulus-primitives-core = { path = "../../../../primitives/core", default-features = false } -xcm = { package = "staging-xcm", path = "../../../../../polkadot/xcm", default-features = false } -pallet-message-queue = { path = "../../../../../substrate/frame/message-queue", default-features = false } -snowbridge-core = { path = "../../../../../bridges/snowbridge/primitives/core", default-features = false } +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 } +xcm = { workspace = true } +pallet-message-queue = { workspace = true } +snowbridge-core = { workspace = true } [features] default = ["std"] diff --git a/cumulus/parachains/runtimes/bridge-hubs/test-utils/Cargo.toml b/cumulus/parachains/runtimes/bridge-hubs/test-utils/Cargo.toml index 80f0114cc4cadb6cd7871454eead80a0988d5e7e..90af4dd8f3ed80708cde59e66aed557042e3da39 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/test-utils/Cargo.toml +++ b/cumulus/parachains/runtimes/bridge-hubs/test-utils/Cargo.toml @@ -10,47 +10,47 @@ license = "Apache-2.0" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive", "max-encoded-len"] } -impl-trait-for-tuples = "0.2" +codec = { features = ["derive", "max-encoded-len"], workspace = true } +impl-trait-for-tuples = { workspace = true } log = { workspace = true } # Substrate -frame-support = { path = "../../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../../substrate/frame/system", default-features = false } -sp-core = { path = "../../../../../substrate/primitives/core", default-features = false } -sp-io = { path = "../../../../../substrate/primitives/io", default-features = false } -sp-keyring = { path = "../../../../../substrate/primitives/keyring" } -sp-runtime = { path = "../../../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../../../substrate/primitives/std", default-features = false } -sp-tracing = { path = "../../../../../substrate/primitives/tracing" } -pallet-balances = { path = "../../../../../substrate/frame/balances", default-features = false } -pallet-utility = { path = "../../../../../substrate/frame/utility", default-features = false } -pallet-timestamp = { path = "../../../../../substrate/frame/timestamp", default-features = false } +frame-support = { workspace = true } +frame-system = { workspace = true } +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 } +pallet-timestamp = { workspace = true } # Cumulus -asset-test-utils = { path = "../../assets/test-utils" } -cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false } -cumulus-pallet-xcmp-queue = { path = "../../../../pallets/xcmp-queue", default-features = false } -parachains-common = { path = "../../../common", default-features = false } -parachains-runtimes-test-utils = { path = "../../test-utils", default-features = false } +asset-test-utils = { workspace = true, default-features = true } +cumulus-pallet-parachain-system = { workspace = true } +cumulus-pallet-xcmp-queue = { workspace = true } +parachains-common = { workspace = true } +parachains-runtimes-test-utils = { workspace = true } # Polkadot -xcm = { package = "staging-xcm", path = "../../../../../polkadot/xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../../../polkadot/xcm/xcm-builder", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../../polkadot/xcm/xcm-executor", default-features = false } +xcm = { workspace = true } +xcm-builder = { workspace = true } +xcm-executor = { workspace = true } # Bridges -bp-header-chain = { path = "../../../../../bridges/primitives/header-chain", default-features = false } -bp-messages = { path = "../../../../../bridges/primitives/messages", default-features = false } -bp-polkadot-core = { path = "../../../../../bridges/primitives/polkadot-core", default-features = false } -bp-relayers = { path = "../../../../../bridges/primitives/relayers", default-features = false } -bp-runtime = { path = "../../../../../bridges/primitives/runtime", default-features = false } -bp-test-utils = { path = "../../../../../bridges/primitives/test-utils", default-features = false } -pallet-bridge-grandpa = { path = "../../../../../bridges/modules/grandpa", default-features = false } -pallet-bridge-parachains = { path = "../../../../../bridges/modules/parachains", default-features = false } -pallet-bridge-messages = { path = "../../../../../bridges/modules/messages", default-features = false } -pallet-bridge-relayers = { path = "../../../../../bridges/modules/relayers", default-features = false } -bridge-runtime-common = { path = "../../../../../bridges/bin/runtime-common", default-features = false } +bp-header-chain = { workspace = true } +bp-messages = { workspace = true } +bp-polkadot-core = { workspace = true } +bp-relayers = { workspace = true } +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-relayers = { workspace = true } +bridge-runtime-common = { workspace = true } [features] default = ["std"] diff --git a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_data/mod.rs b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_data/mod.rs index 9285a1e7ad4500a4c2c7db73d9966dd711d852be..ee3fc1ed2c41f1ff2a729dcf784f832a5a563a58 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_data/mod.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/test-utils/src/test_data/mod.rs @@ -39,8 +39,8 @@ pub fn prepare_inbound_xcm( xcm_message: Xcm, destination: InteriorLocation, ) -> Vec { - let location = xcm::VersionedInteriorLocation::V4(destination); - let xcm = xcm::VersionedXcm::::V4(xcm_message); + let location = xcm::VersionedInteriorLocation::from(destination); + let xcm = xcm::VersionedXcm::::from(xcm_message); // this is the `BridgeMessage` from polkadot xcm builder, but it has no constructor // or public fields, so just tuple // (double encoding, because `.encode()` is called on original Xcm BLOB when it is pushed diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/Cargo.toml b/cumulus/parachains/runtimes/collectives/collectives-westend/Cargo.toml index fe4de3114be0d0b92643946f0deafe030a8b88f8..87cf42ba87d836976a8997d90ce99eea9c1f1e9f 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/Cargo.toml +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/Cargo.toml @@ -10,88 +10,88 @@ description = "Westend Collectives Parachain Runtime" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive", "max-encoded-len"] } -hex-literal = { version = "0.4.1" } +codec = { features = ["derive", "max-encoded-len"], workspace = true } +hex-literal = { workspace = true, default-features = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } # Substrate -frame-benchmarking = { path = "../../../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-executive = { path = "../../../../../substrate/frame/executive", default-features = false } -frame-support = { path = "../../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../../substrate/frame/system", default-features = false } -frame-system-benchmarking = { path = "../../../../../substrate/frame/system/benchmarking", default-features = false, optional = true } -frame-system-rpc-runtime-api = { path = "../../../../../substrate/frame/system/rpc/runtime-api", default-features = false } -frame-try-runtime = { path = "../../../../../substrate/frame/try-runtime", default-features = false, optional = true } -pallet-asset-rate = { path = "../../../../../substrate/frame/asset-rate", default-features = false } -pallet-alliance = { path = "../../../../../substrate/frame/alliance", default-features = false } -pallet-aura = { path = "../../../../../substrate/frame/aura", default-features = false } -pallet-authorship = { path = "../../../../../substrate/frame/authorship", default-features = false } -pallet-balances = { path = "../../../../../substrate/frame/balances", default-features = false } -pallet-collective = { path = "../../../../../substrate/frame/collective", default-features = false } -pallet-multisig = { path = "../../../../../substrate/frame/multisig", default-features = false } -pallet-preimage = { path = "../../../../../substrate/frame/preimage", default-features = false } -pallet-proxy = { path = "../../../../../substrate/frame/proxy", default-features = false } -pallet-scheduler = { path = "../../../../../substrate/frame/scheduler", default-features = false } -pallet-session = { path = "../../../../../substrate/frame/session", default-features = false } -pallet-state-trie-migration = { path = "../../../../../substrate/frame/state-trie-migration", default-features = false } -pallet-timestamp = { path = "../../../../../substrate/frame/timestamp", default-features = false } -pallet-transaction-payment = { path = "../../../../../substrate/frame/transaction-payment", default-features = false } -pallet-transaction-payment-rpc-runtime-api = { path = "../../../../../substrate/frame/transaction-payment/rpc/runtime-api", default-features = false } -pallet-treasury = { path = "../../../../../substrate/frame/treasury", default-features = false } -pallet-utility = { path = "../../../../../substrate/frame/utility", default-features = false } -pallet-referenda = { path = "../../../../../substrate/frame/referenda", default-features = false } -pallet-ranked-collective = { path = "../../../../../substrate/frame/ranked-collective", default-features = false } -pallet-core-fellowship = { path = "../../../../../substrate/frame/core-fellowship", default-features = false } -pallet-salary = { path = "../../../../../substrate/frame/salary", default-features = false } -sp-api = { path = "../../../../../substrate/primitives/api", default-features = false } -sp-arithmetic = { path = "../../../../../substrate/primitives/arithmetic", default-features = false } -sp-block-builder = { path = "../../../../../substrate/primitives/block-builder", default-features = false } -sp-consensus-aura = { path = "../../../../../substrate/primitives/consensus/aura", default-features = false } -sp-core = { path = "../../../../../substrate/primitives/core", default-features = false } -sp-genesis-builder = { path = "../../../../../substrate/primitives/genesis-builder", default-features = false } -sp-inherents = { path = "../../../../../substrate/primitives/inherents", default-features = false } -sp-offchain = { path = "../../../../../substrate/primitives/offchain", default-features = false } -sp-runtime = { path = "../../../../../substrate/primitives/runtime", default-features = false } -sp-session = { path = "../../../../../substrate/primitives/session", default-features = false } -sp-std = { path = "../../../../../substrate/primitives/std", default-features = false } -sp-storage = { path = "../../../../../substrate/primitives/storage", default-features = false } -sp-transaction-pool = { path = "../../../../../substrate/primitives/transaction-pool", default-features = false } -sp-version = { path = "../../../../../substrate/primitives/version", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +frame-executive = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +frame-system-benchmarking = { optional = true, workspace = true } +frame-system-rpc-runtime-api = { workspace = true } +frame-try-runtime = { optional = true, workspace = true } +pallet-asset-rate = { workspace = true } +pallet-alliance = { workspace = true } +pallet-aura = { workspace = true } +pallet-authorship = { workspace = true } +pallet-balances = { workspace = true } +pallet-collective = { workspace = true } +pallet-multisig = { workspace = true } +pallet-preimage = { workspace = true } +pallet-proxy = { workspace = true } +pallet-scheduler = { workspace = true } +pallet-session = { workspace = true } +pallet-state-trie-migration = { workspace = true } +pallet-timestamp = { workspace = true } +pallet-transaction-payment = { workspace = true } +pallet-transaction-payment-rpc-runtime-api = { workspace = true } +pallet-treasury = { workspace = true } +pallet-utility = { workspace = true } +pallet-referenda = { workspace = true } +pallet-ranked-collective = { workspace = true } +pallet-core-fellowship = { workspace = true } +pallet-salary = { workspace = true } +sp-api = { workspace = true } +sp-arithmetic = { workspace = true } +sp-block-builder = { workspace = true } +sp-consensus-aura = { workspace = true } +sp-core = { workspace = true } +sp-genesis-builder = { workspace = true } +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 } # Polkadot -pallet-xcm = { path = "../../../../../polkadot/xcm/pallet-xcm", default-features = false } -polkadot-parachain-primitives = { path = "../../../../../polkadot/parachain", default-features = false } -polkadot-runtime-common = { path = "../../../../../polkadot/runtime/common", default-features = false } -xcm = { package = "staging-xcm", path = "../../../../../polkadot/xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../../../polkadot/xcm/xcm-builder", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../../polkadot/xcm/xcm-executor", default-features = false } -xcm-fee-payment-runtime-api = { path = "../../../../../polkadot/xcm/xcm-fee-payment-runtime-api", default-features = false } -westend-runtime-constants = { path = "../../../../../polkadot/runtime/westend/constants", default-features = false } +pallet-xcm = { workspace = true } +polkadot-parachain-primitives = { workspace = true } +polkadot-runtime-common = { workspace = true } +xcm = { workspace = true } +xcm-builder = { workspace = true } +xcm-executor = { workspace = true } +westend-runtime-constants = { workspace = true } +xcm-runtime-apis = { workspace = true } # Cumulus -cumulus-pallet-aura-ext = { path = "../../../../pallets/aura-ext", default-features = false } -pallet-message-queue = { path = "../../../../../substrate/frame/message-queue", default-features = false } -cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false } -cumulus-pallet-session-benchmarking = { path = "../../../../pallets/session-benchmarking", default-features = false } -cumulus-pallet-xcm = { path = "../../../../pallets/xcm", default-features = false } -cumulus-pallet-xcmp-queue = { path = "../../../../pallets/xcmp-queue", default-features = false } -cumulus-primitives-aura = { path = "../../../../primitives/aura", default-features = false } -cumulus-primitives-core = { path = "../../../../primitives/core", default-features = false } -cumulus-primitives-utility = { path = "../../../../primitives/utility", default-features = false } -cumulus-primitives-storage-weight-reclaim = { path = "../../../../primitives/storage-weight-reclaim", default-features = false } +cumulus-pallet-aura-ext = { workspace = true } +pallet-message-queue = { workspace = true } +cumulus-pallet-parachain-system = { workspace = true } +cumulus-pallet-session-benchmarking = { workspace = true } +cumulus-pallet-xcm = { workspace = true } +cumulus-pallet-xcmp-queue = { workspace = true } +cumulus-primitives-aura = { workspace = true } +cumulus-primitives-core = { workspace = true } +cumulus-primitives-utility = { workspace = true } +cumulus-primitives-storage-weight-reclaim = { workspace = true } -pallet-collator-selection = { path = "../../../../pallets/collator-selection", default-features = false } -pallet-collective-content = { path = "../../../pallets/collective-content", default-features = false } -parachain-info = { package = "staging-parachain-info", path = "../../../pallets/parachain-info", default-features = false } -parachains-common = { path = "../../../common", default-features = false } -testnet-parachains-constants = { path = "../../constants", default-features = false, features = ["westend"] } +pallet-collator-selection = { workspace = true } +pallet-collective-content = { workspace = true } +parachain-info = { workspace = true } +parachains-common = { workspace = true } +testnet-parachains-constants = { features = ["westend"], workspace = true } [build-dependencies] -substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } +substrate-wasm-builder = { optional = true, workspace = true, default-features = true } [dev-dependencies] -sp-io = { path = "../../../../../substrate/primitives/io", features = ["std"] } +sp-io = { features = ["std"], workspace = true, default-features = true } [features] default = ["std"] @@ -131,7 +131,7 @@ runtime-benchmarks = [ "sp-runtime/runtime-benchmarks", "xcm-builder/runtime-benchmarks", "xcm-executor/runtime-benchmarks", - "xcm-fee-payment-runtime-api/runtime-benchmarks", + "xcm-runtime-apis/runtime-benchmarks", ] try-runtime = [ "cumulus-pallet-aura-ext/try-runtime", @@ -238,7 +238,7 @@ std = [ "westend-runtime-constants/std", "xcm-builder/std", "xcm-executor/std", - "xcm-fee-payment-runtime-api/std", + "xcm-runtime-apis/std", "xcm/std", ] diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/ambassador/mod.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/ambassador/mod.rs index ceef6de6b7435e453e9622a3d318669e1a3a9307..a052a9d3800cc6880ccee84358883194cb46eb80 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/ambassador/mod.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/ambassador/mod.rs @@ -117,6 +117,7 @@ impl pallet_ranked_collective::Config for Runtime type MinRankOfClass = sp_runtime::traits::Identity; type MemberSwappedHandler = (crate::AmbassadorCore, crate::AmbassadorSalary); type VoteWeight = pallet_ranked_collective::Linear; + type MaxMemberCount = (); #[cfg(feature = "runtime-benchmarks")] type BenchmarkSetup = (crate::AmbassadorCore, crate::AmbassadorSalary); } @@ -219,6 +220,7 @@ impl pallet_core_fellowship::Config for Runtime { >; type ApproveOrigin = PromoteOrigin; type PromoteOrigin = PromoteOrigin; + type FastPromoteOrigin = Self::PromoteOrigin; type EvidenceSize = ConstU32<65536>; type MaxRank = ConstU32<9>; } diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/fellowship/mod.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/fellowship/mod.rs index 6a4a182079671f297d18bc40de0bc557911735cd..942e0c294dd022c7c4dacf4febaf99b6ac686dbf 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/fellowship/mod.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/fellowship/mod.rs @@ -30,7 +30,7 @@ use frame_support::{ parameter_types, traits::{ tokens::UnityOrOuterConversion, EitherOf, EitherOfDiverse, FromContains, MapSuccess, - NeverEnsureOrigin, OriginTrait, TryWithMorphedArg, + OriginTrait, TryWithMorphedArg, }, PalletId, }; @@ -55,8 +55,6 @@ use xcm_builder::{AliasesIntoAccountId32, PayOverXcm}; #[cfg(feature = "runtime-benchmarks")] use crate::impls::benchmarks::{OpenHrmpChannel, PayWithEnsure}; -#[cfg(feature = "runtime-benchmarks")] -use testnet_parachains_constants::westend::currency::DOLLARS; /// The Fellowship members' ranks. pub mod ranks { @@ -152,6 +150,7 @@ impl pallet_ranked_collective::Config for Runtime type MinRankOfClass = tracks::MinRankOfClass; type MemberSwappedHandler = (crate::FellowshipCore, crate::FellowshipSalary); type VoteWeight = pallet_ranked_collective::Geometric; + type MaxMemberCount = (); #[cfg(feature = "runtime-benchmarks")] type BenchmarkSetup = (crate::FellowshipCore, crate::FellowshipSalary); } @@ -209,6 +208,7 @@ impl pallet_core_fellowship::Config for Runtime { >, EnsureCanPromoteTo, >; + type FastPromoteOrigin = Self::PromoteOrigin; type EvidenceSize = ConstU32<65536>; type MaxRank = ConstU32<9>; } @@ -270,16 +270,6 @@ parameter_types! { pub SelfParaId: ParaId = ParachainInfo::parachain_id(); } -#[cfg(feature = "runtime-benchmarks")] -parameter_types! { - // Benchmark bond. Needed to make `propose_spend` work. - pub const TenPercent: Permill = Permill::from_percent(10); - // Benchmark minimum. Needed to make `propose_spend` work. - pub const BenchmarkProposalBondMinimum: Balance = 1 * DOLLARS; - // Benchmark maximum. Needed to make `propose_spend` work. - pub const BenchmarkProposalBondMaximum: Balance = 10 * DOLLARS; -} - /// [`PayOverXcm`] setup to pay the Fellowship Treasury. pub type FellowshipTreasuryPaymaster = PayOverXcm< FellowshipTreasuryInteriorLocation, @@ -295,28 +285,6 @@ pub type FellowshipTreasuryPaymaster = PayOverXcm< pub type FellowshipTreasuryInstance = pallet_treasury::Instance1; impl pallet_treasury::Config for Runtime { - // The creation of proposals via the treasury pallet is deprecated and should not be utilized. - // Instead, public or fellowship referenda should be used to propose and command the treasury - // spend or spend_local dispatchables. The parameters below have been configured accordingly to - // discourage its use. - // TODO: replace with `NeverEnsure` once polkadot-sdk 1.5 is released. - type ApproveOrigin = NeverEnsureOrigin<()>; - type OnSlash = (); - #[cfg(not(feature = "runtime-benchmarks"))] - type ProposalBond = HundredPercent; - #[cfg(not(feature = "runtime-benchmarks"))] - type ProposalBondMinimum = MaxBalance; - #[cfg(not(feature = "runtime-benchmarks"))] - type ProposalBondMaximum = MaxBalance; - - #[cfg(feature = "runtime-benchmarks")] - type ProposalBond = TenPercent; - #[cfg(feature = "runtime-benchmarks")] - type ProposalBondMinimum = BenchmarkProposalBondMinimum; - #[cfg(feature = "runtime-benchmarks")] - type ProposalBondMaximum = BenchmarkProposalBondMaximum; - // end. - type WeightInfo = weights::pallet_treasury::WeightInfo; type PalletId = FellowshipTreasuryPalletId; type Currency = Balances; diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/lib.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/lib.rs index 5fce8e5095410b1e07c363c0731fc9b18e9ca076..909d5dc60942f77deb724d8fe308983c9209440c 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/lib.rs @@ -70,8 +70,8 @@ use frame_support::{ genesis_builder_helper::{build_state, get_preset}, parameter_types, traits::{ - fungible::HoldConsideration, ConstBool, ConstU16, ConstU32, ConstU64, ConstU8, - EitherOfDiverse, InstanceFilter, LinearStoragePrice, TransformOrigin, + fungible::HoldConsideration, ConstBool, ConstU32, ConstU64, ConstU8, EitherOfDiverse, + InstanceFilter, LinearStoragePrice, TransformOrigin, }, weights::{ConstantMultiplier, Weight, WeightToFee as _}, PalletId, @@ -104,7 +104,7 @@ use polkadot_runtime_common::{ impls::VersionedLocatableAsset, BlockHashCount, SlowAdjustingFeeUpdate, }; use xcm::prelude::*; -use xcm_fee_payment_runtime_api::{ +use xcm_runtime_apis::{ dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects}, fees::Error as XcmPaymentApiError, }; @@ -122,7 +122,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("collectives-westend"), impl_name: create_runtime_str!("collectives-westend"), authoring_version: 1, - spec_version: 1_012_000, + spec_version: 1_013_000, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 6, @@ -163,6 +163,7 @@ parameter_types! { }) .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO) .build_or_panic(); + pub const SS58Prefix: u8 = 42; } // Configure FRAME pallets to include in runtime. @@ -180,7 +181,7 @@ impl frame_system::Config for Runtime { type Version = Version; type AccountData = pallet_balances::AccountData; type SystemWeightInfo = weights::frame_system::WeightInfo; - type SS58Prefix = ConstU16<0>; + type SS58Prefix = SS58Prefix; type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode; type MaxConsumers = frame_support::traits::ConstU32<16>; } @@ -940,7 +941,7 @@ impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::fees::XcmPaymentApi for Runtime { + impl xcm_runtime_apis::fees::XcmPaymentApi for Runtime { fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result, XcmPaymentApiError> { let acceptable_assets = vec![AssetId(xcm_config::WndLocation::get())]; PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets) @@ -953,11 +954,11 @@ impl_runtime_apis! { Ok(WeightToFee::weight_to_fee(&weight)) }, Ok(asset_id) => { - log::trace!(target: "xcm::xcm_fee_payment_runtime_api", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); + log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); Err(XcmPaymentApiError::AssetNotFound) }, Err(_) => { - log::trace!(target: "xcm::xcm_fee_payment_runtime_api", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!"); + log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!"); Err(XcmPaymentApiError::VersionedConversionFailed) } } @@ -972,7 +973,7 @@ impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::dry_run::DryRunApi for Runtime { + impl xcm_runtime_apis::dry_run::DryRunApi for Runtime { fn dry_run_call(origin: OriginCaller, call: RuntimeCall) -> Result, XcmDryRunApiError> { PolkadotXcm::dry_run_call::(origin, call) } @@ -982,6 +983,18 @@ impl_runtime_apis! { } } + impl xcm_runtime_apis::conversions::LocationToAccountApi for Runtime { + fn convert_location(location: VersionedLocation) -> Result< + AccountId, + xcm_runtime_apis::conversions::Error + > { + xcm_runtime_apis::conversions::LocationToAccountHelper::< + AccountId, + LocationToAccountId, + >::convert_location(location) + } + } + impl cumulus_primitives_core::CollectCollationInfo for Runtime { fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { ParachainSystem::collect_collation_info(header) diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_core_fellowship_ambassador_core.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_core_fellowship_ambassador_core.rs index f40940a8b25faa7c441b1ac9b237cb34e671cf17..6bedfcc7e012383657a059b87942517644057d8a 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_core_fellowship_ambassador_core.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_core_fellowship_ambassador_core.rs @@ -58,6 +58,17 @@ impl pallet_core_fellowship::WeightInfo for WeightInfo< .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(1)) } + /// Storage: `AmbassadorCore::Params` (r:0 w:1) + /// Proof: `AmbassadorCore::Params` (`max_values`: Some(1), `max_size`: Some(364), added: 859, mode: `MaxEncodedLen`) + fn set_partial_params() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 11_000_000 picoseconds. + Weight::from_parts(11_000_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } /// Storage: `AmbassadorCore::Member` (r:1 w:1) /// Proof: `AmbassadorCore::Member` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) /// Storage: `AmbassadorCollective::Members` (r:1 w:1) @@ -160,6 +171,20 @@ impl pallet_core_fellowship::WeightInfo for WeightInfo< .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(6)) } + fn promote_fast(r: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `16844` + // Estimated: `19894 + r * (2489 ยฑ0)` + // Minimum execution time: 45_065_000 picoseconds. + Weight::from_parts(34_090_392, 19894) + // Standard Error: 18_620 + .saturating_add(Weight::from_parts(13_578_046, 0).saturating_mul(r.into())) + .saturating_add(T::DbWeight::get().reads(3_u64)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(r.into()))) + .saturating_add(T::DbWeight::get().writes(3_u64)) + .saturating_add(T::DbWeight::get().writes((3_u64).saturating_mul(r.into()))) + .saturating_add(Weight::from_parts(0, 2489).saturating_mul(r.into())) + } /// Storage: `AmbassadorCollective::Members` (r:1 w:0) /// Proof: `AmbassadorCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) /// Storage: `AmbassadorCore::Member` (r:1 w:1) diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_core_fellowship_fellowship_core.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_core_fellowship_fellowship_core.rs index 471ee82ead729ea5abff616f0c9fe3a86704fd91..05014e273f0009bf212969ba8705879747eedd75 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_core_fellowship_fellowship_core.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_core_fellowship_fellowship_core.rs @@ -57,6 +57,17 @@ impl pallet_core_fellowship::WeightInfo for WeightInfo< .saturating_add(Weight::from_parts(0, 0)) .saturating_add(T::DbWeight::get().writes(1)) } + /// Storage: `FellowshipCore::Params` (r:0 w:1) + /// Proof: `FellowshipCore::Params` (`max_values`: Some(1), `max_size`: Some(364), added: 859, mode: `MaxEncodedLen`) + fn set_partial_params() -> Weight { + // Proof Size summary in bytes: + // Measured: `0` + // Estimated: `0` + // Minimum execution time: 11_000_000 picoseconds. + Weight::from_parts(12_000_000, 0) + .saturating_add(Weight::from_parts(0, 0)) + .saturating_add(T::DbWeight::get().writes(1)) + } /// Storage: `FellowshipCore::Member` (r:1 w:1) /// Proof: `FellowshipCore::Member` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) /// Storage: `FellowshipCollective::Members` (r:1 w:1) @@ -159,6 +170,20 @@ impl pallet_core_fellowship::WeightInfo for WeightInfo< .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(6)) } + fn promote_fast(r: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `16844` + // Estimated: `19894 + r * (2489 ยฑ0)` + // Minimum execution time: 45_065_000 picoseconds. + Weight::from_parts(34_090_392, 19894) + // Standard Error: 18_620 + .saturating_add(Weight::from_parts(13_578_046, 0).saturating_mul(r.into())) + .saturating_add(T::DbWeight::get().reads(3_u64)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(r.into()))) + .saturating_add(T::DbWeight::get().writes(3_u64)) + .saturating_add(T::DbWeight::get().writes((3_u64).saturating_mul(r.into()))) + .saturating_add(Weight::from_parts(0, 2489).saturating_mul(r.into())) + } /// Storage: `FellowshipCollective::Members` (r:1 w:0) /// Proof: `FellowshipCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) /// Storage: `FellowshipCore::Member` (r:1 w:1) diff --git a/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_treasury.rs b/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_treasury.rs index 58540e646d8c3885bf84da512e2ddc3e42abc80e..5c513c3754ce84605465aa48ac43e7731e798d2a 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_treasury.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-westend/src/weights/pallet_treasury.rs @@ -62,43 +62,6 @@ impl pallet_treasury::WeightInfo for WeightInfo { .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(3)) } - /// Storage: `FellowshipTreasury::ProposalCount` (r:1 w:1) - /// Proof: `FellowshipTreasury::ProposalCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `FellowshipTreasury::Proposals` (r:0 w:1) - /// Proof: `FellowshipTreasury::Proposals` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - fn propose_spend() -> Weight { - // Proof Size summary in bytes: - // Measured: `143` - // Estimated: `1489` - // Minimum execution time: 264_000_000 picoseconds. - Weight::from_parts(277_000_000, 0) - .saturating_add(Weight::from_parts(0, 1489)) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: `FellowshipTreasury::Proposals` (r:1 w:1) - /// Proof: `FellowshipTreasury::Proposals` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - fn reject_proposal() -> Weight { - // Proof Size summary in bytes: - // Measured: `301` - // Estimated: `3593` - // Minimum execution time: 289_000_000 picoseconds. - Weight::from_parts(312_000_000, 0) - .saturating_add(Weight::from_parts(0, 3593)) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// The range of component `p` is `[0, 99]`. - fn approve_proposal(_p: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `0` - // Estimated: `0` - // Minimum execution time: 0_000 picoseconds. - Weight::from_parts(0, 0) - .saturating_add(Weight::from_parts(0, 0)) - } /// Storage: `FellowshipTreasury::Approvals` (r:1 w:1) /// Proof: `FellowshipTreasury::Approvals` (`max_values`: Some(1), `max_size`: Some(402), added: 897, mode: `MaxEncodedLen`) fn remove_approval() -> Weight { diff --git a/cumulus/parachains/runtimes/constants/Cargo.toml b/cumulus/parachains/runtimes/constants/Cargo.toml index 561e8276b5f0543001e10fd21345ea5d3a65fee5..d54f1e7db6c167480858758bf56ed07941fb06c2 100644 --- a/cumulus/parachains/runtimes/constants/Cargo.toml +++ b/cumulus/parachains/runtimes/constants/Cargo.toml @@ -13,20 +13,20 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -smallvec = "1.11.0" +smallvec = { workspace = true, default-features = true } # Substrate -frame-support = { path = "../../../../substrate/frame/support", default-features = false } -sp-runtime = { path = "../../../../substrate/primitives/runtime", default-features = false } +frame-support = { workspace = true } +sp-runtime = { workspace = true } # Polkadot -polkadot-core-primitives = { path = "../../../../polkadot/core-primitives", default-features = false } -rococo-runtime-constants = { path = "../../../../polkadot/runtime/rococo/constants", default-features = false, optional = true } -westend-runtime-constants = { path = "../../../../polkadot/runtime/westend/constants", default-features = false, optional = true } -xcm = { package = "staging-xcm", path = "../../../../polkadot/xcm", default-features = false } +polkadot-core-primitives = { workspace = true } +rococo-runtime-constants = { optional = true, workspace = true } +westend-runtime-constants = { optional = true, workspace = true } +xcm = { workspace = true } # Cumulus -cumulus-primitives-core = { path = "../../../primitives/core", default-features = false } +cumulus-primitives-core = { workspace = true } [features] default = ["std"] diff --git a/cumulus/parachains/runtimes/contracts/contracts-rococo/Cargo.toml b/cumulus/parachains/runtimes/contracts/contracts-rococo/Cargo.toml index e43a69482c79f1d67e30d6c65ea67840a7893816..4fb4bcde02351b9485dc2a5ccf6b48cc729633e7 100644 --- a/cumulus/parachains/runtimes/contracts/contracts-rococo/Cargo.toml +++ b/cumulus/parachains/runtimes/contracts/contracts-rococo/Cargo.toml @@ -13,74 +13,74 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [build-dependencies] -substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } +substrate-wasm-builder = { optional = true, workspace = true, default-features = true } [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -hex-literal = { version = "0.4.1", optional = true } +codec = { features = ["derive"], workspace = true } +hex-literal = { optional = true, workspace = true, default-features = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } # Substrate -sp-api = { path = "../../../../../substrate/primitives/api", default-features = false } -sp-block-builder = { path = "../../../../../substrate/primitives/block-builder", default-features = false } -sp-consensus-aura = { path = "../../../../../substrate/primitives/consensus/aura", default-features = false } -sp-core = { path = "../../../../../substrate/primitives/core", default-features = false } -sp-genesis-builder = { path = "../../../../../substrate/primitives/genesis-builder", default-features = false } -sp-inherents = { path = "../../../../../substrate/primitives/inherents", default-features = false } -sp-offchain = { path = "../../../../../substrate/primitives/offchain", default-features = false } -sp-runtime = { path = "../../../../../substrate/primitives/runtime", default-features = false } -sp-session = { path = "../../../../../substrate/primitives/session", default-features = false } -sp-std = { path = "../../../../../substrate/primitives/std", default-features = false } -sp-storage = { path = "../../../../../substrate/primitives/storage", default-features = false } -sp-transaction-pool = { path = "../../../../../substrate/primitives/transaction-pool", default-features = false } -sp-version = { path = "../../../../../substrate/primitives/version", default-features = false } -frame-benchmarking = { path = "../../../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-try-runtime = { path = "../../../../../substrate/frame/try-runtime", default-features = false, optional = true } -frame-executive = { path = "../../../../../substrate/frame/executive", default-features = false } -frame-support = { path = "../../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../../substrate/frame/system", default-features = false } -frame-system-benchmarking = { path = "../../../../../substrate/frame/system/benchmarking", default-features = false, optional = true } -frame-system-rpc-runtime-api = { path = "../../../../../substrate/frame/system/rpc/runtime-api", default-features = false } -pallet-aura = { path = "../../../../../substrate/frame/aura", default-features = false } -pallet-authorship = { path = "../../../../../substrate/frame/authorship", default-features = false } -pallet-insecure-randomness-collective-flip = { path = "../../../../../substrate/frame/insecure-randomness-collective-flip", default-features = false } -pallet-balances = { path = "../../../../../substrate/frame/balances", default-features = false } -pallet-multisig = { path = "../../../../../substrate/frame/multisig", default-features = false } -pallet-session = { path = "../../../../../substrate/frame/session", default-features = false } -pallet-timestamp = { path = "../../../../../substrate/frame/timestamp", default-features = false } -pallet-transaction-payment = { path = "../../../../../substrate/frame/transaction-payment", default-features = false } -pallet-transaction-payment-rpc-runtime-api = { path = "../../../../../substrate/frame/transaction-payment/rpc/runtime-api", default-features = false } -pallet-utility = { path = "../../../../../substrate/frame/utility", default-features = false } -pallet-sudo = { path = "../../../../../substrate/frame/sudo", default-features = false } -pallet-contracts = { path = "../../../../../substrate/frame/contracts", default-features = false } +sp-api = { workspace = true } +sp-block-builder = { workspace = true } +sp-consensus-aura = { workspace = true } +sp-core = { workspace = true } +sp-genesis-builder = { workspace = true } +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 } +frame-benchmarking = { optional = true, workspace = true } +frame-try-runtime = { optional = true, workspace = true } +frame-executive = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +frame-system-benchmarking = { optional = true, workspace = true } +frame-system-rpc-runtime-api = { workspace = true } +pallet-aura = { workspace = true } +pallet-authorship = { workspace = true } +pallet-insecure-randomness-collective-flip = { workspace = true } +pallet-balances = { workspace = true } +pallet-multisig = { workspace = true } +pallet-session = { workspace = true } +pallet-timestamp = { workspace = true } +pallet-transaction-payment = { workspace = true } +pallet-transaction-payment-rpc-runtime-api = { workspace = true } +pallet-utility = { workspace = true } +pallet-sudo = { workspace = true } +pallet-contracts = { workspace = true } # Polkadot -pallet-xcm = { path = "../../../../../polkadot/xcm/pallet-xcm", default-features = false } -polkadot-parachain-primitives = { path = "../../../../../polkadot/parachain", default-features = false } -polkadot-runtime-common = { path = "../../../../../polkadot/runtime/common", default-features = false } -rococo-runtime-constants = { path = "../../../../../polkadot/runtime/rococo/constants", default-features = false } -xcm = { package = "staging-xcm", path = "../../../../../polkadot/xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../../../polkadot/xcm/xcm-builder", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../../polkadot/xcm/xcm-executor", default-features = false } -xcm-fee-payment-runtime-api = { path = "../../../../../polkadot/xcm/xcm-fee-payment-runtime-api", default-features = false } +pallet-xcm = { workspace = true } +polkadot-parachain-primitives = { workspace = true } +polkadot-runtime-common = { workspace = true } +rococo-runtime-constants = { workspace = true } +xcm = { workspace = true } +xcm-builder = { workspace = true } +xcm-executor = { workspace = true } +xcm-runtime-apis = { workspace = true } # Cumulus -cumulus-pallet-aura-ext = { path = "../../../../pallets/aura-ext", default-features = false } -pallet-message-queue = { path = "../../../../../substrate/frame/message-queue", default-features = false } -cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false } -cumulus-pallet-session-benchmarking = { path = "../../../../pallets/session-benchmarking", default-features = false } -cumulus-pallet-xcm = { path = "../../../../pallets/xcm", default-features = false } -cumulus-pallet-xcmp-queue = { path = "../../../../pallets/xcmp-queue", default-features = false } -cumulus-primitives-aura = { path = "../../../../primitives/aura", default-features = false } -cumulus-primitives-core = { path = "../../../../primitives/core", default-features = false } -cumulus-primitives-utility = { path = "../../../../primitives/utility", default-features = false } -cumulus-primitives-storage-weight-reclaim = { path = "../../../../primitives/storage-weight-reclaim", default-features = false } +cumulus-pallet-aura-ext = { workspace = true } +pallet-message-queue = { workspace = true } +cumulus-pallet-parachain-system = { workspace = true } +cumulus-pallet-session-benchmarking = { workspace = true } +cumulus-pallet-xcm = { workspace = true } +cumulus-pallet-xcmp-queue = { workspace = true } +cumulus-primitives-aura = { workspace = true } +cumulus-primitives-core = { workspace = true } +cumulus-primitives-utility = { workspace = true } +cumulus-primitives-storage-weight-reclaim = { workspace = true } -pallet-collator-selection = { path = "../../../../pallets/collator-selection", default-features = false } -parachain-info = { package = "staging-parachain-info", path = "../../../pallets/parachain-info", default-features = false } -parachains-common = { path = "../../../common", default-features = false } -testnet-parachains-constants = { path = "../../constants", default-features = false, features = ["rococo"] } +pallet-collator-selection = { workspace = true } +parachain-info = { workspace = true } +parachains-common = { workspace = true } +testnet-parachains-constants = { features = ["rococo"], workspace = true } [features] default = ["std"] @@ -141,7 +141,7 @@ std = [ "testnet-parachains-constants/std", "xcm-builder/std", "xcm-executor/std", - "xcm-fee-payment-runtime-api/std", + "xcm-runtime-apis/std", "xcm/std", ] @@ -171,7 +171,7 @@ runtime-benchmarks = [ "sp-runtime/runtime-benchmarks", "xcm-builder/runtime-benchmarks", "xcm-executor/runtime-benchmarks", - "xcm-fee-payment-runtime-api/runtime-benchmarks", + "xcm-runtime-apis/runtime-benchmarks", ] try-runtime = [ diff --git a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs index 2d346e66c6c3b3f4a7e72072875646d9095a821a..ab779b31c72e1f8b9321cf6bf21ea67cd2b92598 100644 --- a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs @@ -50,7 +50,7 @@ use frame_support::{ dispatch::DispatchClass, genesis_builder_helper::{build_state, get_preset}, parameter_types, - traits::{ConstBool, ConstU16, ConstU32, ConstU64, ConstU8}, + traits::{ConstBool, ConstU32, ConstU64, ConstU8}, weights::{ConstantMultiplier, Weight, WeightToFee as _}, PalletId, }; @@ -64,7 +64,7 @@ pub use parachains_common::{AuraId, Balance}; use testnet_parachains_constants::rococo::{consensus::*, currency::*, fee::WeightToFee, time::*}; use xcm::prelude::*; use xcm_config::CollatorSelectionUpdateOrigin; -use xcm_fee_payment_runtime_api::{ +use xcm_runtime_apis::{ dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects}, fees::Error as XcmPaymentApiError, }; @@ -142,7 +142,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("contracts-rococo"), impl_name: create_runtime_str!("contracts-rococo"), authoring_version: 1, - spec_version: 1_012_000, + spec_version: 1_013_000, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 7, @@ -177,6 +177,7 @@ parameter_types! { }) .avg_block_initialization(AVERAGE_ON_INITIALIZE_RATIO) .build_or_panic(); + pub const SS58Prefix: u8 = 42; } // Configure FRAME pallets to include in runtime. @@ -193,7 +194,7 @@ impl frame_system::Config for Runtime { type Version = Version; type AccountData = pallet_balances::AccountData; type SystemWeightInfo = frame_system::weights::SubstrateWeight; - type SS58Prefix = ConstU16<42>; + type SS58Prefix = SS58Prefix; type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode; type MaxConsumers = ConstU32<16>; } @@ -590,7 +591,7 @@ impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::fees::XcmPaymentApi for Runtime { + impl xcm_runtime_apis::fees::XcmPaymentApi for Runtime { fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result, XcmPaymentApiError> { let acceptable_assets = vec![AssetId(xcm_config::RelayLocation::get())]; PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets) @@ -603,11 +604,11 @@ impl_runtime_apis! { Ok(WeightToFee::weight_to_fee(&weight)) }, Ok(asset_id) => { - log::trace!(target: "xcm::xcm_fee_payment_runtime_api", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); + log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); Err(XcmPaymentApiError::AssetNotFound) }, Err(_) => { - log::trace!(target: "xcm::xcm_fee_payment_runtime_api", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!"); + log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!"); Err(XcmPaymentApiError::VersionedConversionFailed) } } @@ -622,7 +623,7 @@ impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::dry_run::DryRunApi for Runtime { + impl xcm_runtime_apis::dry_run::DryRunApi for Runtime { fn dry_run_call(origin: OriginCaller, call: RuntimeCall) -> Result, XcmDryRunApiError> { PolkadotXcm::dry_run_call::(origin, call) } @@ -632,6 +633,18 @@ impl_runtime_apis! { } } + impl xcm_runtime_apis::conversions::LocationToAccountApi for Runtime { + fn convert_location(location: VersionedLocation) -> Result< + AccountId, + xcm_runtime_apis::conversions::Error + > { + xcm_runtime_apis::conversions::LocationToAccountHelper::< + AccountId, + xcm_config::LocationToAccountId + >::convert_location(location) + } + } + impl cumulus_primitives_core::CollectCollationInfo for Runtime { fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { ParachainSystem::collect_collation_info(header) diff --git a/cumulus/parachains/runtimes/coretime/coretime-rococo/Cargo.toml b/cumulus/parachains/runtimes/coretime/coretime-rococo/Cargo.toml index dc99fe331f78671b0b43842e0762db8bd96a840b..ebc0053308194e41bdd47a879e599c8826cdcc60 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-rococo/Cargo.toml +++ b/cumulus/parachains/runtimes/coretime/coretime-rococo/Cargo.toml @@ -10,74 +10,74 @@ license = "Apache-2.0" workspace = true [build-dependencies] -substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } +substrate-wasm-builder = { optional = true, workspace = true, default-features = true } [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -hex-literal = "0.4.1" +codec = { features = ["derive"], workspace = true } +hex-literal = { workspace = true, default-features = true } log = { workspace = true } -scale-info = { version = "2.9.0", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } serde = { optional = true, features = ["derive"], workspace = true, default-features = true } # Substrate -frame-benchmarking = { path = "../../../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-executive = { path = "../../../../../substrate/frame/executive", default-features = false } -frame-support = { path = "../../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../../substrate/frame/system", default-features = false } -frame-system-benchmarking = { path = "../../../../../substrate/frame/system/benchmarking", default-features = false, optional = true } -frame-system-rpc-runtime-api = { path = "../../../../../substrate/frame/system/rpc/runtime-api", default-features = false } -frame-try-runtime = { path = "../../../../../substrate/frame/try-runtime", default-features = false, optional = true } -pallet-aura = { path = "../../../../../substrate/frame/aura", default-features = false } -pallet-authorship = { path = "../../../../../substrate/frame/authorship", default-features = false } -pallet-balances = { path = "../../../../../substrate/frame/balances", default-features = false } -pallet-message-queue = { path = "../../../../../substrate/frame/message-queue", default-features = false } -pallet-broker = { path = "../../../../../substrate/frame/broker", default-features = false } -pallet-multisig = { path = "../../../../../substrate/frame/multisig", default-features = false } -pallet-session = { path = "../../../../../substrate/frame/session", default-features = false } -pallet-sudo = { path = "../../../../../substrate/frame/sudo", default-features = false } -pallet-timestamp = { path = "../../../../../substrate/frame/timestamp", default-features = false } -pallet-transaction-payment = { path = "../../../../../substrate/frame/transaction-payment", default-features = false } -pallet-transaction-payment-rpc-runtime-api = { path = "../../../../../substrate/frame/transaction-payment/rpc/runtime-api", default-features = false } -pallet-utility = { path = "../../../../../substrate/frame/utility", default-features = false } -sp-api = { path = "../../../../../substrate/primitives/api", default-features = false } -sp-block-builder = { path = "../../../../../substrate/primitives/block-builder", default-features = false } -sp-consensus-aura = { path = "../../../../../substrate/primitives/consensus/aura", default-features = false } -sp-core = { path = "../../../../../substrate/primitives/core", default-features = false } -sp-inherents = { path = "../../../../../substrate/primitives/inherents", default-features = false } -sp-genesis-builder = { path = "../../../../../substrate/primitives/genesis-builder", default-features = false } -sp-offchain = { path = "../../../../../substrate/primitives/offchain", default-features = false } -sp-runtime = { path = "../../../../../substrate/primitives/runtime", default-features = false } -sp-session = { path = "../../../../../substrate/primitives/session", default-features = false } -sp-std = { path = "../../../../../substrate/primitives/std", default-features = false } -sp-storage = { path = "../../../../../substrate/primitives/storage", default-features = false } -sp-transaction-pool = { path = "../../../../../substrate/primitives/transaction-pool", default-features = false } -sp-version = { path = "../../../../../substrate/primitives/version", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +frame-executive = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +frame-system-benchmarking = { optional = true, workspace = true } +frame-system-rpc-runtime-api = { workspace = true } +frame-try-runtime = { optional = true, workspace = true } +pallet-aura = { workspace = true } +pallet-authorship = { workspace = true } +pallet-balances = { workspace = true } +pallet-message-queue = { workspace = true } +pallet-broker = { workspace = true } +pallet-multisig = { workspace = true } +pallet-session = { workspace = true } +pallet-sudo = { workspace = true } +pallet-timestamp = { workspace = true } +pallet-transaction-payment = { workspace = true } +pallet-transaction-payment-rpc-runtime-api = { workspace = true } +pallet-utility = { workspace = true } +sp-api = { workspace = true } +sp-block-builder = { workspace = true } +sp-consensus-aura = { workspace = true } +sp-core = { workspace = true } +sp-inherents = { workspace = true } +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 } # Polkadot -pallet-xcm = { path = "../../../../../polkadot/xcm/pallet-xcm", default-features = false } -pallet-xcm-benchmarks = { path = "../../../../../polkadot/xcm/pallet-xcm-benchmarks", default-features = false, optional = true } -polkadot-parachain-primitives = { path = "../../../../../polkadot/parachain", default-features = false } -polkadot-runtime-common = { path = "../../../../../polkadot/runtime/common", default-features = false } -rococo-runtime-constants = { path = "../../../../../polkadot/runtime/rococo/constants", default-features = false } -xcm = { package = "staging-xcm", path = "../../../../../polkadot/xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../../../polkadot/xcm/xcm-builder", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../../polkadot/xcm/xcm-executor", default-features = false } -xcm-fee-payment-runtime-api = { path = "../../../../../polkadot/xcm/xcm-fee-payment-runtime-api", default-features = false } +pallet-xcm = { workspace = true } +pallet-xcm-benchmarks = { optional = true, workspace = true } +polkadot-parachain-primitives = { workspace = true } +polkadot-runtime-common = { workspace = true } +rococo-runtime-constants = { workspace = true } +xcm = { workspace = true } +xcm-builder = { workspace = true } +xcm-executor = { workspace = true } +xcm-runtime-apis = { workspace = true } # Cumulus -cumulus-pallet-aura-ext = { path = "../../../../pallets/aura-ext", default-features = false } -cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false } -cumulus-pallet-session-benchmarking = { path = "../../../../pallets/session-benchmarking", default-features = false } -cumulus-pallet-xcm = { path = "../../../../pallets/xcm", default-features = false } -cumulus-pallet-xcmp-queue = { path = "../../../../pallets/xcmp-queue", default-features = false } -cumulus-primitives-aura = { path = "../../../../primitives/aura", default-features = false } -cumulus-primitives-core = { path = "../../../../primitives/core", default-features = false } -cumulus-primitives-utility = { path = "../../../../primitives/utility", default-features = false } -cumulus-primitives-storage-weight-reclaim = { path = "../../../../primitives/storage-weight-reclaim", default-features = false } -pallet-collator-selection = { path = "../../../../pallets/collator-selection", default-features = false } -parachain-info = { package = "staging-parachain-info", path = "../../../pallets/parachain-info", default-features = false } -parachains-common = { path = "../../../common", default-features = false } -testnet-parachains-constants = { path = "../../constants", default-features = false, features = ["rococo"] } +cumulus-pallet-aura-ext = { workspace = true } +cumulus-pallet-parachain-system = { workspace = true } +cumulus-pallet-session-benchmarking = { workspace = true } +cumulus-pallet-xcm = { workspace = true } +cumulus-pallet-xcmp-queue = { workspace = true } +cumulus-primitives-aura = { workspace = true } +cumulus-primitives-core = { workspace = true } +cumulus-primitives-utility = { workspace = true } +cumulus-primitives-storage-weight-reclaim = { workspace = true } +pallet-collator-selection = { workspace = true } +parachain-info = { workspace = true } +parachains-common = { workspace = true } +testnet-parachains-constants = { features = ["rococo"], workspace = true } [features] default = ["std"] @@ -139,7 +139,7 @@ std = [ "testnet-parachains-constants/std", "xcm-builder/std", "xcm-executor/std", - "xcm-fee-payment-runtime-api/std", + "xcm-runtime-apis/std", "xcm/std", ] @@ -169,7 +169,7 @@ runtime-benchmarks = [ "sp-runtime/runtime-benchmarks", "xcm-builder/runtime-benchmarks", "xcm-executor/runtime-benchmarks", - "xcm-fee-payment-runtime-api/runtime-benchmarks", + "xcm-runtime-apis/runtime-benchmarks", ] try-runtime = [ diff --git a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/lib.rs b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/lib.rs index b3eaf3d127a2f6f6acb8b161f1fcbd8bdb479d36..34f7fa4d3ecc1329baa08f602aaca562e7ed28e9 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-rococo/src/lib.rs @@ -76,7 +76,7 @@ use xcm::prelude::*; use xcm_config::{ FellowshipLocation, GovernanceLocation, RocRelayLocation, XcmOriginToTransactDispatchOrigin, }; -use xcm_fee_payment_runtime_api::{ +use xcm_runtime_apis::{ dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects}, fees::Error as XcmPaymentApiError, }; @@ -142,7 +142,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("coretime-rococo"), impl_name: create_runtime_str!("coretime-rococo"), authoring_version: 1, - spec_version: 1_012_000, + spec_version: 1_013_000, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 1, @@ -660,7 +660,7 @@ impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::fees::XcmPaymentApi for Runtime { + impl xcm_runtime_apis::fees::XcmPaymentApi for Runtime { fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result, XcmPaymentApiError> { let acceptable_assets = vec![AssetId(xcm_config::RocRelayLocation::get())]; PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets) @@ -673,11 +673,11 @@ impl_runtime_apis! { Ok(WeightToFee::weight_to_fee(&weight)) }, Ok(asset_id) => { - log::trace!(target: "xcm::xcm_fee_payment_runtime_api", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); + log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); Err(XcmPaymentApiError::AssetNotFound) }, Err(_) => { - log::trace!(target: "xcm::xcm_fee_payment_runtime_api", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!"); + log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!"); Err(XcmPaymentApiError::VersionedConversionFailed) } } @@ -692,7 +692,7 @@ impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::dry_run::DryRunApi for Runtime { + impl xcm_runtime_apis::dry_run::DryRunApi for Runtime { fn dry_run_call(origin: OriginCaller, call: RuntimeCall) -> Result, XcmDryRunApiError> { PolkadotXcm::dry_run_call::(origin, call) } @@ -702,6 +702,18 @@ impl_runtime_apis! { } } + impl xcm_runtime_apis::conversions::LocationToAccountApi for Runtime { + fn convert_location(location: VersionedLocation) -> Result< + AccountId, + xcm_runtime_apis::conversions::Error + > { + xcm_runtime_apis::conversions::LocationToAccountHelper::< + AccountId, + xcm_config::LocationToAccountId, + >::convert_location(location) + } + } + impl cumulus_primitives_core::CollectCollationInfo for Runtime { fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { ParachainSystem::collect_collation_info(header) diff --git a/cumulus/parachains/runtimes/coretime/coretime-westend/Cargo.toml b/cumulus/parachains/runtimes/coretime/coretime-westend/Cargo.toml index 78018537f5d3ce07d75ed8a465d5e17dba157028..10edf7fac8536af4e26234420e541c2622615308 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-westend/Cargo.toml +++ b/cumulus/parachains/runtimes/coretime/coretime-westend/Cargo.toml @@ -10,74 +10,74 @@ license = "Apache-2.0" workspace = true [build-dependencies] -substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } +substrate-wasm-builder = { optional = true, workspace = true, default-features = true } [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -hex-literal = "0.4.1" +codec = { features = ["derive"], workspace = true } +hex-literal = { workspace = true, default-features = true } log = { workspace = true } -scale-info = { version = "2.9.0", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } serde = { optional = true, features = ["derive"], workspace = true, default-features = true } # Substrate -frame-benchmarking = { path = "../../../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-executive = { path = "../../../../../substrate/frame/executive", default-features = false } -frame-support = { path = "../../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../../substrate/frame/system", default-features = false } -frame-system-benchmarking = { path = "../../../../../substrate/frame/system/benchmarking", default-features = false, optional = true } -frame-system-rpc-runtime-api = { path = "../../../../../substrate/frame/system/rpc/runtime-api", default-features = false } -frame-try-runtime = { path = "../../../../../substrate/frame/try-runtime", default-features = false, optional = true } -pallet-aura = { path = "../../../../../substrate/frame/aura", default-features = false } -pallet-authorship = { path = "../../../../../substrate/frame/authorship", default-features = false } -pallet-balances = { path = "../../../../../substrate/frame/balances", default-features = false } -pallet-message-queue = { path = "../../../../../substrate/frame/message-queue", default-features = false } -pallet-broker = { path = "../../../../../substrate/frame/broker", default-features = false } -pallet-multisig = { path = "../../../../../substrate/frame/multisig", default-features = false } -pallet-session = { path = "../../../../../substrate/frame/session", default-features = false } -pallet-timestamp = { path = "../../../../../substrate/frame/timestamp", default-features = false } -pallet-transaction-payment = { path = "../../../../../substrate/frame/transaction-payment", default-features = false } -pallet-transaction-payment-rpc-runtime-api = { path = "../../../../../substrate/frame/transaction-payment/rpc/runtime-api", default-features = false } -pallet-utility = { path = "../../../../../substrate/frame/utility", default-features = false } -sp-api = { path = "../../../../../substrate/primitives/api", default-features = false } -sp-block-builder = { path = "../../../../../substrate/primitives/block-builder", default-features = false } -sp-consensus-aura = { path = "../../../../../substrate/primitives/consensus/aura", default-features = false } -sp-core = { path = "../../../../../substrate/primitives/core", default-features = false } -sp-inherents = { path = "../../../../../substrate/primitives/inherents", default-features = false } -sp-genesis-builder = { path = "../../../../../substrate/primitives/genesis-builder", default-features = false } -sp-offchain = { path = "../../../../../substrate/primitives/offchain", default-features = false } -sp-runtime = { path = "../../../../../substrate/primitives/runtime", default-features = false } -sp-session = { path = "../../../../../substrate/primitives/session", default-features = false } -sp-std = { path = "../../../../../substrate/primitives/std", default-features = false } -sp-storage = { path = "../../../../../substrate/primitives/storage", default-features = false } -sp-transaction-pool = { path = "../../../../../substrate/primitives/transaction-pool", default-features = false } -sp-version = { path = "../../../../../substrate/primitives/version", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +frame-executive = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +frame-system-benchmarking = { optional = true, workspace = true } +frame-system-rpc-runtime-api = { workspace = true } +frame-try-runtime = { optional = true, workspace = true } +pallet-aura = { workspace = true } +pallet-authorship = { workspace = true } +pallet-balances = { workspace = true } +pallet-message-queue = { workspace = true } +pallet-broker = { workspace = true } +pallet-multisig = { workspace = true } +pallet-session = { workspace = true } +pallet-timestamp = { workspace = true } +pallet-transaction-payment = { workspace = true } +pallet-transaction-payment-rpc-runtime-api = { workspace = true } +pallet-utility = { workspace = true } +sp-api = { workspace = true } +sp-block-builder = { workspace = true } +sp-consensus-aura = { workspace = true } +sp-core = { workspace = true } +sp-inherents = { workspace = true } +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 } # Polkadot -pallet-xcm = { path = "../../../../../polkadot/xcm/pallet-xcm", default-features = false } -pallet-xcm-benchmarks = { path = "../../../../../polkadot/xcm/pallet-xcm-benchmarks", default-features = false, optional = true } -polkadot-parachain-primitives = { path = "../../../../../polkadot/parachain", default-features = false } -polkadot-runtime-common = { path = "../../../../../polkadot/runtime/common", default-features = false } -westend-runtime-constants = { path = "../../../../../polkadot/runtime/westend/constants", default-features = false } -xcm = { package = "staging-xcm", path = "../../../../../polkadot/xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../../../polkadot/xcm/xcm-builder", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../../polkadot/xcm/xcm-executor", default-features = false } -xcm-fee-payment-runtime-api = { path = "../../../../../polkadot/xcm/xcm-fee-payment-runtime-api", default-features = false } +pallet-xcm = { workspace = true } +pallet-xcm-benchmarks = { optional = true, workspace = true } +polkadot-parachain-primitives = { workspace = true } +polkadot-runtime-common = { workspace = true } +westend-runtime-constants = { workspace = true } +xcm = { workspace = true } +xcm-builder = { workspace = true } +xcm-executor = { workspace = true } +xcm-runtime-apis = { workspace = true } # Cumulus -cumulus-pallet-aura-ext = { path = "../../../../pallets/aura-ext", default-features = false } -cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false } -cumulus-pallet-session-benchmarking = { path = "../../../../pallets/session-benchmarking", default-features = false } -cumulus-pallet-xcm = { path = "../../../../pallets/xcm", default-features = false } -cumulus-pallet-xcmp-queue = { path = "../../../../pallets/xcmp-queue", default-features = false } -cumulus-primitives-aura = { path = "../../../../primitives/aura", default-features = false } -cumulus-primitives-core = { path = "../../../../primitives/core", default-features = false } -cumulus-primitives-utility = { path = "../../../../primitives/utility", default-features = false } -cumulus-primitives-storage-weight-reclaim = { path = "../../../../primitives/storage-weight-reclaim", default-features = false } +cumulus-pallet-aura-ext = { workspace = true } +cumulus-pallet-parachain-system = { workspace = true } +cumulus-pallet-session-benchmarking = { workspace = true } +cumulus-pallet-xcm = { workspace = true } +cumulus-pallet-xcmp-queue = { workspace = true } +cumulus-primitives-aura = { workspace = true } +cumulus-primitives-core = { workspace = true } +cumulus-primitives-utility = { workspace = true } +cumulus-primitives-storage-weight-reclaim = { workspace = true } -pallet-collator-selection = { path = "../../../../pallets/collator-selection", default-features = false } -parachain-info = { package = "staging-parachain-info", path = "../../../pallets/parachain-info", default-features = false } -parachains-common = { path = "../../../common", default-features = false } -testnet-parachains-constants = { path = "../../constants", default-features = false, features = ["westend"] } +pallet-collator-selection = { workspace = true } +parachain-info = { workspace = true } +parachains-common = { workspace = true } +testnet-parachains-constants = { features = ["westend"], workspace = true } [features] default = ["std"] @@ -138,7 +138,7 @@ std = [ "westend-runtime-constants/std", "xcm-builder/std", "xcm-executor/std", - "xcm-fee-payment-runtime-api/std", + "xcm-runtime-apis/std", "xcm/std", ] @@ -167,7 +167,7 @@ runtime-benchmarks = [ "sp-runtime/runtime-benchmarks", "xcm-builder/runtime-benchmarks", "xcm-executor/runtime-benchmarks", - "xcm-fee-payment-runtime-api/runtime-benchmarks", + "xcm-runtime-apis/runtime-benchmarks", ] try-runtime = [ diff --git a/cumulus/parachains/runtimes/coretime/coretime-westend/src/lib.rs b/cumulus/parachains/runtimes/coretime/coretime-westend/src/lib.rs index 6c22702ce872fe28e5acc9783c263bedbc135dee..4b2f494c8909991fa6722e25d16ce1a2bc5d9f4b 100644 --- a/cumulus/parachains/runtimes/coretime/coretime-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/coretime/coretime-westend/src/lib.rs @@ -76,7 +76,7 @@ use xcm::prelude::*; use xcm_config::{ FellowshipLocation, GovernanceLocation, TokenRelayLocation, XcmOriginToTransactDispatchOrigin, }; -use xcm_fee_payment_runtime_api::{ +use xcm_runtime_apis::{ dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects}, fees::Error as XcmPaymentApiError, }; @@ -141,7 +141,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("coretime-westend"), impl_name: create_runtime_str!("coretime-westend"), authoring_version: 1, - spec_version: 1_012_000, + spec_version: 1_013_000, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 1, @@ -651,7 +651,7 @@ impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::fees::XcmPaymentApi for Runtime { + impl xcm_runtime_apis::fees::XcmPaymentApi for Runtime { fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result, XcmPaymentApiError> { let acceptable_assets = vec![AssetId(xcm_config::TokenRelayLocation::get())]; PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets) @@ -664,11 +664,11 @@ impl_runtime_apis! { Ok(WeightToFee::weight_to_fee(&weight)) }, Ok(asset_id) => { - log::trace!(target: "xcm::xcm_fee_payment_runtime_api", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); + log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); Err(XcmPaymentApiError::AssetNotFound) }, Err(_) => { - log::trace!(target: "xcm::xcm_fee_payment_runtime_api", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!"); + log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!"); Err(XcmPaymentApiError::VersionedConversionFailed) } } @@ -683,7 +683,7 @@ impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::dry_run::DryRunApi for Runtime { + impl xcm_runtime_apis::dry_run::DryRunApi for Runtime { fn dry_run_call(origin: OriginCaller, call: RuntimeCall) -> Result, XcmDryRunApiError> { PolkadotXcm::dry_run_call::(origin, call) } @@ -693,6 +693,18 @@ impl_runtime_apis! { } } + impl xcm_runtime_apis::conversions::LocationToAccountApi for Runtime { + fn convert_location(location: VersionedLocation) -> Result< + AccountId, + xcm_runtime_apis::conversions::Error + > { + xcm_runtime_apis::conversions::LocationToAccountHelper::< + AccountId, + xcm_config::LocationToAccountId, + >::convert_location(location) + } + } + impl cumulus_primitives_core::CollectCollationInfo for Runtime { fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { ParachainSystem::collect_collation_info(header) diff --git a/cumulus/parachains/runtimes/glutton/glutton-westend/Cargo.toml b/cumulus/parachains/runtimes/glutton/glutton-westend/Cargo.toml index 92a5bbbd1376088909f315371dff6be13ffa69af..c201c8375be0d900d3797b11d2597e120eef873c 100644 --- a/cumulus/parachains/runtimes/glutton/glutton-westend/Cargo.toml +++ b/cumulus/parachains/runtimes/glutton/glutton-westend/Cargo.toml @@ -10,54 +10,54 @@ description = "Glutton parachain runtime." workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } # Substrate -frame-benchmarking = { path = "../../../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-executive = { path = "../../../../../substrate/frame/executive", default-features = false } -frame-support = { path = "../../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../../substrate/frame/system", default-features = false } -frame-system-rpc-runtime-api = { path = "../../../../../substrate/frame/system/rpc/runtime-api", default-features = false } -frame-system-benchmarking = { path = "../../../../../substrate/frame/system/benchmarking", default-features = false, optional = true } -frame-try-runtime = { path = "../../../../../substrate/frame/try-runtime", default-features = false, optional = true } -pallet-aura = { path = "../../../../../substrate/frame/aura", default-features = false } -pallet-glutton = { path = "../../../../../substrate/frame/glutton", default-features = false } -pallet-sudo = { path = "../../../../../substrate/frame/sudo", default-features = false } -pallet-timestamp = { path = "../../../../../substrate/frame/timestamp", default-features = false } -sp-api = { path = "../../../../../substrate/primitives/api", default-features = false } -sp-block-builder = { path = "../../../../../substrate/primitives/block-builder", default-features = false } -sp-consensus-aura = { path = "../../../../../substrate/primitives/consensus/aura", default-features = false } -sp-core = { path = "../../../../../substrate/primitives/core", default-features = false } -sp-genesis-builder = { path = "../../../../../substrate/primitives/genesis-builder", default-features = false } -sp-inherents = { path = "../../../../../substrate/primitives/inherents", default-features = false } -pallet-message-queue = { path = "../../../../../substrate/frame/message-queue", default-features = false } -sp-offchain = { path = "../../../../../substrate/primitives/offchain", default-features = false } -sp-runtime = { path = "../../../../../substrate/primitives/runtime", default-features = false } -sp-session = { path = "../../../../../substrate/primitives/session", default-features = false } -sp-std = { path = "../../../../../substrate/primitives/std", default-features = false } -sp-storage = { path = "../../../../../substrate/primitives/storage", default-features = false } -sp-transaction-pool = { path = "../../../../../substrate/primitives/transaction-pool", default-features = false } -sp-version = { path = "../../../../../substrate/primitives/version", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +frame-executive = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +frame-system-rpc-runtime-api = { workspace = true } +frame-system-benchmarking = { optional = true, workspace = true } +frame-try-runtime = { optional = true, workspace = true } +pallet-aura = { workspace = true } +pallet-glutton = { workspace = true } +pallet-sudo = { workspace = true } +pallet-timestamp = { workspace = true } +sp-api = { workspace = true } +sp-block-builder = { workspace = true } +sp-consensus-aura = { workspace = true } +sp-core = { workspace = true } +sp-genesis-builder = { workspace = true } +sp-inherents = { workspace = true } +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 } # Polkadot -xcm = { package = "staging-xcm", path = "../../../../../polkadot/xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../../../polkadot/xcm/xcm-builder", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../../polkadot/xcm/xcm-executor", default-features = false } +xcm = { workspace = true } +xcm-builder = { workspace = true } +xcm-executor = { workspace = true } # Cumulus -cumulus-pallet-aura-ext = { path = "../../../../pallets/aura-ext", default-features = false } -cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false } -cumulus-pallet-xcm = { path = "../../../../pallets/xcm", default-features = false } -cumulus-primitives-aura = { path = "../../../../primitives/aura", default-features = false } -cumulus-primitives-core = { path = "../../../../primitives/core", default-features = false } -cumulus-primitives-timestamp = { path = "../../../../primitives/timestamp", default-features = false } -parachain-info = { package = "staging-parachain-info", path = "../../../pallets/parachain-info", default-features = false } -parachains-common = { path = "../../../common", default-features = false } -testnet-parachains-constants = { path = "../../constants", default-features = false, features = ["westend"] } +cumulus-pallet-aura-ext = { workspace = true } +cumulus-pallet-parachain-system = { workspace = true } +cumulus-pallet-xcm = { workspace = true } +cumulus-primitives-aura = { workspace = true } +cumulus-primitives-core = { workspace = true } +cumulus-primitives-timestamp = { workspace = true } +parachain-info = { workspace = true } +parachains-common = { workspace = true } +testnet-parachains-constants = { features = ["westend"], workspace = true } [build-dependencies] -substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder" } +substrate-wasm-builder = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/cumulus/parachains/runtimes/glutton/glutton-westend/src/lib.rs b/cumulus/parachains/runtimes/glutton/glutton-westend/src/lib.rs index 4092fb78594d205d8ad9ddf7d8268c4fa4db27db..b8a328c3db696100a558e355286463e524f2f931 100644 --- a/cumulus/parachains/runtimes/glutton/glutton-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/glutton/glutton-westend/src/lib.rs @@ -100,7 +100,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("glutton-westend"), impl_name: create_runtime_str!("glutton-westend"), authoring_version: 1, - spec_version: 1_012_000, + spec_version: 1_013_000, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 1, @@ -296,6 +296,7 @@ pub type SignedExtra = ( frame_system::CheckGenesis, frame_system::CheckEra, frame_system::CheckNonce, + frame_system::CheckWeight, ); /// Unchecked extrinsic type as expected by this runtime. pub type UncheckedExtrinsic = diff --git a/cumulus/parachains/runtimes/people/people-rococo/Cargo.toml b/cumulus/parachains/runtimes/people/people-rococo/Cargo.toml index d4e65da3cd6426f7a21a2c96d03d53d8161410fb..890de672e0b5ed74a11435a28dc9f81bbde9297b 100644 --- a/cumulus/parachains/runtimes/people/people-rococo/Cargo.toml +++ b/cumulus/parachains/runtimes/people/people-rococo/Cargo.toml @@ -7,74 +7,74 @@ description = "Rococo's People parachain runtime" license = "Apache-2.0" [build-dependencies] -substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } +substrate-wasm-builder = { optional = true, workspace = true, default-features = true } [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -enumflags2 = { version = "0.7.7" } -hex-literal = { version = "0.4.1" } +codec = { features = ["derive"], workspace = true } +enumflags2 = { workspace = true } +hex-literal = { workspace = true, default-features = true } log = { workspace = true } -scale-info = { version = "2.9.0", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } serde = { optional = true, features = ["derive"], workspace = true, default-features = true } # Substrate -frame-benchmarking = { path = "../../../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-executive = { path = "../../../../../substrate/frame/executive", default-features = false } -frame-support = { path = "../../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../../substrate/frame/system", default-features = false } -frame-system-benchmarking = { path = "../../../../../substrate/frame/system/benchmarking", default-features = false, optional = true } -frame-system-rpc-runtime-api = { path = "../../../../../substrate/frame/system/rpc/runtime-api", default-features = false } -frame-try-runtime = { path = "../../../../../substrate/frame/try-runtime", default-features = false, optional = true } -pallet-aura = { path = "../../../../../substrate/frame/aura", default-features = false } -pallet-authorship = { path = "../../../../../substrate/frame/authorship", default-features = false } -pallet-balances = { path = "../../../../../substrate/frame/balances", default-features = false } -pallet-identity = { path = "../../../../../substrate/frame/identity", default-features = false } -pallet-message-queue = { path = "../../../../../substrate/frame/message-queue", default-features = false } -pallet-multisig = { path = "../../../../../substrate/frame/multisig", default-features = false } -pallet-session = { path = "../../../../../substrate/frame/session", default-features = false } -pallet-timestamp = { path = "../../../../../substrate/frame/timestamp", default-features = false } -pallet-transaction-payment = { path = "../../../../../substrate/frame/transaction-payment", default-features = false } -pallet-transaction-payment-rpc-runtime-api = { path = "../../../../../substrate/frame/transaction-payment/rpc/runtime-api", default-features = false } -pallet-utility = { path = "../../../../../substrate/frame/utility", default-features = false } -sp-api = { path = "../../../../../substrate/primitives/api", default-features = false } -sp-block-builder = { path = "../../../../../substrate/primitives/block-builder", default-features = false } -sp-consensus-aura = { path = "../../../../../substrate/primitives/consensus/aura", default-features = false } -sp-core = { path = "../../../../../substrate/primitives/core", default-features = false } -sp-genesis-builder = { path = "../../../../../substrate/primitives/genesis-builder", default-features = false } -sp-inherents = { path = "../../../../../substrate/primitives/inherents", default-features = false } -sp-offchain = { path = "../../../../../substrate/primitives/offchain", default-features = false } -sp-runtime = { path = "../../../../../substrate/primitives/runtime", default-features = false } -sp-session = { path = "../../../../../substrate/primitives/session", default-features = false } -sp-std = { path = "../../../../../substrate/primitives/std", default-features = false } -sp-storage = { path = "../../../../../substrate/primitives/storage", default-features = false } -sp-transaction-pool = { path = "../../../../../substrate/primitives/transaction-pool", default-features = false } -sp-version = { path = "../../../../../substrate/primitives/version", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +frame-executive = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +frame-system-benchmarking = { optional = true, workspace = true } +frame-system-rpc-runtime-api = { workspace = true } +frame-try-runtime = { optional = true, workspace = true } +pallet-aura = { workspace = true } +pallet-authorship = { workspace = true } +pallet-balances = { workspace = true } +pallet-identity = { workspace = true } +pallet-message-queue = { workspace = true } +pallet-multisig = { workspace = true } +pallet-session = { workspace = true } +pallet-timestamp = { workspace = true } +pallet-transaction-payment = { workspace = true } +pallet-transaction-payment-rpc-runtime-api = { workspace = true } +pallet-utility = { workspace = true } +sp-api = { workspace = true } +sp-block-builder = { workspace = true } +sp-consensus-aura = { workspace = true } +sp-core = { workspace = true } +sp-genesis-builder = { workspace = true } +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 } # Polkadot -pallet-xcm = { path = "../../../../../polkadot/xcm/pallet-xcm", default-features = false } -pallet-xcm-benchmarks = { path = "../../../../../polkadot/xcm/pallet-xcm-benchmarks", default-features = false, optional = true } -polkadot-parachain-primitives = { path = "../../../../../polkadot/parachain", default-features = false } -polkadot-runtime-common = { path = "../../../../../polkadot/runtime/common", default-features = false } -rococo-runtime-constants = { path = "../../../../../polkadot/runtime/rococo/constants", default-features = false } -xcm = { package = "staging-xcm", path = "../../../../../polkadot/xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../../../polkadot/xcm/xcm-builder", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../../polkadot/xcm/xcm-executor", default-features = false } -xcm-fee-payment-runtime-api = { path = "../../../../../polkadot/xcm/xcm-fee-payment-runtime-api", default-features = false } +pallet-xcm = { workspace = true } +pallet-xcm-benchmarks = { optional = true, workspace = true } +polkadot-parachain-primitives = { workspace = true } +polkadot-runtime-common = { workspace = true } +rococo-runtime-constants = { workspace = true } +xcm = { workspace = true } +xcm-builder = { workspace = true } +xcm-executor = { workspace = true } +xcm-runtime-apis = { workspace = true } # Cumulus -cumulus-pallet-aura-ext = { path = "../../../../pallets/aura-ext", default-features = false } -cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false } -cumulus-pallet-session-benchmarking = { path = "../../../../pallets/session-benchmarking", default-features = false } -cumulus-pallet-xcm = { path = "../../../../pallets/xcm", default-features = false } -cumulus-pallet-xcmp-queue = { path = "../../../../pallets/xcmp-queue", default-features = false } -cumulus-primitives-aura = { path = "../../../../primitives/aura", default-features = false } -cumulus-primitives-core = { path = "../../../../primitives/core", default-features = false } -cumulus-primitives-utility = { path = "../../../../primitives/utility", default-features = false } -cumulus-primitives-storage-weight-reclaim = { path = "../../../../primitives/storage-weight-reclaim", default-features = false } -pallet-collator-selection = { path = "../../../../pallets/collator-selection", default-features = false } -parachain-info = { package = "staging-parachain-info", path = "../../../pallets/parachain-info", default-features = false } -parachains-common = { path = "../../../common", default-features = false } -testnet-parachains-constants = { path = "../../constants", default-features = false, features = ["rococo"] } +cumulus-pallet-aura-ext = { workspace = true } +cumulus-pallet-parachain-system = { workspace = true } +cumulus-pallet-session-benchmarking = { workspace = true } +cumulus-pallet-xcm = { workspace = true } +cumulus-pallet-xcmp-queue = { workspace = true } +cumulus-primitives-aura = { workspace = true } +cumulus-primitives-core = { workspace = true } +cumulus-primitives-utility = { workspace = true } +cumulus-primitives-storage-weight-reclaim = { workspace = true } +pallet-collator-selection = { workspace = true } +parachain-info = { workspace = true } +parachains-common = { workspace = true } +testnet-parachains-constants = { features = ["rococo"], workspace = true } [features] default = ["std"] @@ -136,7 +136,7 @@ std = [ "testnet-parachains-constants/std", "xcm-builder/std", "xcm-executor/std", - "xcm-fee-payment-runtime-api/std", + "xcm-runtime-apis/std", "xcm/std", ] @@ -165,7 +165,7 @@ runtime-benchmarks = [ "sp-runtime/runtime-benchmarks", "xcm-builder/runtime-benchmarks", "xcm-executor/runtime-benchmarks", - "xcm-fee-payment-runtime-api/runtime-benchmarks", + "xcm-runtime-apis/runtime-benchmarks", ] try-runtime = [ diff --git a/cumulus/parachains/runtimes/people/people-rococo/src/lib.rs b/cumulus/parachains/runtimes/people/people-rococo/src/lib.rs index c80f6879fb3448b7b20dd81c387d3ce6c3a3ea90..63dd863a861b6ebaef8b0d4cbb395fe096bb283a 100644 --- a/cumulus/parachains/runtimes/people/people-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/people/people-rococo/src/lib.rs @@ -70,7 +70,7 @@ use xcm_config::{ FellowshipLocation, GovernanceLocation, PriceForSiblingParachainDelivery, XcmConfig, XcmOriginToTransactDispatchOrigin, }; -use xcm_fee_payment_runtime_api::{ +use xcm_runtime_apis::{ dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects}, fees::Error as XcmPaymentApiError, }; @@ -132,7 +132,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("people-rococo"), impl_name: create_runtime_str!("people-rococo"), authoring_version: 1, - spec_version: 1_012_000, + spec_version: 1_013_000, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 1, @@ -625,7 +625,7 @@ impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::fees::XcmPaymentApi for Runtime { + impl xcm_runtime_apis::fees::XcmPaymentApi for Runtime { fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result, XcmPaymentApiError> { let acceptable_assets = vec![AssetId(xcm_config::RelayLocation::get())]; PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets) @@ -638,11 +638,11 @@ impl_runtime_apis! { Ok(WeightToFee::weight_to_fee(&weight)) }, Ok(asset_id) => { - log::trace!(target: "xcm::xcm_fee_payment_runtime_api", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); + log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); Err(XcmPaymentApiError::AssetNotFound) }, Err(_) => { - log::trace!(target: "xcm::xcm_fee_payment_runtime_api", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!"); + log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!"); Err(XcmPaymentApiError::VersionedConversionFailed) } } @@ -657,7 +657,7 @@ impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::dry_run::DryRunApi for Runtime { + impl xcm_runtime_apis::dry_run::DryRunApi for Runtime { fn dry_run_call(origin: OriginCaller, call: RuntimeCall) -> Result, XcmDryRunApiError> { PolkadotXcm::dry_run_call::(origin, call) } @@ -667,6 +667,18 @@ impl_runtime_apis! { } } + impl xcm_runtime_apis::conversions::LocationToAccountApi for Runtime { + fn convert_location(location: VersionedLocation) -> Result< + AccountId, + xcm_runtime_apis::conversions::Error + > { + xcm_runtime_apis::conversions::LocationToAccountHelper::< + AccountId, + xcm_config::LocationToAccountId, + >::convert_location(location) + } + } + impl cumulus_primitives_core::CollectCollationInfo for Runtime { fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { ParachainSystem::collect_collation_info(header) diff --git a/cumulus/parachains/runtimes/people/people-westend/Cargo.toml b/cumulus/parachains/runtimes/people/people-westend/Cargo.toml index b040613d19e75a51d3008af0f71aa7953e82be29..83068e489d2ebb3919d20ac7747d5236ceb5aeb7 100644 --- a/cumulus/parachains/runtimes/people/people-westend/Cargo.toml +++ b/cumulus/parachains/runtimes/people/people-westend/Cargo.toml @@ -7,74 +7,74 @@ description = "Westend's People parachain runtime" license = "Apache-2.0" [build-dependencies] -substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } +substrate-wasm-builder = { optional = true, workspace = true, default-features = true } [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -enumflags2 = { version = "0.7.7" } -hex-literal = { version = "0.4.1" } +codec = { features = ["derive"], workspace = true } +enumflags2 = { workspace = true } +hex-literal = { workspace = true, default-features = true } log = { workspace = true } -scale-info = { version = "2.9.0", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } serde = { optional = true, features = ["derive"], workspace = true, default-features = true } # Substrate -frame-benchmarking = { path = "../../../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-executive = { path = "../../../../../substrate/frame/executive", default-features = false } -frame-support = { path = "../../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../../substrate/frame/system", default-features = false } -frame-system-benchmarking = { path = "../../../../../substrate/frame/system/benchmarking", default-features = false, optional = true } -frame-system-rpc-runtime-api = { path = "../../../../../substrate/frame/system/rpc/runtime-api", default-features = false } -frame-try-runtime = { path = "../../../../../substrate/frame/try-runtime", default-features = false, optional = true } -pallet-aura = { path = "../../../../../substrate/frame/aura", default-features = false } -pallet-authorship = { path = "../../../../../substrate/frame/authorship", default-features = false } -pallet-balances = { path = "../../../../../substrate/frame/balances", default-features = false } -pallet-identity = { path = "../../../../../substrate/frame/identity", default-features = false } -pallet-message-queue = { path = "../../../../../substrate/frame/message-queue", default-features = false } -pallet-multisig = { path = "../../../../../substrate/frame/multisig", default-features = false } -pallet-session = { path = "../../../../../substrate/frame/session", default-features = false } -pallet-timestamp = { path = "../../../../../substrate/frame/timestamp", default-features = false } -pallet-transaction-payment = { path = "../../../../../substrate/frame/transaction-payment", default-features = false } -pallet-transaction-payment-rpc-runtime-api = { path = "../../../../../substrate/frame/transaction-payment/rpc/runtime-api", default-features = false } -pallet-utility = { path = "../../../../../substrate/frame/utility", default-features = false } -sp-api = { path = "../../../../../substrate/primitives/api", default-features = false } -sp-block-builder = { path = "../../../../../substrate/primitives/block-builder", default-features = false } -sp-consensus-aura = { path = "../../../../../substrate/primitives/consensus/aura", default-features = false } -sp-core = { path = "../../../../../substrate/primitives/core", default-features = false } -sp-genesis-builder = { path = "../../../../../substrate/primitives/genesis-builder", default-features = false } -sp-inherents = { path = "../../../../../substrate/primitives/inherents", default-features = false } -sp-offchain = { path = "../../../../../substrate/primitives/offchain", default-features = false } -sp-runtime = { path = "../../../../../substrate/primitives/runtime", default-features = false } -sp-session = { path = "../../../../../substrate/primitives/session", default-features = false } -sp-std = { path = "../../../../../substrate/primitives/std", default-features = false } -sp-storage = { path = "../../../../../substrate/primitives/storage", default-features = false } -sp-transaction-pool = { path = "../../../../../substrate/primitives/transaction-pool", default-features = false } -sp-version = { path = "../../../../../substrate/primitives/version", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +frame-executive = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +frame-system-benchmarking = { optional = true, workspace = true } +frame-system-rpc-runtime-api = { workspace = true } +frame-try-runtime = { optional = true, workspace = true } +pallet-aura = { workspace = true } +pallet-authorship = { workspace = true } +pallet-balances = { workspace = true } +pallet-identity = { workspace = true } +pallet-message-queue = { workspace = true } +pallet-multisig = { workspace = true } +pallet-session = { workspace = true } +pallet-timestamp = { workspace = true } +pallet-transaction-payment = { workspace = true } +pallet-transaction-payment-rpc-runtime-api = { workspace = true } +pallet-utility = { workspace = true } +sp-api = { workspace = true } +sp-block-builder = { workspace = true } +sp-consensus-aura = { workspace = true } +sp-core = { workspace = true } +sp-genesis-builder = { workspace = true } +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 } # Polkadot -pallet-xcm = { path = "../../../../../polkadot/xcm/pallet-xcm", default-features = false } -pallet-xcm-benchmarks = { path = "../../../../../polkadot/xcm/pallet-xcm-benchmarks", default-features = false, optional = true } -polkadot-parachain-primitives = { path = "../../../../../polkadot/parachain", default-features = false } -polkadot-runtime-common = { path = "../../../../../polkadot/runtime/common", default-features = false } -westend-runtime-constants = { path = "../../../../../polkadot/runtime/westend/constants", default-features = false } -xcm = { package = "staging-xcm", path = "../../../../../polkadot/xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../../../polkadot/xcm/xcm-builder", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../../polkadot/xcm/xcm-executor", default-features = false } -xcm-fee-payment-runtime-api = { path = "../../../../../polkadot/xcm/xcm-fee-payment-runtime-api", default-features = false } +pallet-xcm = { workspace = true } +pallet-xcm-benchmarks = { optional = true, workspace = true } +polkadot-parachain-primitives = { workspace = true } +polkadot-runtime-common = { workspace = true } +westend-runtime-constants = { workspace = true } +xcm = { workspace = true } +xcm-builder = { workspace = true } +xcm-executor = { workspace = true } +xcm-runtime-apis = { workspace = true } # Cumulus -cumulus-pallet-aura-ext = { path = "../../../../pallets/aura-ext", default-features = false } -cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false } -cumulus-pallet-session-benchmarking = { path = "../../../../pallets/session-benchmarking", default-features = false } -cumulus-pallet-xcm = { path = "../../../../pallets/xcm", default-features = false } -cumulus-pallet-xcmp-queue = { path = "../../../../pallets/xcmp-queue", default-features = false } -cumulus-primitives-aura = { path = "../../../../primitives/aura", default-features = false } -cumulus-primitives-core = { path = "../../../../primitives/core", default-features = false } -cumulus-primitives-utility = { path = "../../../../primitives/utility", default-features = false } -cumulus-primitives-storage-weight-reclaim = { path = "../../../../primitives/storage-weight-reclaim", default-features = false } -pallet-collator-selection = { path = "../../../../pallets/collator-selection", default-features = false } -parachain-info = { package = "staging-parachain-info", path = "../../../pallets/parachain-info", default-features = false } -parachains-common = { path = "../../../common", default-features = false } -testnet-parachains-constants = { path = "../../constants", default-features = false, features = ["westend"] } +cumulus-pallet-aura-ext = { workspace = true } +cumulus-pallet-parachain-system = { workspace = true } +cumulus-pallet-session-benchmarking = { workspace = true } +cumulus-pallet-xcm = { workspace = true } +cumulus-pallet-xcmp-queue = { workspace = true } +cumulus-primitives-aura = { workspace = true } +cumulus-primitives-core = { workspace = true } +cumulus-primitives-utility = { workspace = true } +cumulus-primitives-storage-weight-reclaim = { workspace = true } +pallet-collator-selection = { workspace = true } +parachain-info = { workspace = true } +parachains-common = { workspace = true } +testnet-parachains-constants = { features = ["westend"], workspace = true } [features] default = ["std"] @@ -136,7 +136,7 @@ std = [ "westend-runtime-constants/std", "xcm-builder/std", "xcm-executor/std", - "xcm-fee-payment-runtime-api/std", + "xcm-runtime-apis/std", "xcm/std", ] @@ -165,7 +165,7 @@ runtime-benchmarks = [ "sp-runtime/runtime-benchmarks", "xcm-builder/runtime-benchmarks", "xcm-executor/runtime-benchmarks", - "xcm-fee-payment-runtime-api/runtime-benchmarks", + "xcm-runtime-apis/runtime-benchmarks", ] try-runtime = [ diff --git a/cumulus/parachains/runtimes/people/people-westend/src/lib.rs b/cumulus/parachains/runtimes/people/people-westend/src/lib.rs index 06c938b8a40c31ac31c2557f480017ba385e157b..84655972b0cd67e0e039880420832a366cdcb49c 100644 --- a/cumulus/parachains/runtimes/people/people-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/people/people-westend/src/lib.rs @@ -70,7 +70,7 @@ use xcm_config::{ FellowshipLocation, GovernanceLocation, PriceForSiblingParachainDelivery, XcmConfig, XcmOriginToTransactDispatchOrigin, }; -use xcm_fee_payment_runtime_api::{ +use xcm_runtime_apis::{ dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects}, fees::Error as XcmPaymentApiError, }; @@ -132,7 +132,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("people-westend"), impl_name: create_runtime_str!("people-westend"), authoring_version: 1, - spec_version: 1_012_000, + spec_version: 1_013_000, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 1, @@ -625,7 +625,7 @@ impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::fees::XcmPaymentApi for Runtime { + impl xcm_runtime_apis::fees::XcmPaymentApi for Runtime { fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result, XcmPaymentApiError> { let acceptable_assets = vec![AssetId(xcm_config::RelayLocation::get())]; PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets) @@ -638,11 +638,11 @@ impl_runtime_apis! { Ok(WeightToFee::weight_to_fee(&weight)) }, Ok(asset_id) => { - log::trace!(target: "xcm::xcm_fee_payment_runtime_api", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); + log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); Err(XcmPaymentApiError::AssetNotFound) }, Err(_) => { - log::trace!(target: "xcm::xcm_fee_payment_runtime_api", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!"); + log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!"); Err(XcmPaymentApiError::VersionedConversionFailed) } } @@ -657,7 +657,7 @@ impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::dry_run::DryRunApi for Runtime { + impl xcm_runtime_apis::dry_run::DryRunApi for Runtime { fn dry_run_call(origin: OriginCaller, call: RuntimeCall) -> Result, XcmDryRunApiError> { PolkadotXcm::dry_run_call::(origin, call) } @@ -667,6 +667,18 @@ impl_runtime_apis! { } } + impl xcm_runtime_apis::conversions::LocationToAccountApi for Runtime { + fn convert_location(location: VersionedLocation) -> Result< + AccountId, + xcm_runtime_apis::conversions::Error + > { + xcm_runtime_apis::conversions::LocationToAccountHelper::< + AccountId, + xcm_config::LocationToAccountId, + >::convert_location(location) + } + } + impl cumulus_primitives_core::CollectCollationInfo for Runtime { fn collect_collation_info(header: &::Header) -> cumulus_primitives_core::CollationInfo { ParachainSystem::collect_collation_info(header) diff --git a/cumulus/parachains/runtimes/starters/seedling/Cargo.toml b/cumulus/parachains/runtimes/starters/seedling/Cargo.toml index 910944f54a5ff3433f11fab1d33aa0e88abc35b2..8a7c5922362e888723826a04d31b941264a0e5b8 100644 --- a/cumulus/parachains/runtimes/starters/seedling/Cargo.toml +++ b/cumulus/parachains/runtimes/starters/seedling/Cargo.toml @@ -10,41 +10,41 @@ license = "Apache-2.0" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } # Substrate -frame-executive = { path = "../../../../../substrate/frame/executive", default-features = false } -frame-support = { path = "../../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../../substrate/frame/system", default-features = false } -pallet-aura = { path = "../../../../../substrate/frame/aura", default-features = false } -pallet-balances = { path = "../../../../../substrate/frame/balances", default-features = false } -pallet-sudo = { path = "../../../../../substrate/frame/sudo", default-features = false } -pallet-timestamp = { path = "../../../../../substrate/frame/timestamp", default-features = false } -sp-api = { path = "../../../../../substrate/primitives/api", default-features = false } -sp-block-builder = { path = "../../../../../substrate/primitives/block-builder", default-features = false } -sp-consensus-aura = { path = "../../../../../substrate/primitives/consensus/aura", default-features = false } -sp-core = { path = "../../../../../substrate/primitives/core", default-features = false } -sp-genesis-builder = { path = "../../../../../substrate/primitives/genesis-builder", default-features = false } -sp-inherents = { path = "../../../../../substrate/primitives/inherents", default-features = false } -sp-offchain = { path = "../../../../../substrate/primitives/offchain", default-features = false } -sp-runtime = { path = "../../../../../substrate/primitives/runtime", default-features = false } -sp-session = { path = "../../../../../substrate/primitives/session", default-features = false } -sp-std = { path = "../../../../../substrate/primitives/std", default-features = false } -sp-transaction-pool = { path = "../../../../../substrate/primitives/transaction-pool", default-features = false } -sp-version = { path = "../../../../../substrate/primitives/version", default-features = false } +frame-executive = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-aura = { workspace = true } +pallet-balances = { workspace = true } +pallet-sudo = { workspace = true } +pallet-timestamp = { workspace = true } +sp-api = { workspace = true } +sp-block-builder = { workspace = true } +sp-consensus-aura = { workspace = true } +sp-core = { workspace = true } +sp-genesis-builder = { workspace = true } +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 } # Cumulus -cumulus-pallet-aura-ext = { path = "../../../../pallets/aura-ext", default-features = false } -cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false } -cumulus-pallet-solo-to-para = { path = "../../../../pallets/solo-to-para", default-features = false } -cumulus-primitives-core = { path = "../../../../primitives/core", default-features = false } -cumulus-primitives-timestamp = { path = "../../../../primitives/timestamp", default-features = false } -parachain-info = { package = "staging-parachain-info", path = "../../../pallets/parachain-info", default-features = false } -parachains-common = { path = "../../../common", default-features = false } +cumulus-pallet-aura-ext = { workspace = true } +cumulus-pallet-parachain-system = { workspace = true } +cumulus-pallet-solo-to-para = { workspace = true } +cumulus-primitives-core = { workspace = true } +cumulus-primitives-timestamp = { workspace = true } +parachain-info = { workspace = true } +parachains-common = { workspace = true } [build-dependencies] -substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } +substrate-wasm-builder = { optional = true, workspace = true, default-features = true } [features] default = ["std"] diff --git a/cumulus/parachains/runtimes/starters/shell/Cargo.toml b/cumulus/parachains/runtimes/starters/shell/Cargo.toml index 7a7fad537ac302a9e71889c949a04aacc79df3f3..4a1271ca658406b2f4d6c100a70e1ca7b46ef8eb 100644 --- a/cumulus/parachains/runtimes/starters/shell/Cargo.toml +++ b/cumulus/parachains/runtimes/starters/shell/Cargo.toml @@ -10,45 +10,45 @@ license = "Apache-2.0" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } # Substrate -frame-executive = { path = "../../../../../substrate/frame/executive", default-features = false } -frame-support = { path = "../../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../../substrate/frame/system", default-features = false } -frame-try-runtime = { path = "../../../../../substrate/frame/try-runtime", default-features = false, optional = true } -pallet-aura = { path = "../../../../../substrate/frame/aura", default-features = false } -pallet-timestamp = { path = "../../../../../substrate/frame/timestamp", default-features = false } -sp-api = { path = "../../../../../substrate/primitives/api", default-features = false } -sp-block-builder = { path = "../../../../../substrate/primitives/block-builder", default-features = false } -sp-consensus-aura = { path = "../../../../../substrate/primitives/consensus/aura", default-features = false } -sp-core = { path = "../../../../../substrate/primitives/core", default-features = false } -sp-genesis-builder = { path = "../../../../../substrate/primitives/genesis-builder", default-features = false } -sp-inherents = { path = "../../../../../substrate/primitives/inherents", default-features = false } -sp-offchain = { path = "../../../../../substrate/primitives/offchain", default-features = false } -sp-runtime = { path = "../../../../../substrate/primitives/runtime", default-features = false } -sp-session = { path = "../../../../../substrate/primitives/session", default-features = false } -sp-std = { path = "../../../../../substrate/primitives/std", default-features = false } -sp-transaction-pool = { path = "../../../../../substrate/primitives/transaction-pool", default-features = false } -sp-version = { path = "../../../../../substrate/primitives/version", default-features = false } -pallet-message-queue = { path = "../../../../../substrate/frame/message-queue", default-features = false } +frame-executive = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +frame-try-runtime = { optional = true, workspace = true } +pallet-aura = { workspace = true } +pallet-timestamp = { workspace = true } +sp-api = { workspace = true } +sp-block-builder = { workspace = true } +sp-consensus-aura = { workspace = true } +sp-core = { workspace = true } +sp-genesis-builder = { workspace = true } +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 } # Polkadot -xcm = { package = "staging-xcm", path = "../../../../../polkadot/xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../../../polkadot/xcm/xcm-builder", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../../polkadot/xcm/xcm-executor", default-features = false } +xcm = { workspace = true } +xcm-builder = { workspace = true } +xcm-executor = { workspace = true } # Cumulus -cumulus-pallet-aura-ext = { path = "../../../../pallets/aura-ext", default-features = false } -cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false } -cumulus-pallet-xcm = { path = "../../../../pallets/xcm", default-features = false } -cumulus-primitives-core = { path = "../../../../primitives/core", default-features = false } -parachain-info = { package = "staging-parachain-info", path = "../../../pallets/parachain-info", default-features = false } -parachains-common = { path = "../../../common", default-features = false } +cumulus-pallet-aura-ext = { workspace = true } +cumulus-pallet-parachain-system = { workspace = true } +cumulus-pallet-xcm = { workspace = true } +cumulus-primitives-core = { workspace = true } +parachain-info = { workspace = true } +parachains-common = { workspace = true } [build-dependencies] -substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } +substrate-wasm-builder = { optional = true, workspace = true, default-features = true } [features] default = ["std"] diff --git a/cumulus/parachains/runtimes/test-utils/Cargo.toml b/cumulus/parachains/runtimes/test-utils/Cargo.toml index c081bac4babe87413c40869917715d03c0c71a86..5e895271ab17f8d9d4cf13cded7f1ebc9716000e 100644 --- a/cumulus/parachains/runtimes/test-utils/Cargo.toml +++ b/cumulus/parachains/runtimes/test-utils/Cargo.toml @@ -10,41 +10,41 @@ license = "Apache-2.0" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive", "max-encoded-len"] } +codec = { features = ["derive", "max-encoded-len"], workspace = true } # Substrate -frame-support = { path = "../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../substrate/frame/system", default-features = false } -pallet-balances = { path = "../../../../substrate/frame/balances", default-features = false } -pallet-session = { path = "../../../../substrate/frame/session", default-features = false } -pallet-timestamp = { path = "../../../../substrate/frame/timestamp", default-features = false } -sp-consensus-aura = { path = "../../../../substrate/primitives/consensus/aura", default-features = false } -sp-io = { path = "../../../../substrate/primitives/io", default-features = false } -sp-runtime = { path = "../../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../../substrate/primitives/std", default-features = false } -sp-tracing = { path = "../../../../substrate/primitives/tracing" } -sp-core = { path = "../../../../substrate/primitives/core", default-features = false } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-balances = { workspace = true } +pallet-session = { workspace = true } +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 } # Cumulus -cumulus-pallet-parachain-system = { path = "../../../pallets/parachain-system", default-features = false } -cumulus-pallet-xcmp-queue = { path = "../../../pallets/xcmp-queue", default-features = false } -pallet-collator-selection = { path = "../../../pallets/collator-selection", default-features = false } -parachain-info = { package = "staging-parachain-info", path = "../../pallets/parachain-info", default-features = false } -cumulus-primitives-core = { path = "../../../primitives/core", default-features = false } -cumulus-primitives-parachain-inherent = { path = "../../../primitives/parachain-inherent", default-features = false } -cumulus-test-relay-sproof-builder = { path = "../../../test/relay-sproof-builder", default-features = false } +cumulus-pallet-parachain-system = { workspace = true } +cumulus-pallet-xcmp-queue = { workspace = true } +pallet-collator-selection = { workspace = true } +parachain-info = { workspace = true } +cumulus-primitives-core = { workspace = true } +cumulus-primitives-parachain-inherent = { workspace = true } +cumulus-test-relay-sproof-builder = { workspace = true } # Polkadot -xcm = { package = "staging-xcm", path = "../../../../polkadot/xcm", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../polkadot/xcm/xcm-executor", default-features = false } -pallet-xcm = { path = "../../../../polkadot/xcm/pallet-xcm", default-features = false } -polkadot-parachain-primitives = { path = "../../../../polkadot/parachain", default-features = false } +xcm = { workspace = true } +xcm-executor = { workspace = true } +pallet-xcm = { workspace = true } +polkadot-parachain-primitives = { workspace = true } [dev-dependencies] -hex-literal = "0.4.1" +hex-literal = { workspace = true, default-features = true } [build-dependencies] -substrate-wasm-builder = { path = "../../../../substrate/utils/wasm-builder" } +substrate-wasm-builder = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/cumulus/parachains/runtimes/testing/penpal/Cargo.toml b/cumulus/parachains/runtimes/testing/penpal/Cargo.toml index 3262233053e7e130c230adbc0aef857572756b1d..bdd0dfac6065759d10108a7961dbaf987e0ebb16 100644 --- a/cumulus/parachains/runtimes/testing/penpal/Cargo.toml +++ b/cumulus/parachains/runtimes/testing/penpal/Cargo.toml @@ -15,70 +15,70 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [build-dependencies] -substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } +substrate-wasm-builder = { optional = true, workspace = true, default-features = true } [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -hex-literal = { version = "0.4.1", optional = true } +codec = { features = ["derive"], workspace = true } +hex-literal = { optional = true, workspace = true, default-features = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -smallvec = "1.11.0" +scale-info = { features = ["derive"], workspace = true } +smallvec = { workspace = true, default-features = true } # Substrate -frame-benchmarking = { path = "../../../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-executive = { path = "../../../../../substrate/frame/executive", default-features = false } -frame-support = { path = "../../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../../substrate/frame/system", default-features = false } -frame-system-benchmarking = { path = "../../../../../substrate/frame/system/benchmarking", default-features = false, optional = true } -frame-system-rpc-runtime-api = { path = "../../../../../substrate/frame/system/rpc/runtime-api", default-features = false } -frame-try-runtime = { path = "../../../../../substrate/frame/try-runtime", default-features = false, optional = true } -pallet-aura = { path = "../../../../../substrate/frame/aura", default-features = false } -pallet-authorship = { path = "../../../../../substrate/frame/authorship", default-features = false } -pallet-balances = { path = "../../../../../substrate/frame/balances", default-features = false } -pallet-session = { path = "../../../../../substrate/frame/session", default-features = false } -pallet-sudo = { path = "../../../../../substrate/frame/sudo", default-features = false } -pallet-timestamp = { path = "../../../../../substrate/frame/timestamp", default-features = false } -pallet-transaction-payment = { path = "../../../../../substrate/frame/transaction-payment", default-features = false } -pallet-transaction-payment-rpc-runtime-api = { path = "../../../../../substrate/frame/transaction-payment/rpc/runtime-api", default-features = false } -pallet-asset-tx-payment = { path = "../../../../../substrate/frame/transaction-payment/asset-tx-payment", default-features = false } -pallet-assets = { path = "../../../../../substrate/frame/assets", default-features = false } -sp-api = { path = "../../../../../substrate/primitives/api", default-features = false } -sp-block-builder = { path = "../../../../../substrate/primitives/block-builder", default-features = false } -sp-consensus-aura = { path = "../../../../../substrate/primitives/consensus/aura", default-features = false } -sp-core = { path = "../../../../../substrate/primitives/core", default-features = false } -sp-genesis-builder = { path = "../../../../../substrate/primitives/genesis-builder", default-features = false } -sp-inherents = { path = "../../../../../substrate/primitives/inherents", default-features = false } -sp-offchain = { path = "../../../../../substrate/primitives/offchain", default-features = false } -sp-runtime = { path = "../../../../../substrate/primitives/runtime", default-features = false } -sp-session = { path = "../../../../../substrate/primitives/session", default-features = false } -sp-std = { path = "../../../../../substrate/primitives/std", default-features = false } -sp-storage = { path = "../../../../../substrate/primitives/storage", default-features = false } -sp-transaction-pool = { path = "../../../../../substrate/primitives/transaction-pool", default-features = false } -sp-version = { path = "../../../../../substrate/primitives/version", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +frame-executive = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +frame-system-benchmarking = { optional = true, workspace = true } +frame-system-rpc-runtime-api = { workspace = true } +frame-try-runtime = { optional = true, workspace = true } +pallet-aura = { workspace = true } +pallet-authorship = { workspace = true } +pallet-balances = { workspace = true } +pallet-session = { workspace = true } +pallet-sudo = { workspace = true } +pallet-timestamp = { workspace = true } +pallet-transaction-payment = { workspace = true } +pallet-transaction-payment-rpc-runtime-api = { workspace = true } +pallet-asset-tx-payment = { workspace = true } +pallet-assets = { workspace = true } +sp-api = { workspace = true } +sp-block-builder = { workspace = true } +sp-consensus-aura = { workspace = true } +sp-core = { workspace = true } +sp-genesis-builder = { workspace = true } +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 } # Polkadot -polkadot-primitives = { path = "../../../../../polkadot/primitives", default-features = false } -pallet-xcm = { path = "../../../../../polkadot/xcm/pallet-xcm", default-features = false } -polkadot-parachain-primitives = { path = "../../../../../polkadot/parachain", default-features = false } -polkadot-runtime-common = { path = "../../../../../polkadot/runtime/common", default-features = false } -xcm = { package = "staging-xcm", path = "../../../../../polkadot/xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../../../polkadot/xcm/xcm-builder", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../../polkadot/xcm/xcm-executor", default-features = false } -xcm-fee-payment-runtime-api = { path = "../../../../../polkadot/xcm/xcm-fee-payment-runtime-api", default-features = false } +polkadot-primitives = { workspace = true } +pallet-xcm = { workspace = true } +polkadot-parachain-primitives = { workspace = true } +polkadot-runtime-common = { workspace = true } +xcm = { workspace = true } +xcm-builder = { workspace = true } +xcm-executor = { workspace = true } +xcm-runtime-apis = { workspace = true } # Cumulus -cumulus-pallet-aura-ext = { path = "../../../../pallets/aura-ext", default-features = false } -pallet-message-queue = { path = "../../../../../substrate/frame/message-queue", default-features = false } -cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false } -cumulus-pallet-session-benchmarking = { path = "../../../../pallets/session-benchmarking", default-features = false } -cumulus-pallet-xcm = { path = "../../../../pallets/xcm", default-features = false } -cumulus-pallet-xcmp-queue = { path = "../../../../pallets/xcmp-queue", default-features = false } -cumulus-primitives-core = { path = "../../../../primitives/core", default-features = false } -cumulus-primitives-utility = { path = "../../../../primitives/utility", default-features = false } -pallet-collator-selection = { path = "../../../../pallets/collator-selection", default-features = false } -parachain-info = { package = "staging-parachain-info", path = "../../../pallets/parachain-info", default-features = false } -parachains-common = { path = "../../../common", default-features = false } -assets-common = { path = "../../assets/common", default-features = false } +cumulus-pallet-aura-ext = { workspace = true } +pallet-message-queue = { workspace = true } +cumulus-pallet-parachain-system = { workspace = true } +cumulus-pallet-session-benchmarking = { workspace = true } +cumulus-pallet-xcm = { workspace = true } +cumulus-pallet-xcmp-queue = { workspace = true } +cumulus-primitives-core = { workspace = true } +cumulus-primitives-utility = { workspace = true } +pallet-collator-selection = { workspace = true } +parachain-info = { workspace = true } +parachains-common = { workspace = true } +assets-common = { workspace = true } [features] default = ["std"] @@ -135,7 +135,7 @@ std = [ "substrate-wasm-builder", "xcm-builder/std", "xcm-executor/std", - "xcm-fee-payment-runtime-api/std", + "xcm-runtime-apis/std", "xcm/std", ] @@ -166,7 +166,7 @@ runtime-benchmarks = [ "sp-runtime/runtime-benchmarks", "xcm-builder/runtime-benchmarks", "xcm-executor/runtime-benchmarks", - "xcm-fee-payment-runtime-api/runtime-benchmarks", + "xcm-runtime-apis/runtime-benchmarks", ] try-runtime = [ diff --git a/cumulus/parachains/runtimes/testing/penpal/src/lib.rs b/cumulus/parachains/runtimes/testing/penpal/src/lib.rs index e77416e6cd5b681a83b3d8b0571401ef1543004b..8d03f8332764f4a1a478ab4bef9c3dfd663e7169 100644 --- a/cumulus/parachains/runtimes/testing/penpal/src/lib.rs +++ b/cumulus/parachains/runtimes/testing/penpal/src/lib.rs @@ -85,7 +85,7 @@ use xcm::{ latest::prelude::{AssetId as AssetLocationId, BodyId}, VersionedAssetId, VersionedAssets, VersionedLocation, VersionedXcm, }; -use xcm_fee_payment_runtime_api::{ +use xcm_runtime_apis::{ dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects}, fees::Error as XcmPaymentApiError, }; @@ -847,7 +847,7 @@ impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::fees::XcmPaymentApi for Runtime { + impl xcm_runtime_apis::fees::XcmPaymentApi for Runtime { fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result, XcmPaymentApiError> { let acceptable_assets = vec![AssetLocationId(xcm_config::RelayLocation::get())]; PolkadotXcm::query_acceptable_payment_assets(xcm_version, acceptable_assets) @@ -860,11 +860,11 @@ impl_runtime_apis! { Ok(WeightToFee::weight_to_fee(&weight)) }, Ok(asset_id) => { - log::trace!(target: "xcm::xcm_fee_payment_runtime_api", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); + log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); Err(XcmPaymentApiError::AssetNotFound) }, Err(_) => { - log::trace!(target: "xcm::xcm_fee_payment_runtime_api", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!"); + log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!"); Err(XcmPaymentApiError::VersionedConversionFailed) } } @@ -879,7 +879,7 @@ impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::dry_run::DryRunApi for Runtime { + impl xcm_runtime_apis::dry_run::DryRunApi for Runtime { fn dry_run_call(origin: OriginCaller, call: RuntimeCall) -> Result, XcmDryRunApiError> { use xcm_builder::InspectMessageQueues; use xcm_executor::RecordXcm; diff --git a/cumulus/parachains/runtimes/testing/rococo-parachain/Cargo.toml b/cumulus/parachains/runtimes/testing/rococo-parachain/Cargo.toml index cf734345a976f027ae31f2f38735b9b7aac59f7d..7cbb614babe7988831db0898e6b08242cc66efe0 100644 --- a/cumulus/parachains/runtimes/testing/rococo-parachain/Cargo.toml +++ b/cumulus/parachains/runtimes/testing/rococo-parachain/Cargo.toml @@ -10,60 +10,60 @@ license = "Apache-2.0" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } # Substrate -frame-benchmarking = { path = "../../../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-executive = { path = "../../../../../substrate/frame/executive", default-features = false } -frame-support = { path = "../../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../../substrate/frame/system", default-features = false } -frame-system-rpc-runtime-api = { path = "../../../../../substrate/frame/system/rpc/runtime-api", default-features = false } -pallet-assets = { path = "../../../../../substrate/frame/assets", default-features = false } -pallet-aura = { path = "../../../../../substrate/frame/aura", default-features = false } -pallet-balances = { path = "../../../../../substrate/frame/balances", default-features = false } -pallet-sudo = { path = "../../../../../substrate/frame/sudo", default-features = false } -pallet-timestamp = { path = "../../../../../substrate/frame/timestamp", default-features = false } -pallet-transaction-payment = { path = "../../../../../substrate/frame/transaction-payment", default-features = false } -pallet-transaction-payment-rpc-runtime-api = { path = "../../../../../substrate/frame/transaction-payment/rpc/runtime-api", default-features = false } -sp-api = { path = "../../../../../substrate/primitives/api", default-features = false } -sp-block-builder = { path = "../../../../../substrate/primitives/block-builder", default-features = false } -sp-consensus-aura = { path = "../../../../../substrate/primitives/consensus/aura", default-features = false } -sp-core = { path = "../../../../../substrate/primitives/core", default-features = false } -sp-genesis-builder = { path = "../../../../../substrate/primitives/genesis-builder", default-features = false } -sp-inherents = { path = "../../../../../substrate/primitives/inherents", default-features = false } -sp-offchain = { path = "../../../../../substrate/primitives/offchain", default-features = false } -sp-runtime = { path = "../../../../../substrate/primitives/runtime", default-features = false } -sp-session = { path = "../../../../../substrate/primitives/session", default-features = false } -sp-std = { path = "../../../../../substrate/primitives/std", default-features = false } -sp-transaction-pool = { path = "../../../../../substrate/primitives/transaction-pool", default-features = false } -sp-version = { path = "../../../../../substrate/primitives/version", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +frame-executive = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +frame-system-rpc-runtime-api = { workspace = true } +pallet-assets = { workspace = true } +pallet-aura = { workspace = true } +pallet-balances = { workspace = true } +pallet-sudo = { workspace = true } +pallet-timestamp = { workspace = true } +pallet-transaction-payment = { workspace = true } +pallet-transaction-payment-rpc-runtime-api = { workspace = true } +sp-api = { workspace = true } +sp-block-builder = { workspace = true } +sp-consensus-aura = { workspace = true } +sp-core = { workspace = true } +sp-genesis-builder = { workspace = true } +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 } # Polkadot -pallet-xcm = { path = "../../../../../polkadot/xcm/pallet-xcm", default-features = false } -polkadot-parachain-primitives = { path = "../../../../../polkadot/parachain", default-features = false } -xcm = { package = "staging-xcm", path = "../../../../../polkadot/xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../../../polkadot/xcm/xcm-builder", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../../polkadot/xcm/xcm-executor", default-features = false } -polkadot-runtime-common = { path = "../../../../../polkadot/runtime/common", default-features = false } +pallet-xcm = { workspace = true } +polkadot-parachain-primitives = { workspace = true } +xcm = { workspace = true } +xcm-builder = { workspace = true } +xcm-executor = { workspace = true } +polkadot-runtime-common = { workspace = true } # Cumulus -cumulus-pallet-aura-ext = { path = "../../../../pallets/aura-ext", default-features = false } -pallet-message-queue = { path = "../../../../../substrate/frame/message-queue", default-features = false } -cumulus-pallet-parachain-system = { path = "../../../../pallets/parachain-system", default-features = false } -cumulus-pallet-xcm = { path = "../../../../pallets/xcm", default-features = false } -cumulus-pallet-xcmp-queue = { path = "../../../../pallets/xcmp-queue", default-features = false } -cumulus-ping = { path = "../../../pallets/ping", default-features = false } -cumulus-primitives-aura = { path = "../../../../primitives/aura", default-features = false } -cumulus-primitives-core = { path = "../../../../primitives/core", default-features = false } -cumulus-primitives-storage-weight-reclaim = { path = "../../../../primitives/storage-weight-reclaim", default-features = false } -cumulus-primitives-utility = { path = "../../../../primitives/utility", default-features = false } -parachains-common = { path = "../../../common", default-features = false } -testnet-parachains-constants = { path = "../../constants", default-features = false, features = ["rococo"] } -parachain-info = { package = "staging-parachain-info", path = "../../../pallets/parachain-info", default-features = false } +cumulus-pallet-aura-ext = { workspace = true } +pallet-message-queue = { workspace = true } +cumulus-pallet-parachain-system = { workspace = true } +cumulus-pallet-xcm = { workspace = true } +cumulus-pallet-xcmp-queue = { workspace = true } +cumulus-ping = { workspace = true } +cumulus-primitives-aura = { workspace = true } +cumulus-primitives-core = { workspace = true } +cumulus-primitives-storage-weight-reclaim = { workspace = true } +cumulus-primitives-utility = { workspace = true } +parachains-common = { workspace = true } +testnet-parachains-constants = { features = ["rococo"], workspace = true } +parachain-info = { workspace = true } [build-dependencies] -substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } +substrate-wasm-builder = { optional = true, workspace = true, default-features = true } [features] default = ["std"] diff --git a/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs b/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs index fd4716ab972e8e8f6d3d1a3ca6aca74df7263fa7..bf45b437f8bb0bba641ee1d622709ee4ed65732d 100644 --- a/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs +++ b/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs @@ -107,7 +107,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("test-parachain"), impl_name: create_runtime_str!("test-parachain"), authoring_version: 1, - spec_version: 1_012_000, + spec_version: 1_013_000, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 6, diff --git a/cumulus/polkadot-parachain/Cargo.toml b/cumulus/polkadot-parachain/Cargo.toml index 639b8b3d4dcf18f8d9601d0873f99b0278939f2d..89364ff7fab6423cf09d9b26dd6135afc6988c0b 100644 --- a/cumulus/polkadot-parachain/Cargo.toml +++ b/cumulus/polkadot-parachain/Cargo.toml @@ -15,113 +15,113 @@ name = "polkadot-parachain" path = "src/main.rs" [dependencies] -async-trait = "0.1.79" -clap = { version = "4.5.3", features = ["derive"] } -codec = { package = "parity-scale-codec", version = "3.6.12" } -futures = "0.3.28" -hex-literal = "0.4.1" +async-trait = { workspace = true } +clap = { features = ["derive"], workspace = true } +codec = { workspace = true, default-features = true } +color-print = { workspace = true } +futures = { workspace = true } +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 } # Local -rococo-parachain-runtime = { path = "../parachains/runtimes/testing/rococo-parachain" } -shell-runtime = { path = "../parachains/runtimes/starters/shell" } -glutton-westend-runtime = { path = "../parachains/runtimes/glutton/glutton-westend" } -seedling-runtime = { path = "../parachains/runtimes/starters/seedling" } -asset-hub-rococo-runtime = { path = "../parachains/runtimes/assets/asset-hub-rococo" } -asset-hub-westend-runtime = { path = "../parachains/runtimes/assets/asset-hub-westend" } -collectives-westend-runtime = { path = "../parachains/runtimes/collectives/collectives-westend" } -contracts-rococo-runtime = { path = "../parachains/runtimes/contracts/contracts-rococo" } -bridge-hub-rococo-runtime = { path = "../parachains/runtimes/bridge-hubs/bridge-hub-rococo" } -coretime-rococo-runtime = { path = "../parachains/runtimes/coretime/coretime-rococo" } -coretime-westend-runtime = { path = "../parachains/runtimes/coretime/coretime-westend" } -bridge-hub-westend-runtime = { path = "../parachains/runtimes/bridge-hubs/bridge-hub-westend" } -penpal-runtime = { path = "../parachains/runtimes/testing/penpal" } -jsonrpsee = { version = "0.22", features = ["server"] } -people-rococo-runtime = { path = "../parachains/runtimes/people/people-rococo" } -people-westend-runtime = { path = "../parachains/runtimes/people/people-westend" } -parachains-common = { path = "../parachains/common" } -testnet-parachains-constants = { path = "../parachains/runtimes/constants", default-features = false, features = [ +rococo-parachain-runtime = { workspace = true } +shell-runtime = { workspace = true } +glutton-westend-runtime = { workspace = true } +seedling-runtime = { workspace = true } +asset-hub-rococo-runtime = { workspace = true, default-features = true } +asset-hub-westend-runtime = { workspace = true } +collectives-westend-runtime = { workspace = true } +contracts-rococo-runtime = { workspace = true } +bridge-hub-rococo-runtime = { workspace = true, default-features = true } +coretime-rococo-runtime = { workspace = true } +coretime-westend-runtime = { workspace = true } +bridge-hub-westend-runtime = { workspace = true, default-features = true } +penpal-runtime = { workspace = true } +jsonrpsee = { features = ["server"], workspace = true } +people-rococo-runtime = { workspace = true } +people-westend-runtime = { workspace = true } +parachains-common = { workspace = true, default-features = true } +testnet-parachains-constants = { features = [ "rococo", "westend", -] } +], workspace = true } # Substrate -frame-benchmarking = { path = "../../substrate/frame/benchmarking" } -frame-benchmarking-cli = { path = "../../substrate/utils/frame/benchmarking-cli" } -sp-runtime = { path = "../../substrate/primitives/runtime", default-features = false } -sp-io = { path = "../../substrate/primitives/io" } -sp-core = { path = "../../substrate/primitives/core" } -sp-session = { path = "../../substrate/primitives/session" } -frame-try-runtime = { path = "../../substrate/frame/try-runtime", optional = true } -sc-consensus = { path = "../../substrate/client/consensus/common" } -sp-tracing = { path = "../../substrate/primitives/tracing" } -frame-support = { path = "../../substrate/frame/support" } -sc-cli = { path = "../../substrate/client/cli" } -sc-client-api = { path = "../../substrate/client/api" } -sc-executor = { path = "../../substrate/client/executor" } -sc-service = { path = "../../substrate/client/service" } -sc-telemetry = { path = "../../substrate/client/telemetry" } -sc-transaction-pool = { path = "../../substrate/client/transaction-pool" } -sp-transaction-pool = { path = "../../substrate/primitives/transaction-pool" } -sc-network = { path = "../../substrate/client/network" } -sc-network-sync = { path = "../../substrate/client/network/sync" } -sc-basic-authorship = { path = "../../substrate/client/basic-authorship" } -sp-timestamp = { path = "../../substrate/primitives/timestamp" } -sp-blockchain = { path = "../../substrate/primitives/blockchain" } -sp-genesis-builder = { path = "../../substrate/primitives/genesis-builder", default-features = false } -sp-block-builder = { path = "../../substrate/primitives/block-builder" } -sp-keystore = { path = "../../substrate/primitives/keystore" } -sc-chain-spec = { path = "../../substrate/client/chain-spec" } -sc-rpc = { path = "../../substrate/client/rpc" } -sp-version = { path = "../../substrate/primitives/version" } -sc-tracing = { path = "../../substrate/client/tracing" } -sp-offchain = { path = "../../substrate/primitives/offchain" } -frame-system-rpc-runtime-api = { path = "../../substrate/frame/system/rpc/runtime-api" } -pallet-transaction-payment = { path = "../../substrate/frame/transaction-payment" } -pallet-transaction-payment-rpc-runtime-api = { path = "../../substrate/frame/transaction-payment/rpc/runtime-api" } -sp-std = { path = "../../substrate/primitives/std" } -sp-inherents = { path = "../../substrate/primitives/inherents" } -sp-api = { path = "../../substrate/primitives/api" } -sp-consensus-aura = { path = "../../substrate/primitives/consensus/aura" } -sc-sysinfo = { path = "../../substrate/client/sysinfo" } -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../substrate/utils/prometheus" } -sc-transaction-pool-api = { path = "../../substrate/client/transaction-pool/api" } -substrate-frame-rpc-system = { path = "../../substrate/utils/frame/rpc/system" } -pallet-transaction-payment-rpc = { path = "../../substrate/frame/transaction-payment/rpc" } -substrate-state-trie-migration-rpc = { path = "../../substrate/utils/frame/rpc/state-trie-migration-rpc" } +frame-benchmarking = { workspace = true, default-features = true } +frame-benchmarking-cli = { workspace = true, default-features = true } +sp-runtime = { workspace = true } +sp-io = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-session = { workspace = true, default-features = true } +frame-try-runtime = { optional = true, workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +frame-support = { workspace = true, default-features = true } +sc-cli = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-executor = { workspace = true, default-features = true } +sc-service = { workspace = true, default-features = true } +sc-telemetry = { workspace = true, default-features = true } +sc-transaction-pool = { workspace = true, default-features = true } +sp-transaction-pool = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sc-network-sync = { workspace = true, default-features = true } +sc-basic-authorship = { workspace = true, default-features = true } +sp-timestamp = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-genesis-builder = { workspace = true } +sp-block-builder = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sc-chain-spec = { workspace = true, default-features = true } +sc-rpc = { workspace = true, default-features = true } +sp-version = { workspace = true, default-features = true } +sc-tracing = { workspace = true, default-features = true } +sp-offchain = { workspace = true, default-features = true } +frame-system-rpc-runtime-api = { workspace = true, default-features = true } +pallet-transaction-payment = { workspace = true, default-features = true } +pallet-transaction-payment-rpc-runtime-api = { workspace = true, default-features = true } +sp-std = { workspace = true, default-features = true } +sp-inherents = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-consensus-aura = { workspace = true, default-features = true } +sc-sysinfo = { workspace = true, default-features = true } +prometheus-endpoint = { workspace = true, default-features = true } +sc-transaction-pool-api = { workspace = true, default-features = true } +substrate-frame-rpc-system = { workspace = true, default-features = true } +pallet-transaction-payment-rpc = { workspace = true, default-features = true } +substrate-state-trie-migration-rpc = { workspace = true, default-features = true } # Polkadot # Use rococo-native as this is currently the default "local" relay chain -polkadot-cli = { path = "../../polkadot/cli", features = ["rococo-native"] } -polkadot-primitives = { path = "../../polkadot/primitives" } -polkadot-service = { path = "../../polkadot/node/service" } -xcm = { package = "staging-xcm", path = "../../polkadot/xcm" } +polkadot-cli = { features = ["rococo-native", "westend-native"], workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-service = { workspace = true, default-features = true } +xcm = { workspace = true, default-features = true } # Cumulus -cumulus-client-cli = { path = "../client/cli" } -cumulus-client-collator = { path = "../client/collator" } -cumulus-client-consensus-aura = { path = "../client/consensus/aura" } -cumulus-client-consensus-relay-chain = { path = "../client/consensus/relay-chain" } -cumulus-client-consensus-common = { path = "../client/consensus/common" } -cumulus-client-consensus-proposer = { path = "../client/consensus/proposer" } -cumulus-client-parachain-inherent = { path = "../client/parachain-inherent" } -cumulus-client-service = { path = "../client/service" } -cumulus-primitives-aura = { path = "../primitives/aura" } -cumulus-primitives-core = { path = "../primitives/core" } -cumulus-relay-chain-interface = { path = "../client/relay-chain-interface" } -color-print = "0.3.4" +cumulus-client-cli = { workspace = true, default-features = true } +cumulus-client-collator = { workspace = true, default-features = true } +cumulus-client-consensus-aura = { workspace = true, default-features = true } +cumulus-client-consensus-relay-chain = { workspace = true, default-features = true } +cumulus-client-consensus-common = { workspace = true, default-features = true } +cumulus-client-consensus-proposer = { workspace = true, default-features = true } +cumulus-client-parachain-inherent = { workspace = true, default-features = true } +cumulus-client-service = { workspace = true, default-features = true } +cumulus-primitives-aura = { workspace = true, default-features = true } +cumulus-primitives-core = { workspace = true, default-features = true } +cumulus-relay-chain-interface = { workspace = true, default-features = true } [build-dependencies] -substrate-build-script-utils = { path = "../../substrate/utils/build-script-utils" } +substrate-build-script-utils = { workspace = true, default-features = true } [dev-dependencies] -assert_cmd = "2.0" -nix = { version = "0.28.0", features = ["signal"] } -tempfile = "3.8.0" -tokio = { version = "1.32.0", features = ["macros", "parking_lot", "time"] } -wait-timeout = "0.2" +assert_cmd = { workspace = true } +nix = { features = ["signal"], workspace = true } +tempfile = { workspace = true } +tokio = { features = ["macros", "parking_lot", "time"], workspace = true, default-features = true } +wait-timeout = { workspace = true } [features] default = [] diff --git a/cumulus/polkadot-parachain/src/cli.rs b/cumulus/polkadot-parachain/src/cli.rs index f7d2fd0f0be3c938ac5a9376d6896a0b073fa364..fa4b4da1ba9cadcd2d2d16c772e9d1ceed26f486 100644 --- a/cumulus/polkadot-parachain/src/cli.rs +++ b/cumulus/polkadot-parachain/src/cli.rs @@ -14,6 +14,7 @@ // You should have received a copy of the GNU General Public License // along with Cumulus. If not, see . +use clap::{CommandFactory, FromArgMatches}; use std::path::PathBuf; /// Sub-commands supported by the collator. @@ -108,18 +109,19 @@ pub struct RelayChainCli { } impl RelayChainCli { - /// Parse the relay chain CLI parameters using the para chain `Configuration`. + /// Parse the relay chain CLI parameters using the parachain `Configuration`. pub fn new<'a>( para_config: &sc_service::Configuration, relay_chain_args: impl Iterator, ) -> Self { + let polkadot_cmd = polkadot_cli::RunCmd::command().no_binary_name(true); + let matches = polkadot_cmd.get_matches_from(relay_chain_args); + let base = FromArgMatches::from_arg_matches(&matches).unwrap_or_else(|e| e.exit()); + let extension = crate::chain_spec::Extensions::try_get(&*para_config.chain_spec); let chain_id = extension.map(|e| e.relay_chain.clone()); + let base_path = para_config.base_path.path().join("polkadot"); - Self { - base_path: Some(base_path), - chain_id, - base: clap::Parser::parse_from(relay_chain_args), - } + Self { base, chain_id, base_path: Some(base_path) } } } diff --git a/cumulus/polkadot-parachain/src/command.rs b/cumulus/polkadot-parachain/src/command.rs index 653ea3281f0f769df9a3c88629e139244b187863..6b3f4b4cd0a7f462da66a219e4180c4132464bd2 100644 --- a/cumulus/polkadot-parachain/src/command.rs +++ b/cumulus/polkadot-parachain/src/command.rs @@ -530,13 +530,9 @@ pub fn run() -> Result<()> { }), Some(Subcommand::PurgeChain(cmd)) => { let runner = cli.create_runner(cmd)?; + let polkadot_cli = RelayChainCli::new(runner.config(), cli.relaychain_args.iter()); runner.sync_run(|config| { - let polkadot_cli = RelayChainCli::new( - &config, - [RelayChainCli::executable_name()].iter().chain(cli.relaychain_args.iter()), - ); - let polkadot_config = SubstrateCli::create_configuration( &polkadot_cli, &polkadot_cli, @@ -603,6 +599,7 @@ pub fn run() -> Result<()> { Some(Subcommand::Key(cmd)) => Ok(cmd.run(&cli)?), None => { let runner = cli.create_runner(&cli.run.normalize())?; + let polkadot_cli = RelayChainCli::new(runner.config(), cli.relaychain_args.iter()); let collator_options = cli.run.collator_options(); runner.run_node_until_exit(|config| async move { @@ -648,11 +645,6 @@ pub fn run() -> Result<()> { .map(|e| e.para_id) .ok_or("Could not find parachain extension in chain-spec.")?; - let polkadot_cli = RelayChainCli::new( - &config, - [RelayChainCli::executable_name()].iter().chain(cli.relaychain_args.iter()), - ); - let id = ParaId::from(para_id); let parachain_account = @@ -667,7 +659,7 @@ pub fn run() -> Result<()> { info!("Parachain Account: {}", parachain_account); info!("Is collating: {}", if config.role.is_authority() { "yes" } else { "no" }); - match polkadot_config.network.network_backend { + match config.network.network_backend { sc_network::config::NetworkBackendType::Libp2p => start_node::>( config, diff --git a/cumulus/polkadot-parachain/src/common/aura.rs b/cumulus/polkadot-parachain/src/common/aura.rs new file mode 100644 index 0000000000000000000000000000000000000000..9f72d847926f3a7be480911bdb273e33bf6c0afb --- /dev/null +++ b/cumulus/polkadot-parachain/src/common/aura.rs @@ -0,0 +1,68 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Cumulus. + +// Cumulus 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. + +// Cumulus 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 Cumulus. If not, see . + +//! Aura-related primitives for cumulus parachain collators. + +use codec::Codec; +use cumulus_primitives_aura::AuraUnincludedSegmentApi; +use cumulus_primitives_core::BlockT; +use sp_consensus_aura::AuraApi; +use sp_runtime::app_crypto::{AppCrypto, AppPair, AppSignature, Pair}; + +/// Convenience trait for defining the basic bounds of an `AuraId`. +pub trait AuraIdT: AppCrypto + Codec + Send { + /// Extra bounds for the `Pair`. + type BoundedPair: AppPair + AppCrypto; + + /// Extra bounds for the `Signature`. + type BoundedSignature: AppSignature + + TryFrom> + + std::hash::Hash + + sp_runtime::traits::Member + + Codec; +} + +impl AuraIdT for T +where + T: AppCrypto + Codec + Send + Sync, + <::Pair as AppCrypto>::Signature: + TryFrom> + std::hash::Hash + sp_runtime::traits::Member + Codec, +{ + type BoundedPair = ::Pair; + type BoundedSignature = <::Pair as AppCrypto>::Signature; +} + +/// Convenience trait for defining the basic bounds of a parachain runtime that supports +/// the Aura consensus. +pub trait AuraRuntimeApi: + sp_api::ApiExt + + AuraApi::Public> + + AuraUnincludedSegmentApi + + Sized +{ + /// Check if the runtime has the Aura API. + fn has_aura_api(&self, at: Block::Hash) -> bool { + self.has_api::::Public>>(at) + .unwrap_or(false) + } +} + +impl AuraRuntimeApi for T where + T: sp_api::ApiExt + + AuraApi::Public> + + AuraUnincludedSegmentApi +{ +} diff --git a/cumulus/polkadot-parachain/src/common/mod.rs b/cumulus/polkadot-parachain/src/common/mod.rs new file mode 100644 index 0000000000000000000000000000000000000000..5adbb4137cd3da4070dc7f271cf2ac1c826e395c --- /dev/null +++ b/cumulus/polkadot-parachain/src/common/mod.rs @@ -0,0 +1,67 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Cumulus. + +// Cumulus 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. + +// Cumulus 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 Cumulus. If not, see . + +//! Cumulus parachain collator primitives. + +#![warn(missing_docs)] + +pub mod aura; + +use cumulus_primitives_core::CollectCollationInfo; +use sp_api::{ApiExt, CallApiAt, ConstructRuntimeApi, Metadata}; +use sp_block_builder::BlockBuilder; +use sp_runtime::traits::Block as BlockT; +use sp_session::SessionKeys; +use sp_transaction_pool::runtime_api::TaggedTransactionQueue; + +/// Convenience trait that defines the basic bounds for the `RuntimeApi` of a parachain node. +pub trait NodeRuntimeApi: + ApiExt + + Metadata + + SessionKeys + + BlockBuilder + + TaggedTransactionQueue + + CollectCollationInfo + + Sized +{ +} + +impl NodeRuntimeApi for T where + T: ApiExt + + Metadata + + SessionKeys + + BlockBuilder + + TaggedTransactionQueue + + CollectCollationInfo +{ +} + +/// Convenience trait that defines the basic bounds for the `ConstructRuntimeApi` of a parachain +/// node. +pub trait ConstructNodeRuntimeApi>: + ConstructRuntimeApi + Send + Sync + 'static +{ + /// Basic bounds for the `RuntimeApi` of a parachain node. + type BoundedRuntimeApi: NodeRuntimeApi; +} + +impl> ConstructNodeRuntimeApi for T +where + T: ConstructRuntimeApi + Send + Sync + 'static, + T::RuntimeApi: NodeRuntimeApi, +{ + type BoundedRuntimeApi = T::RuntimeApi; +} 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 82c02943c5fc9ee8337cca377ddf2271b454cdda..0b79d338c16813238e70a29d454e91882113128f 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 @@ -105,12 +105,6 @@ sp_api::impl_runtime_apis! { } } - impl sp_offchain::OffchainWorkerApi for Runtime { - fn offchain_worker(_: &::Header) { - unimplemented!() - } - } - impl sp_session::SessionKeys for Runtime { fn generate_session_keys(_: Option>) -> 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 6b718e9121642e37640ad09ee9364974a3d0aa38..823eb9ab584a06ea1370d6b4c03ce124c426f9fe 100644 --- a/cumulus/polkadot-parachain/src/fake_runtime_api/aura.rs +++ b/cumulus/polkadot-parachain/src/fake_runtime_api/aura.rs @@ -105,12 +105,6 @@ sp_api::impl_runtime_apis! { } } - impl sp_offchain::OffchainWorkerApi for Runtime { - fn offchain_worker(_: &::Header) { - unimplemented!() - } - } - impl sp_session::SessionKeys for Runtime { fn generate_session_keys(_: Option>) -> Vec { unimplemented!() diff --git a/cumulus/polkadot-parachain/src/main.rs b/cumulus/polkadot-parachain/src/main.rs index 0757bea84aae83b64ec24982874c28f095057e75..2bf659228bc6020276858fcd2b154e5c0e37f82b 100644 --- a/cumulus/polkadot-parachain/src/main.rs +++ b/cumulus/polkadot-parachain/src/main.rs @@ -22,6 +22,7 @@ mod chain_spec; mod cli; mod command; +mod common; mod fake_runtime_api; mod rpc; mod service; diff --git a/cumulus/polkadot-parachain/src/service.rs b/cumulus/polkadot-parachain/src/service.rs index 19ad75e384cecd307608cd02cdbf67a42c5a93b0..a22ae77a77594680f45ee283f266378d0be207de 100644 --- a/cumulus/polkadot-parachain/src/service.rs +++ b/cumulus/polkadot-parachain/src/service.rs @@ -14,13 +14,11 @@ // You should have received a copy of the GNU General Public License // along with Cumulus. If not, see . -use codec::{Codec, Decode}; +use codec::Decode; use cumulus_client_cli::CollatorOptions; use cumulus_client_collator::service::CollatorService; use cumulus_client_consensus_aura::collators::lookahead::{self as aura, Params as AuraParams}; -use cumulus_client_consensus_common::{ - ParachainBlockImport as TParachainBlockImport, ParachainCandidate, ParachainConsensus, -}; +use cumulus_client_consensus_common::ParachainBlockImport as TParachainBlockImport; use cumulus_client_consensus_proposer::Proposer; #[allow(deprecated)] use cumulus_client_service::old_consensus; @@ -28,22 +26,26 @@ use cumulus_client_service::{ build_network, build_relay_chain_interface, prepare_node_config, start_relay_chain_tasks, BuildNetworkParams, CollatorSybilResistance, DARecoveryProfile, StartRelayChainTasksParams, }; -use cumulus_primitives_core::{ - relay_chain::{Hash as PHash, PersistedValidationData, ValidationCode}, - ParaId, -}; +use cumulus_primitives_core::{relay_chain::ValidationCode, ParaId}; use cumulus_relay_chain_interface::{OverseerHandle, RelayChainInterface}; use sc_rpc::DenyUnsafe; -use sp_core::Pair; use jsonrpsee::RpcModule; -use crate::{fake_runtime_api::aura::RuntimeApi as FakeRuntimeApi, rpc}; -pub use parachains_common::{AccountId, AuraId, Balance, Block, Hash, Header, Nonce}; +use crate::{ + common::{ + aura::{AuraIdT, AuraRuntimeApi}, + ConstructNodeRuntimeApi, + }, + fake_runtime_api::aura::RuntimeApi as FakeRuntimeApi, + rpc, +}; +pub use parachains_common::{AccountId, AuraId, Balance, Block, Hash, Nonce}; use cumulus_client_consensus_relay_chain::Verifier as RelayChainVerifier; -use futures::{lock::Mutex, prelude::*}; +use futures::prelude::*; use prometheus_endpoint::Registry; +use sc_client_api::Backend as ClientApiBackend; use sc_consensus::{ import_queue::{BasicQueue, Verifier as VerifierT}, BlockImportParams, ImportQueue, @@ -53,8 +55,8 @@ use sc_network::{config::FullNetworkConfiguration, service::traits::NetworkBacke use sc_network_sync::SyncingService; use sc_service::{Configuration, PartialComponents, TFullBackend, TFullClient, TaskManager}; use sc_telemetry::{Telemetry, TelemetryHandle, TelemetryWorker, TelemetryWorkerHandle}; -use sp_api::{ApiExt, ConstructRuntimeApi, ProvideRuntimeApi}; -use sp_consensus_aura::AuraApi; +use sp_api::{ConstructRuntimeApi, ProvideRuntimeApi}; +use sp_blockchain::HeaderBackend; use sp_core::traits::SpawnEssentialNamed; use sp_keystore::KeystorePtr; use sp_runtime::{ @@ -100,13 +102,7 @@ pub fn new_partial( build_import_queue: BIQ, ) -> Result, sc_service::Error> where - RuntimeApi: ConstructRuntimeApi> + Send + Sync + 'static, - RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue - + sp_api::Metadata - + sp_session::SessionKeys - + sp_api::ApiExt - + sp_offchain::OffchainWorkerApi - + sp_block_builder::BlockBuilder, + RuntimeApi: ConstructNodeRuntimeApi>, BIQ: FnOnce( Arc>, ParachainBlockImport, @@ -200,16 +196,7 @@ async fn start_node_impl( hwbench: Option, ) -> sc_service::error::Result<(TaskManager, Arc>)> where - RuntimeApi: ConstructRuntimeApi> + Send + Sync + 'static, - RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue - + sp_api::Metadata - + sp_session::SessionKeys - + sp_api::ApiExt - + sp_offchain::OffchainWorkerApi - + sp_block_builder::BlockBuilder - + cumulus_primitives_core::CollectCollationInfo - + pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi - + substrate_frame_rpc_system::AccountNonceApi, + RuntimeApi: ConstructNodeRuntimeApi>, RB: Fn( DenyUnsafe, Arc>, @@ -511,82 +498,9 @@ pub async fn start_shell_node>( .await } -enum BuildOnAccess { - Uninitialized(Option R + Send + Sync>>), - Initialized(R), -} - -impl BuildOnAccess { - fn get_mut(&mut self) -> &mut R { - loop { - match self { - Self::Uninitialized(f) => { - *self = Self::Initialized((f.take().unwrap())()); - }, - Self::Initialized(ref mut r) => return r, - } - } - } -} - -/// Special [`ParachainConsensus`] implementation that waits for the upgrade from -/// shell to a parachain runtime that implements Aura. -struct WaitForAuraConsensus { - client: Arc, - aura_consensus: Arc>>>>, - relay_chain_consensus: Arc>>>, - _phantom: PhantomData, -} - -impl Clone for WaitForAuraConsensus { - fn clone(&self) -> Self { - Self { - client: self.client.clone(), - aura_consensus: self.aura_consensus.clone(), - relay_chain_consensus: self.relay_chain_consensus.clone(), - _phantom: PhantomData, - } - } -} - -#[async_trait::async_trait] -impl ParachainConsensus for WaitForAuraConsensus -where - Client: sp_api::ProvideRuntimeApi + Send + Sync, - Client::Api: AuraApi, - AuraId: Send + Codec + Sync, -{ - async fn produce_candidate( - &mut self, - parent: &Header, - relay_parent: PHash, - validation_data: &PersistedValidationData, - ) -> Option> { - if self - .client - .runtime_api() - .has_api::>(parent.hash()) - .unwrap_or(false) - { - self.aura_consensus - .lock() - .await - .get_mut() - .produce_candidate(parent, relay_parent, validation_data) - .await - } else { - self.relay_chain_consensus - .lock() - .await - .produce_candidate(parent, relay_parent, validation_data) - .await - } - } -} - struct Verifier { client: Arc, - aura_verifier: BuildOnAccess>>, + aura_verifier: Box>, relay_chain_verifier: Box>, _phantom: PhantomData, } @@ -594,21 +508,16 @@ struct Verifier { #[async_trait::async_trait] impl VerifierT for Verifier where - Client: sp_api::ProvideRuntimeApi + Send + Sync, - Client::Api: AuraApi, - AuraId: Send + Sync + Codec, + Client: ProvideRuntimeApi + Send + Sync, + Client::Api: AuraRuntimeApi, + AuraId: AuraIdT + Sync, { async fn verify( - &mut self, + &self, block_import: BlockImportParams, ) -> Result, String> { - if self - .client - .runtime_api() - .has_api::>(*block_import.header.parent_hash()) - .unwrap_or(false) - { - self.aura_verifier.get_mut().verify(block_import).await + if self.client.runtime_api().has_aura_api(*block_import.header.parent_hash()) { + self.aura_verifier.verify(block_import).await } else { self.relay_chain_verifier.verify(block_import).await } @@ -617,7 +526,7 @@ where /// Build the import queue for parachain runtimes that started with relay chain consensus and /// switched to aura. -pub fn build_relay_to_aura_import_queue( +pub fn build_relay_to_aura_import_queue( client: Arc>, block_import: ParachainBlockImport, config: &Configuration, @@ -625,48 +534,37 @@ pub fn build_relay_to_aura_import_queue( task_manager: &TaskManager, ) -> Result, sc_service::Error> where - RuntimeApi: ConstructRuntimeApi> + Send + Sync + 'static, - RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue - + sp_api::Metadata - + sp_session::SessionKeys - + sp_api::ApiExt - + sp_offchain::OffchainWorkerApi - + sp_block_builder::BlockBuilder - + sp_consensus_aura::AuraApi::Pair as Pair>::Public>, - <::Pair as Pair>::Signature: - TryFrom> + std::hash::Hash + sp_runtime::traits::Member + Codec, + RuntimeApi: ConstructNodeRuntimeApi>, + RuntimeApi::RuntimeApi: AuraRuntimeApi, + AuraId: AuraIdT + Sync, { let verifier_client = client.clone(); - let aura_verifier = move || { - Box::new(cumulus_client_consensus_aura::build_verifier::< - ::Pair, - _, - _, - _, - >(cumulus_client_consensus_aura::BuildVerifierParams { - client: verifier_client.clone(), - create_inherent_data_providers: move |parent_hash, _| { - let cidp_client = verifier_client.clone(); - async move { - let slot_duration = cumulus_client_consensus_aura::slot_duration_at( - &*cidp_client, - parent_hash, - )?; - let timestamp = sp_timestamp::InherentDataProvider::from_system_time(); - - let slot = - sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration( - *timestamp, - slot_duration, - ); - - Ok((slot, timestamp)) - } - }, - telemetry: telemetry_handle, - })) as Box<_> - }; + let aura_verifier = cumulus_client_consensus_aura::build_verifier::< + ::Pair, + _, + _, + _, + >(cumulus_client_consensus_aura::BuildVerifierParams { + client: verifier_client.clone(), + create_inherent_data_providers: move |parent_hash, _| { + let cidp_client = verifier_client.clone(); + async move { + let slot_duration = + cumulus_client_consensus_aura::slot_duration_at(&*cidp_client, parent_hash)?; + let timestamp = sp_timestamp::InherentDataProvider::from_system_time(); + + let slot = + sp_consensus_aura::inherents::InherentDataProvider::from_timestamp_and_slot_duration( + *timestamp, + slot_duration, + ); + + Ok((slot, timestamp)) + } + }, + telemetry: telemetry_handle, + }); let relay_chain_verifier = Box::new(RelayChainVerifier::new(client.clone(), |_, _| async { Ok(()) })) as Box<_>; @@ -674,7 +572,7 @@ where let verifier = Verifier { client, relay_chain_verifier, - aura_verifier: BuildOnAccess::Uninitialized(Some(Box::new(aura_verifier))), + aura_verifier: Box::new(aura_verifier), _phantom: PhantomData, }; @@ -714,11 +612,7 @@ pub async fn start_generic_aura_lookahead_node> /// /// Uses the lookahead collator to support async backing. #[sc_tracing::logging::prefix_logs_with("Parachain")] -pub async fn start_asset_hub_lookahead_node< - RuntimeApi, - AuraId: AppCrypto + Send + Codec + Sync, - Net, ->( +pub async fn start_asset_hub_lookahead_node( parachain_config: Configuration, polkadot_config: Configuration, collator_options: CollatorOptions, @@ -726,20 +620,11 @@ pub async fn start_asset_hub_lookahead_node< hwbench: Option, ) -> sc_service::error::Result<(TaskManager, Arc>)> where - RuntimeApi: ConstructRuntimeApi> + Send + Sync + 'static, - RuntimeApi::RuntimeApi: sp_transaction_pool::runtime_api::TaggedTransactionQueue - + sp_api::Metadata - + sp_session::SessionKeys - + sp_api::ApiExt - + sp_offchain::OffchainWorkerApi - + sp_block_builder::BlockBuilder - + cumulus_primitives_core::CollectCollationInfo - + sp_consensus_aura::AuraApi::Pair as Pair>::Public> + RuntimeApi: ConstructNodeRuntimeApi>, + RuntimeApi::RuntimeApi: AuraRuntimeApi + pallet_transaction_payment_rpc::TransactionPaymentRuntimeApi - + substrate_frame_rpc_system::AccountNonceApi - + cumulus_primitives_aura::AuraUnincludedSegmentApi, - <::Pair as Pair>::Signature: - TryFrom> + std::hash::Hash + sp_runtime::traits::Member + Codec, + + substrate_frame_rpc_system::AccountNonceApi, + AuraId: AuraIdT + Sync, Net: NetworkBackend, { start_node_impl::( @@ -807,11 +692,7 @@ where // Check if we have upgraded to an Aura compatible runtime and transition if // necessary. - if client - .runtime_api() - .has_api::>(last_head_hash) - .unwrap_or(false) - { + if client.runtime_api().has_aura_api(last_head_hash) { // Respond to this request before transitioning to Aura. request.complete(None); break @@ -930,14 +811,14 @@ fn start_relay_chain_consensus( } /// Start consensus using the lookahead aura collator. -fn start_lookahead_aura_consensus( - client: Arc>, - block_import: ParachainBlockImport, +fn start_lookahead_aura_consensus( + client: Arc>, + block_import: ParachainBlockImport, prometheus_registry: Option<&Registry>, telemetry: Option, task_manager: &TaskManager, relay_chain_interface: Arc, - transaction_pool: Arc>>, + transaction_pool: Arc>>, sync_oracle: Arc>, keystore: KeystorePtr, relay_chain_slot_duration: Duration, @@ -946,7 +827,16 @@ fn start_lookahead_aura_consensus( overseer_handle: OverseerHandle, announce_block: Arc>) + Send + Sync>, backend: Arc, -) -> Result<(), sc_service::Error> { +) -> Result<(), sc_service::Error> +where + RuntimeApi: ConstructNodeRuntimeApi>, + RuntimeApi::RuntimeApi: AuraRuntimeApi, +{ + let info = backend.blockchain().info(); + if !client.runtime_api().has_aura_api(info.finalized_hash) { + return Err(sc_service::error::Error::Other("Missing aura runtime APIs".to_string())); + } + let proposer_factory = sc_basic_authorship::ProposerFactory::with_proof_recording( task_manager.spawn_handle(), client.clone(), diff --git a/cumulus/primitives/aura/Cargo.toml b/cumulus/primitives/aura/Cargo.toml index ef96f334d63753c73de669ddcd98b6868a88389b..f17c2035edd66a46be4810fa470357c1ccd3fdbd 100644 --- a/cumulus/primitives/aura/Cargo.toml +++ b/cumulus/primitives/aura/Cargo.toml @@ -10,17 +10,17 @@ description = "Core primitives for Aura in Cumulus" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } # Substrate -sp-api = { path = "../../../substrate/primitives/api", default-features = false } -sp-consensus-aura = { path = "../../../substrate/primitives/consensus/aura", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +sp-api = { workspace = true } +sp-consensus-aura = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } # Polkadot -polkadot-core-primitives = { path = "../../../polkadot/core-primitives", default-features = false } -polkadot-primitives = { path = "../../../polkadot/primitives", default-features = false } +polkadot-core-primitives = { workspace = true } +polkadot-primitives = { workspace = true } [features] default = ["std"] diff --git a/cumulus/primitives/core/Cargo.toml b/cumulus/primitives/core/Cargo.toml index 595aa5f72bf2453edea23e372865de95e9e46699..f41213e9485e2509965a25ce556f687a185bba9a 100644 --- a/cumulus/primitives/core/Cargo.toml +++ b/cumulus/primitives/core/Cargo.toml @@ -10,20 +10,20 @@ description = "Cumulus related core primitive types and traits" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } # Substrate -sp-api = { path = "../../../substrate/primitives/api", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } -sp-trie = { path = "../../../substrate/primitives/trie", default-features = false } +sp-api = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } +sp-trie = { workspace = true } # Polkadot -polkadot-core-primitives = { path = "../../../polkadot/core-primitives", default-features = false } -polkadot-parachain-primitives = { path = "../../../polkadot/parachain", default-features = false } -polkadot-primitives = { path = "../../../polkadot/primitives", default-features = false } -xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false } +polkadot-core-primitives = { workspace = true } +polkadot-parachain-primitives = { workspace = true } +polkadot-primitives = { workspace = true } +xcm = { workspace = true } [features] default = ["std"] diff --git a/cumulus/primitives/parachain-inherent/Cargo.toml b/cumulus/primitives/parachain-inherent/Cargo.toml index 0156eb02e2b4aaa9ee02e4e237f305c20792569d..c07fe07545614c375634027df171948dbdb95285 100644 --- a/cumulus/primitives/parachain-inherent/Cargo.toml +++ b/cumulus/primitives/parachain-inherent/Cargo.toml @@ -10,20 +10,20 @@ license = "Apache-2.0" workspace = true [dependencies] -async-trait = { version = "0.1.79", optional = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +async-trait = { optional = true, workspace = true } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } # Substrate -sp-core = { path = "../../../substrate/primitives/core", default-features = false } -sp-inherents = { path = "../../../substrate/primitives/inherents", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", optional = true, default-features = false } -sp-state-machine = { path = "../../../substrate/primitives/state-machine", optional = true, default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } -sp-trie = { path = "../../../substrate/primitives/trie", default-features = false } +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 -cumulus-primitives-core = { path = "../core", default-features = false } +cumulus-primitives-core = { workspace = true } [features] default = ["std"] diff --git a/cumulus/primitives/proof-size-hostfunction/Cargo.toml b/cumulus/primitives/proof-size-hostfunction/Cargo.toml index dd584ce86b2e3172563848f028730709e1b1600d..e61c865d05fb07aaff931f0ecd59a09c2592a0fa 100644 --- a/cumulus/primitives/proof-size-hostfunction/Cargo.toml +++ b/cumulus/primitives/proof-size-hostfunction/Cargo.toml @@ -10,14 +10,14 @@ license = "Apache-2.0" workspace = true [dependencies] -sp-runtime-interface = { path = "../../../substrate/primitives/runtime-interface", default-features = false } -sp-externalities = { path = "../../../substrate/primitives/externalities", default-features = false } -sp-trie = { path = "../../../substrate/primitives/trie", default-features = false } +sp-runtime-interface = { workspace = true } +sp-externalities = { workspace = true } +sp-trie = { workspace = true } [dev-dependencies] -sp-state-machine = { path = "../../../substrate/primitives/state-machine" } -sp-core = { path = "../../../substrate/primitives/core" } -sp-io = { path = "../../../substrate/primitives/io" } +sp-state-machine = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/cumulus/primitives/storage-weight-reclaim/Cargo.toml b/cumulus/primitives/storage-weight-reclaim/Cargo.toml index bdfb83ad72a96930c1dae2d2c054a2c19c5cfcb2..af32fb68d8bb20e6c61b2065ddfe948c98bd64a6 100644 --- a/cumulus/primitives/storage-weight-reclaim/Cargo.toml +++ b/cumulus/primitives/storage-weight-reclaim/Cargo.toml @@ -10,24 +10,24 @@ license = "Apache-2.0" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } -frame-support = { path = "../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } +frame-support = { workspace = true } +frame-system = { workspace = true } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +sp-runtime = { workspace = true } +sp-std = { workspace = true } -cumulus-primitives-core = { path = "../core", default-features = false } -cumulus-primitives-proof-size-hostfunction = { path = "../proof-size-hostfunction", default-features = false } -docify = "0.2.8" +cumulus-primitives-core = { workspace = true } +cumulus-primitives-proof-size-hostfunction = { workspace = true } +docify = { workspace = true } [dev-dependencies] -sp-trie = { path = "../../../substrate/primitives/trie", default-features = false } -sp-io = { path = "../../../substrate/primitives/io", default-features = false } -cumulus-test-runtime = { path = "../../test/runtime" } +sp-trie = { workspace = true } +sp-io = { workspace = true } +cumulus-test-runtime = { workspace = true } [features] default = ["std"] diff --git a/cumulus/primitives/storage-weight-reclaim/src/lib.rs b/cumulus/primitives/storage-weight-reclaim/src/lib.rs index c09c12d7a0abf8ac3c64974390d47880af6ec6e9..35fa334f51c6996c48825cec03a0a90df5b0acbe 100644 --- a/cumulus/primitives/storage-weight-reclaim/src/lib.rs +++ b/cumulus/primitives/storage-weight-reclaim/src/lib.rs @@ -201,7 +201,7 @@ mod tests { use super::*; use frame_support::{ assert_ok, - dispatch::DispatchClass, + dispatch::{DispatchClass, PerDispatchClass}, weights::{Weight, WeightMeter}, }; use frame_system::{BlockWeight, CheckWeight}; @@ -215,7 +215,7 @@ mod tests { pages: 0u64, }); const ALICE: AccountId32 = AccountId32::new([1u8; 32]); - const LEN: usize = 0; + const LEN: usize = 150; pub fn new_test_ext() -> sp_io::TestExternalities { let ext: sp_io::TestExternalities = cumulus_test_runtime::RuntimeGenesisConfig::default() @@ -256,6 +256,10 @@ mod tests { }); } + fn get_storage_weight() -> PerDispatchClass { + BlockWeight::::get() + } + #[test] fn basic_refund() { // The real cost will be 100 bytes of storage size @@ -268,6 +272,9 @@ mod tests { let info = DispatchInfo { weight: Weight::from_parts(0, 500), ..Default::default() }; let post_info = PostDispatchInfo::default(); + // Should add 500 + 150 (len) to weight. + assert_ok!(CheckWeight::::do_pre_dispatch(&info, LEN)); + let pre = StorageWeightReclaim::(PhantomData) .pre_dispatch(&ALICE, CALL, &info, LEN) .unwrap(); @@ -283,7 +290,7 @@ mod tests { &Ok(()) )); - assert_eq!(BlockWeight::::get().total().proof_size(), 600); + assert_eq!(get_storage_weight().total().proof_size(), 1250); }) } @@ -299,6 +306,9 @@ mod tests { let info = DispatchInfo { weight: Weight::from_parts(0, 500), ..Default::default() }; let post_info = PostDispatchInfo::default(); + // Adds 500 + 150 (len) weight + assert_ok!(CheckWeight::::do_pre_dispatch(&info, LEN)); + let pre = StorageWeightReclaim::(PhantomData) .pre_dispatch(&ALICE, CALL, &info, LEN) .unwrap(); @@ -313,7 +323,7 @@ mod tests { &Ok(()) )); - assert_eq!(BlockWeight::::get().total().proof_size(), 1000); + assert_eq!(get_storage_weight().total().proof_size(), 1650); }) } @@ -327,6 +337,9 @@ mod tests { let info = DispatchInfo { weight: Weight::from_parts(0, 100), ..Default::default() }; let post_info = PostDispatchInfo::default(); + // Weight added should be 100 + 150 (len) + assert_ok!(CheckWeight::::do_pre_dispatch(&info, LEN)); + let pre = StorageWeightReclaim::(PhantomData) .pre_dispatch(&ALICE, CALL, &info, LEN) .unwrap(); @@ -342,7 +355,10 @@ mod tests { &Ok(()) )); - assert_eq!(BlockWeight::::get().total().proof_size(), 1100); + assert_eq!( + get_storage_weight().total().proof_size(), + 1100 + LEN as u64 + info.weight.proof_size() + ); }) } @@ -354,6 +370,8 @@ mod tests { let info = DispatchInfo { weight: Weight::from_parts(0, 500), ..Default::default() }; let post_info = PostDispatchInfo::default(); + assert_ok!(CheckWeight::::do_pre_dispatch(&info, LEN)); + let pre = StorageWeightReclaim::(PhantomData) .pre_dispatch(&ALICE, CALL, &info, LEN) .unwrap(); @@ -368,7 +386,8 @@ mod tests { &Ok(()) )); - assert_eq!(BlockWeight::::get().total().proof_size(), 0); + // Proof size should be exactly equal to extrinsic length + assert_eq!(get_storage_weight().total().proof_size(), LEN as u64); }); } @@ -382,12 +401,17 @@ mod tests { let info = DispatchInfo { weight: Weight::from_parts(0, 500), ..Default::default() }; let post_info = PostDispatchInfo::default(); + // Adds 500 + 150 (len) weight, total weight is 1950 + assert_ok!(CheckWeight::::do_pre_dispatch(&info, LEN)); + let pre = StorageWeightReclaim::(PhantomData) .pre_dispatch(&ALICE, CALL, &info, LEN) .unwrap(); assert_eq!(pre, Some(300)); + // Refund 500 unspent weight according to `post_info`, total weight is now 1650 assert_ok!(CheckWeight::::post_dispatch(None, &info, &post_info, 0, &Ok(()))); + // Recorded proof size is negative -200, total weight is now 1450 assert_ok!(StorageWeightReclaim::::post_dispatch( Some(pre), &info, @@ -396,7 +420,7 @@ mod tests { &Ok(()) )); - assert_eq!(BlockWeight::::get().total().proof_size(), 800); + assert_eq!(get_storage_weight().total().proof_size(), 1450); }); } @@ -416,6 +440,9 @@ mod tests { pays_fee: Default::default(), }; + // Should add 300 + 150 (len) of weight + assert_ok!(CheckWeight::::do_pre_dispatch(&info, LEN)); + let pre = StorageWeightReclaim::(PhantomData) .pre_dispatch(&ALICE, CALL, &info, LEN) .unwrap(); @@ -432,7 +459,8 @@ mod tests { &Ok(()) )); - assert_eq!(BlockWeight::::get().total().proof_size(), 900); + // Reclaimed 100 + assert_eq!(get_storage_weight().total().proof_size(), 1350); }) } @@ -451,6 +479,9 @@ mod tests { pays_fee: Default::default(), }; + // Adds 50 + 150 (len) weight, total weight 1200 + assert_ok!(CheckWeight::::do_pre_dispatch(&info, LEN)); + let pre = StorageWeightReclaim::(PhantomData) .pre_dispatch(&ALICE, CALL, &info, LEN) .unwrap(); @@ -458,7 +489,56 @@ mod tests { // The `CheckWeight` extension will refund `actual_weight` from `PostDispatchInfo` // we always need to call `post_dispatch` to verify that they interoperate correctly. + + // Refunds unspent 25 weight according to `post_info`, 1175 assert_ok!(CheckWeight::::post_dispatch(None, &info, &post_info, 0, &Ok(()))); + // Adds 200 - 25 (unspent) == 175 weight, total weight 1350 + assert_ok!(StorageWeightReclaim::::post_dispatch( + Some(pre), + &info, + &post_info, + LEN, + &Ok(()) + )); + + assert_eq!(get_storage_weight().total().proof_size(), 1350); + }) + } + + #[test] + fn test_nothing_relcaimed() { + let mut test_ext = setup_test_externalities(&[100, 200]); + + test_ext.execute_with(|| { + set_current_storage_weight(0); + // Benchmarked storage weight: 100 + let info = DispatchInfo { weight: Weight::from_parts(100, 100), ..Default::default() }; + + // Actual proof size is 100 + let post_info = PostDispatchInfo { + actual_weight: Some(Weight::from_parts(50, 100)), + pays_fee: Default::default(), + }; + + // Adds benchmarked weight 100 + 150 (len), total weight is now 250 + assert_ok!(CheckWeight::::do_pre_dispatch(&info, LEN)); + + // Weight should go up by 150 len + 100 proof size weight, total weight 250 + assert_eq!(get_storage_weight().total().proof_size(), 250); + + let pre = StorageWeightReclaim::(PhantomData) + .pre_dispatch(&ALICE, CALL, &info, LEN) + .unwrap(); + // Should return `setup_test_externalities` proof recorder value: 100. + assert_eq!(pre, Some(100)); + + // The `CheckWeight` extension will refund `actual_weight` from `PostDispatchInfo` + // we always need to call `post_dispatch` to verify that they interoperate correctly. + // Nothing to refund, unspent is 0, total weight 250 + assert_ok!(CheckWeight::::post_dispatch(None, &info, &post_info, LEN, &Ok(()))); + // `setup_test_externalities` proof recorder value: 200, so this means the extrinsic + // actually used 100 proof size. + // Nothing to refund or add, weight matches proof recorder assert_ok!(StorageWeightReclaim::::post_dispatch( Some(pre), &info, @@ -467,7 +547,9 @@ mod tests { &Ok(()) )); - assert_eq!(BlockWeight::::get().total().proof_size(), 1150); + // Check block len weight was not reclaimed: + // 100 weight + 150 extrinsic len == 250 proof size + assert_eq!(get_storage_weight().total().proof_size(), 250); }) } @@ -487,11 +569,15 @@ mod tests { pays_fee: Default::default(), }; + // Adds 300 + 150 (len) weight, total weight 1450 + assert_ok!(CheckWeight::::do_pre_dispatch(&info, LEN)); + let pre = StorageWeightReclaim::(PhantomData) .pre_dispatch(&ALICE, CALL, &info, LEN) .unwrap(); assert_eq!(pre, Some(100)); + // This refunds 100 - 50(unspent), total weight is now 1400 assert_ok!(StorageWeightReclaim::::post_dispatch( Some(pre), &info, @@ -504,7 +590,8 @@ mod tests { // we always need to call `post_dispatch` to verify that they interoperate correctly. assert_ok!(CheckWeight::::post_dispatch(None, &info, &post_info, 0, &Ok(()))); - assert_eq!(BlockWeight::::get().total().proof_size(), 900); + // Above call refunds 50 (unspent), total weight is 1350 now + assert_eq!(get_storage_weight().total().proof_size(), 1350); }) } @@ -523,11 +610,15 @@ mod tests { pays_fee: Default::default(), }; + // Adds 50 + 150 (len) weight, total weight is 1200 + assert_ok!(CheckWeight::::do_pre_dispatch(&info, LEN)); + let pre = StorageWeightReclaim::(PhantomData) .pre_dispatch(&ALICE, CALL, &info, LEN) .unwrap(); assert_eq!(pre, Some(100)); + // Adds additional 150 weight recorded assert_ok!(StorageWeightReclaim::::post_dispatch( Some(pre), &info, @@ -540,7 +631,7 @@ mod tests { // we always need to call `post_dispatch` to verify that they interoperate correctly. assert_ok!(CheckWeight::::post_dispatch(None, &info, &post_info, 0, &Ok(()))); - assert_eq!(BlockWeight::::get().total().proof_size(), 1150); + assert_eq!(get_storage_weight().total().proof_size(), 1350); }) } @@ -644,7 +735,7 @@ mod tests { // We reclaimed 3 bytes of storage size! assert_eq!(reclaimed, Some(Weight::from_parts(0, 3))); - assert_eq!(BlockWeight::::get().total().proof_size(), 10); + assert_eq!(get_storage_weight().total().proof_size(), 10); assert_eq!(remaining_weight_meter.remaining(), Weight::from_parts(10, 8)); } } diff --git a/cumulus/primitives/timestamp/Cargo.toml b/cumulus/primitives/timestamp/Cargo.toml index 7a6f4787ba3121cf0c9c7eec3b9f3794c870037d..f7bf53a9d7d7cb4180f7afd9bc0c574e89675513 100644 --- a/cumulus/primitives/timestamp/Cargo.toml +++ b/cumulus/primitives/timestamp/Cargo.toml @@ -10,16 +10,16 @@ license = "Apache-2.0" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -futures = "0.3.28" +codec = { features = ["derive"], workspace = true } +futures = { workspace = true } # Substrate -sp-inherents = { path = "../../../substrate/primitives/inherents", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } -sp-timestamp = { path = "../../../substrate/primitives/timestamp", default-features = false } +sp-inherents = { workspace = true } +sp-std = { workspace = true } +sp-timestamp = { workspace = true } # Cumulus -cumulus-primitives-core = { path = "../core", default-features = false } +cumulus-primitives-core = { workspace = true } [features] default = ["std"] diff --git a/cumulus/primitives/utility/Cargo.toml b/cumulus/primitives/utility/Cargo.toml index 85e3ac2f7606c9e12aa4d38f0c44c3fe1818b107..a2fa2dd9806dca4743d13215ae4a30b7738567b7 100644 --- a/cumulus/primitives/utility/Cargo.toml +++ b/cumulus/primitives/utility/Cargo.toml @@ -10,25 +10,25 @@ description = "Helper datatypes for Cumulus" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } log = { workspace = true } # Substrate -frame-support = { path = "../../../substrate/frame/support", default-features = false } -sp-io = { path = "../../../substrate/primitives/io", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } -pallet-asset-conversion = { path = "../../../substrate/frame/asset-conversion", default-features = false } +frame-support = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } +pallet-asset-conversion = { workspace = true } # Polkadot -polkadot-runtime-common = { path = "../../../polkadot/runtime/common", default-features = false } -polkadot-runtime-parachains = { path = "../../../polkadot/runtime/parachains", default-features = false } -xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../polkadot/xcm/xcm-executor", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../polkadot/xcm/xcm-builder", default-features = false } +polkadot-runtime-common = { workspace = true } +polkadot-runtime-parachains = { workspace = true } +xcm = { workspace = true } +xcm-executor = { workspace = true } +xcm-builder = { workspace = true } # Cumulus -cumulus-primitives-core = { path = "../core", default-features = false } +cumulus-primitives-core = { workspace = true } [features] default = ["std"] diff --git a/cumulus/test/client/Cargo.toml b/cumulus/test/client/Cargo.toml index 120983eb9390e9007c13b08c763f13446011f98e..fbbaab73ce7695c62cfbe1e6ce62d67ba5a68509 100644 --- a/cumulus/test/client/Cargo.toml +++ b/cumulus/test/client/Cargo.toml @@ -9,43 +9,43 @@ publish = false workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } # Substrate -sc-service = { path = "../../../substrate/client/service" } -sc-consensus = { path = "../../../substrate/client/consensus/common" } -sc-consensus-aura = { path = "../../../substrate/client/consensus/aura" } -sc-block-builder = { path = "../../../substrate/client/block-builder" } -sc-executor = { path = "../../../substrate/client/executor" } -sc-executor-common = { path = "../../../substrate/client/executor/common" } -substrate-test-client = { path = "../../../substrate/test-utils/client" } -sp-application-crypto = { path = "../../../substrate/primitives/application-crypto" } -sp-runtime = { path = "../../../substrate/primitives/runtime" } -sp-core = { path = "../../../substrate/primitives/core" } -sp-api = { path = "../../../substrate/primitives/api" } -sp-keyring = { path = "../../../substrate/primitives/keyring" } -sp-keystore = { path = "../../../substrate/primitives/keystore" } -sp-consensus-aura = { path = "../../../substrate/primitives/consensus/aura" } -sp-blockchain = { path = "../../../substrate/primitives/blockchain" } -sp-inherents = { path = "../../../substrate/primitives/inherents" } -sp-io = { path = "../../../substrate/primitives/io" } -sp-timestamp = { path = "../../../substrate/primitives/timestamp" } -frame-system = { path = "../../../substrate/frame/system" } -pallet-transaction-payment = { path = "../../../substrate/frame/transaction-payment" } -pallet-balances = { path = "../../../substrate/frame/balances" } +sc-service = { workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } +sc-consensus-aura = { workspace = true, default-features = true } +sc-block-builder = { workspace = true, default-features = true } +sc-executor = { workspace = true, default-features = true } +sc-executor-common = { workspace = true, default-features = true } +substrate-test-client = { workspace = true } +sp-application-crypto = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-consensus-aura = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-inherents = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-timestamp = { workspace = true, default-features = true } +frame-system = { workspace = true, default-features = true } +pallet-transaction-payment = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } # Polkadot -polkadot-primitives = { path = "../../../polkadot/primitives" } -polkadot-parachain-primitives = { path = "../../../polkadot/parachain" } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-parachain-primitives = { workspace = true, default-features = true } # Cumulus -cumulus-test-runtime = { path = "../runtime" } -cumulus-test-service = { path = "../service" } -cumulus-test-relay-sproof-builder = { path = "../relay-sproof-builder" } -cumulus-primitives-core = { path = "../../primitives/core" } -cumulus-primitives-proof-size-hostfunction = { path = "../../primitives/proof-size-hostfunction" } -cumulus-primitives-parachain-inherent = { path = "../../primitives/parachain-inherent" } -cumulus-primitives-storage-weight-reclaim = { path = "../../primitives/storage-weight-reclaim" } +cumulus-test-runtime = { workspace = true } +cumulus-test-service = { workspace = true } +cumulus-test-relay-sproof-builder = { workspace = true, default-features = true } +cumulus-primitives-core = { workspace = true, default-features = true } +cumulus-primitives-proof-size-hostfunction = { workspace = true, default-features = true } +cumulus-primitives-parachain-inherent = { workspace = true, default-features = true } +cumulus-primitives-storage-weight-reclaim = { workspace = true, default-features = true } [features] runtime-benchmarks = [ diff --git a/cumulus/test/relay-sproof-builder/Cargo.toml b/cumulus/test/relay-sproof-builder/Cargo.toml index d775c61f7801e98b4c8e8436eb95c1ec86854d77..454266c90ba74008bbe33d65891e16fb516737e4 100644 --- a/cumulus/test/relay-sproof-builder/Cargo.toml +++ b/cumulus/test/relay-sproof-builder/Cargo.toml @@ -10,19 +10,19 @@ description = "Mocked relay state proof builder for testing Cumulus." workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } # Substrate -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-state-machine = { path = "../../../substrate/primitives/state-machine", default-features = false } -sp-trie = { path = "../../../substrate/primitives/trie", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +sp-runtime = { workspace = true } +sp-state-machine = { workspace = true } +sp-trie = { workspace = true } +sp-std = { workspace = true } # Polkadot -polkadot-primitives = { path = "../../../polkadot/primitives", default-features = false } +polkadot-primitives = { workspace = true } # Cumulus -cumulus-primitives-core = { path = "../../primitives/core", default-features = false } +cumulus-primitives-core = { workspace = true } [features] default = ["std"] diff --git a/cumulus/test/runtime/Cargo.toml b/cumulus/test/runtime/Cargo.toml index b14e3b7f040e74cfabe834d770859433cdb1553d..fc0eb3ce742f704689e3e6ba71eb7b4ceb89656d 100644 --- a/cumulus/test/runtime/Cargo.toml +++ b/cumulus/test/runtime/Cargo.toml @@ -9,48 +9,48 @@ publish = false workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } # Substrate -frame-executive = { path = "../../../substrate/frame/executive", default-features = false } -frame-support = { path = "../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -frame-system-rpc-runtime-api = { path = "../../../substrate/frame/system/rpc/runtime-api", default-features = false } -pallet-balances = { path = "../../../substrate/frame/balances", default-features = false } -pallet-message-queue = { path = "../../../substrate/frame/message-queue", default-features = false } -pallet-sudo = { path = "../../../substrate/frame/sudo", default-features = false } -pallet-aura = { path = "../../../substrate/frame/aura", default-features = false } -pallet-authorship = { path = "../../../substrate/frame/authorship", default-features = false } -pallet-timestamp = { path = "../../../substrate/frame/timestamp", default-features = false } -pallet-glutton = { path = "../../../substrate/frame/glutton", default-features = false } -pallet-transaction-payment = { path = "../../../substrate/frame/transaction-payment", default-features = false } -pallet-session = { path = "../../../substrate/frame/session", default-features = false } -sp-api = { path = "../../../substrate/primitives/api", default-features = false } -sp-block-builder = { path = "../../../substrate/primitives/block-builder", default-features = false } -sp-core = { path = "../../../substrate/primitives/core", default-features = false } -sp-genesis-builder = { path = "../../../substrate/primitives/genesis-builder", default-features = false } -sp-inherents = { path = "../../../substrate/primitives/inherents", default-features = false } -sp-io = { path = "../../../substrate/primitives/io", default-features = false } -sp-offchain = { path = "../../../substrate/primitives/offchain", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-session = { path = "../../../substrate/primitives/session", default-features = false } -sp-consensus-aura = { path = "../../../substrate/primitives/consensus/aura", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } -sp-transaction-pool = { path = "../../../substrate/primitives/transaction-pool", default-features = false } -sp-version = { path = "../../../substrate/primitives/version", default-features = false } +frame-executive = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +frame-system-rpc-runtime-api = { workspace = true } +pallet-balances = { workspace = true } +pallet-message-queue = { workspace = true } +pallet-sudo = { workspace = true } +pallet-aura = { workspace = true } +pallet-authorship = { workspace = true } +pallet-timestamp = { workspace = true } +pallet-glutton = { workspace = true } +pallet-transaction-payment = { workspace = true } +pallet-session = { workspace = true } +sp-api = { workspace = true } +sp-block-builder = { workspace = true } +sp-core = { workspace = true } +sp-genesis-builder = { workspace = true } +sp-inherents = { workspace = true } +sp-io = { workspace = true } +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 } # Cumulus -cumulus-pallet-parachain-system = { path = "../../pallets/parachain-system", default-features = false } -parachain-info = { package = "staging-parachain-info", path = "../../parachains/pallets/parachain-info", default-features = false } -cumulus-primitives-aura = { path = "../../primitives/aura", default-features = false } -pallet-collator-selection = { path = "../../pallets/collator-selection", default-features = false } -cumulus-pallet-aura-ext = { path = "../../pallets/aura-ext", default-features = false } -cumulus-primitives-core = { path = "../../primitives/core", default-features = false } -cumulus-primitives-storage-weight-reclaim = { path = "../../primitives/storage-weight-reclaim", default-features = false } +cumulus-pallet-parachain-system = { workspace = true } +parachain-info = { workspace = true } +cumulus-primitives-aura = { workspace = true } +pallet-collator-selection = { workspace = true } +cumulus-pallet-aura-ext = { workspace = true } +cumulus-primitives-core = { workspace = true } +cumulus-primitives-storage-weight-reclaim = { workspace = true } [build-dependencies] -substrate-wasm-builder = { path = "../../../substrate/utils/wasm-builder", optional = true } +substrate-wasm-builder = { optional = true, workspace = true, default-features = true } [features] default = ["std"] diff --git a/cumulus/test/runtime/src/lib.rs b/cumulus/test/runtime/src/lib.rs index 452b3241d0bfa4d374e3af77ad15dff8aa15a250..26c6635e1ad3200e1a78fb9f0645bf7ba989ac4b 100644 --- a/cumulus/test/runtime/src/lib.rs +++ b/cumulus/test/runtime/src/lib.rs @@ -66,7 +66,7 @@ use frame_system::{ pub use pallet_balances::Call as BalancesCall; pub use pallet_glutton::Call as GluttonCall; pub use pallet_sudo::Call as SudoCall; -pub use pallet_timestamp::Call as TimestampCall; +pub use pallet_timestamp::{Call as TimestampCall, Now}; #[cfg(any(feature = "std", test))] pub use sp_runtime::BuildStorage; pub use sp_runtime::{Perbill, Permill}; @@ -499,7 +499,7 @@ impl_runtime_apis! { impl crate::GetLastTimestamp for Runtime { fn get_last_timestamp() -> u64 { - Timestamp::now() + Now::::get() } } diff --git a/cumulus/test/service/Cargo.toml b/cumulus/test/service/Cargo.toml index 732d884528f8974b4d09b33c118f41b74d22f348..c40863b90b5443c748765c6d70288c739e415951 100644 --- a/cumulus/test/service/Cargo.toml +++ b/cumulus/test/service/Cargo.toml @@ -13,96 +13,96 @@ name = "test-parachain" path = "src/main.rs" [dependencies] -async-trait = "0.1.79" -clap = { version = "4.5.3", features = ["derive"] } -codec = { package = "parity-scale-codec", version = "3.6.12" } -criterion = { version = "0.5.1", features = ["async_tokio"] } -jsonrpsee = { version = "0.22", features = ["server"] } -rand = "0.8.5" +async-trait = { workspace = true } +clap = { features = ["derive"], workspace = true } +codec = { workspace = true, default-features = true } +criterion = { features = ["async_tokio"], workspace = true, default-features = true } +jsonrpsee = { features = ["server"], workspace = true } +rand = { workspace = true, default-features = true } serde = { features = ["derive"], workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } -tokio = { version = "1.32.0", features = ["macros"] } -tracing = "0.1.37" -url = "2.4.0" -tempfile = "3.8.0" +tokio = { features = ["macros"], workspace = true, default-features = true } +tracing = { workspace = true, default-features = true } +url = { workspace = true } +tempfile = { workspace = true } # Substrate -frame-system = { path = "../../../substrate/frame/system" } -frame-system-rpc-runtime-api = { path = "../../../substrate/frame/system/rpc/runtime-api" } -pallet-transaction-payment = { path = "../../../substrate/frame/transaction-payment" } -sc-basic-authorship = { path = "../../../substrate/client/basic-authorship" } -sc-chain-spec = { path = "../../../substrate/client/chain-spec" } -sc-client-api = { path = "../../../substrate/client/api" } -sc-consensus = { path = "../../../substrate/client/consensus/common" } -sc-consensus-aura = { path = "../../../substrate/client/consensus/aura" } -sc-executor = { path = "../../../substrate/client/executor" } -sc-network = { path = "../../../substrate/client/network" } -sc-service = { path = "../../../substrate/client/service" } -sc-tracing = { path = "../../../substrate/client/tracing" } -sc-transaction-pool = { path = "../../../substrate/client/transaction-pool" } -sc-transaction-pool-api = { path = "../../../substrate/client/transaction-pool/api" } -sc-telemetry = { path = "../../../substrate/client/telemetry" } -sp-arithmetic = { path = "../../../substrate/primitives/arithmetic" } -sp-blockchain = { path = "../../../substrate/primitives/blockchain" } -sp-core = { path = "../../../substrate/primitives/core" } -sp-io = { path = "../../../substrate/primitives/io" } -sp-api = { path = "../../../substrate/primitives/api" } -sp-keyring = { path = "../../../substrate/primitives/keyring" } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-state-machine = { path = "../../../substrate/primitives/state-machine" } -sp-tracing = { path = "../../../substrate/primitives/tracing" } -sp-timestamp = { path = "../../../substrate/primitives/timestamp" } -sp-consensus = { path = "../../../substrate/primitives/consensus/common" } -sp-consensus-aura = { path = "../../../substrate/primitives/consensus/aura" } -substrate-test-client = { path = "../../../substrate/test-utils/client" } -sc-cli = { path = "../../../substrate/client/cli" } -sc-block-builder = { path = "../../../substrate/client/block-builder" } -sc-executor-wasmtime = { path = "../../../substrate/client/executor/wasmtime" } -sc-executor-common = { path = "../../../substrate/client/executor/common" } +frame-system = { workspace = true, default-features = true } +frame-system-rpc-runtime-api = { workspace = true, default-features = true } +pallet-transaction-payment = { workspace = true, default-features = true } +sc-basic-authorship = { workspace = true, default-features = true } +sc-chain-spec = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } +sc-consensus-aura = { workspace = true, default-features = true } +sc-executor = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sc-service = { workspace = true, default-features = true } +sc-tracing = { workspace = true, default-features = true } +sc-transaction-pool = { workspace = true, default-features = true } +sc-transaction-pool-api = { workspace = true, default-features = true } +sc-telemetry = { workspace = true, default-features = true } +sp-arithmetic = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +sp-runtime = { workspace = true } +sp-state-machine = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +sp-timestamp = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-consensus-aura = { workspace = true, default-features = true } +substrate-test-client = { workspace = true } +sc-cli = { workspace = true, default-features = true } +sc-block-builder = { workspace = true, default-features = true } +sc-executor-wasmtime = { workspace = true, default-features = true } +sc-executor-common = { workspace = true, default-features = true } # Polkadot -polkadot-primitives = { path = "../../../polkadot/primitives" } -polkadot-service = { path = "../../../polkadot/node/service" } -polkadot-test-service = { path = "../../../polkadot/node/test/service" } -polkadot-cli = { path = "../../../polkadot/cli" } -polkadot-node-subsystem = { path = "../../../polkadot/node/subsystem" } -polkadot-overseer = { path = "../../../polkadot/node/overseer" } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-service = { workspace = true, default-features = true } +polkadot-test-service = { workspace = true } +polkadot-cli = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-overseer = { workspace = true, default-features = true } # Cumulus -cumulus-client-cli = { path = "../../client/cli" } -parachains-common = { path = "../../parachains/common" } -cumulus-client-consensus-common = { path = "../../client/consensus/common" } -cumulus-client-consensus-proposer = { path = "../../client/consensus/proposer" } -cumulus-client-consensus-aura = { path = "../../client/consensus/aura" } -cumulus-client-consensus-relay-chain = { path = "../../client/consensus/relay-chain" } -cumulus-client-parachain-inherent = { path = "../../client/parachain-inherent" } -cumulus-client-service = { path = "../../client/service" } -cumulus-client-collator = { path = "../../client/collator" } -cumulus-primitives-core = { path = "../../primitives/core" } -cumulus-relay-chain-inprocess-interface = { path = "../../client/relay-chain-inprocess-interface" } -cumulus-relay-chain-interface = { path = "../../client/relay-chain-interface" } -cumulus-test-runtime = { path = "../runtime" } -cumulus-relay-chain-minimal-node = { path = "../../client/relay-chain-minimal-node" } -cumulus-client-pov-recovery = { path = "../../client/pov-recovery" } -cumulus-test-relay-sproof-builder = { path = "../relay-sproof-builder" } -cumulus-pallet-parachain-system = { path = "../../pallets/parachain-system", default-features = false } -cumulus-primitives-storage-weight-reclaim = { path = "../../primitives/storage-weight-reclaim" } -pallet-timestamp = { path = "../../../substrate/frame/timestamp" } +cumulus-client-cli = { workspace = true, default-features = true } +parachains-common = { workspace = true, default-features = true } +cumulus-client-consensus-common = { workspace = true, default-features = true } +cumulus-client-consensus-proposer = { workspace = true, default-features = true } +cumulus-client-consensus-aura = { workspace = true, default-features = true } +cumulus-client-consensus-relay-chain = { workspace = true, default-features = true } +cumulus-client-parachain-inherent = { workspace = true, default-features = true } +cumulus-client-service = { workspace = true, default-features = true } +cumulus-client-collator = { workspace = true, default-features = true } +cumulus-primitives-core = { workspace = true, default-features = true } +cumulus-relay-chain-inprocess-interface = { workspace = true, default-features = true } +cumulus-relay-chain-interface = { workspace = true, default-features = true } +cumulus-test-runtime = { workspace = true } +cumulus-relay-chain-minimal-node = { workspace = true, default-features = true } +cumulus-client-pov-recovery = { workspace = true, default-features = true } +cumulus-test-relay-sproof-builder = { workspace = true, default-features = true } +cumulus-pallet-parachain-system = { workspace = true } +cumulus-primitives-storage-weight-reclaim = { workspace = true, default-features = true } +pallet-timestamp = { workspace = true, default-features = true } [dev-dependencies] -futures = "0.3.28" -portpicker = "0.1.1" -rococo-parachain-runtime = { path = "../../parachains/runtimes/testing/rococo-parachain" } -sp-consensus-grandpa = { path = "../../../substrate/primitives/consensus/grandpa" } -sp-authority-discovery = { path = "../../../substrate/primitives/authority-discovery" } -cumulus-test-client = { path = "../client" } +futures = { workspace = true } +portpicker = { workspace = true } +rococo-parachain-runtime = { workspace = true } +sp-consensus-grandpa = { workspace = true, default-features = true } +sp-authority-discovery = { workspace = true, default-features = true } +cumulus-test-client = { workspace = true } # Polkadot dependencies -polkadot-test-service = { path = "../../../polkadot/node/test/service" } +polkadot-test-service = { workspace = true } # Substrate dependencies -sc-cli = { path = "../../../substrate/client/cli" } -substrate-test-utils = { path = "../../../substrate/test-utils" } +sc-cli = { workspace = true, default-features = true } +substrate-test-utils = { workspace = true } [features] runtime-benchmarks = [ diff --git a/cumulus/xcm/xcm-emulator/Cargo.toml b/cumulus/xcm/xcm-emulator/Cargo.toml index 0ed77bf5b7073bc9e3041388206203ce7c1829a2..ba1097fba075696e9d40dffc3c4753d9956615b1 100644 --- a/cumulus/xcm/xcm-emulator/Cargo.toml +++ b/cumulus/xcm/xcm-emulator/Cargo.toml @@ -10,36 +10,36 @@ license = "Apache-2.0" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12" } -paste = "1.0.14" +codec = { workspace = true, default-features = true } +paste = { workspace = true, default-features = true } log = { workspace = true } -lazy_static = "1.4.0" -impl-trait-for-tuples = "0.2.2" +lazy_static = { workspace = true } +impl-trait-for-tuples = { workspace = true } # Substrate -frame-support = { path = "../../../substrate/frame/support" } -frame-system = { path = "../../../substrate/frame/system" } -sp-io = { path = "../../../substrate/primitives/io" } -sp-core = { path = "../../../substrate/primitives/core" } -sp-crypto-hashing = { path = "../../../substrate/primitives/crypto/hashing" } -sp-std = { path = "../../../substrate/primitives/std" } -sp-runtime = { path = "../../../substrate/primitives/runtime" } -sp-arithmetic = { path = "../../../substrate/primitives/arithmetic" } -sp-tracing = { path = "../../../substrate/primitives/tracing" } -pallet-balances = { path = "../../../substrate/frame/balances" } -pallet-message-queue = { path = "../../../substrate/frame/message-queue" } +frame-support = { workspace = true, default-features = true } +frame-system = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-crypto-hashing = { workspace = true, default-features = true } +sp-std = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-arithmetic = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +pallet-message-queue = { workspace = true, default-features = true } # Cumulus -cumulus-primitives-core = { path = "../../primitives/core" } -cumulus-pallet-xcmp-queue = { path = "../../pallets/xcmp-queue" } -cumulus-pallet-parachain-system = { path = "../../pallets/parachain-system" } -cumulus-primitives-parachain-inherent = { path = "../../primitives/parachain-inherent" } -cumulus-test-relay-sproof-builder = { path = "../../test/relay-sproof-builder" } -parachains-common = { path = "../../parachains/common" } +cumulus-primitives-core = { workspace = true, default-features = true } +cumulus-pallet-xcmp-queue = { workspace = true, default-features = true } +cumulus-pallet-parachain-system = { workspace = true, default-features = true } +cumulus-primitives-parachain-inherent = { workspace = true, default-features = true } +cumulus-test-relay-sproof-builder = { workspace = true, default-features = true } +parachains-common = { workspace = true, default-features = true } # Polkadot -xcm = { package = "staging-xcm", path = "../../../polkadot/xcm" } -xcm-executor = { package = "staging-xcm-executor", path = "../../../polkadot/xcm/xcm-executor" } -polkadot-primitives = { path = "../../../polkadot/primitives" } -polkadot-parachain-primitives = { path = "../../../polkadot/parachain" } -polkadot-runtime-parachains = { path = "../../../polkadot/runtime/parachains" } +xcm = { workspace = true, default-features = true } +xcm-executor = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-parachain-primitives = { workspace = true, default-features = true } +polkadot-runtime-parachains = { workspace = true, default-features = true } diff --git a/docker/dockerfiles/bridges_zombienet_tests_injected.Dockerfile b/docker/dockerfiles/bridges_zombienet_tests_injected.Dockerfile index 196ba861f503c0fc82b6eb0e428df600ce6bfd49..e17952ccee804d5ff82339c1770f96f28c1cdab8 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.5.0 +ARG SUBSTRATE_RELAY_IMAGE=docker.io/paritytech/substrate-relay:v1.6.4 # metadata ARG VCS_REF diff --git a/docs/mermaid/IA.mmd b/docs/mermaid/IA.mmd index fe9a96bcafc0053c18332ca5901a93142811977f..37417497e1f84f3a54fb3e55da631c9ce363e700 100644 --- a/docs/mermaid/IA.mmd +++ b/docs/mermaid/IA.mmd @@ -1,6 +1,6 @@ flowchart parity[paritytech.github.io] --> devhub[polkadot_sdk_docs] - polkadot[polkadot.network] --> devhub[polkadot_sdk_docs] + polkadot_network[polkadot.network] --> devhub[polkadot_sdk_docs] devhub --> polkadot_sdk devhub --> reference_docs @@ -9,5 +9,5 @@ flowchart polkadot_sdk --> substrate polkadot_sdk --> frame polkadot_sdk --> cumulus - polkadot_sdk --> polkadot + polkadot_sdk --> polkadot[polkadot node] polkadot_sdk --> xcm diff --git a/docs/sdk/Cargo.toml b/docs/sdk/Cargo.toml index b0671623f48d42dea7f773a4e568aa0d8a103b22..7d3d2da51ab324356056dff11429e3b68c68344d 100644 --- a/docs/sdk/Cargo.toml +++ b/docs/sdk/Cargo.toml @@ -15,95 +15,101 @@ workspace = true [dependencies] # Needed for all FRAME-based code -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -scale-info = { version = "2.6.0", default-features = false } -frame = { package = "polkadot-sdk-frame", path = "../../substrate/frame", features = [ +codec = { workspace = true } +scale-info = { workspace = true } +frame = { features = [ "experimental", "runtime", -] } -pallet-examples = { path = "../../substrate/frame/examples" } -pallet-default-config-example = { path = "../../substrate/frame/examples/default-config" } -pallet-example-offchain-worker = { path = "../../substrate/frame/examples/offchain-worker" } +], workspace = true, default-features = true } +pallet-examples = { workspace = true } +pallet-default-config-example = { workspace = true, default-features = true } +pallet-example-offchain-worker = { workspace = true, default-features = true } # How we build docs in rust-docs simple-mermaid = "0.1.1" -docify = "0.2.8" +docify = { workspace = true } # Polkadot SDK deps, typically all should only be in scope such that we can link to their doc item. -polkadot-sdk = { path = "../../umbrella", features = ["runtime"] } -node-cli = { package = "staging-node-cli", path = "../../substrate/bin/node/cli" } -kitchensink-runtime = { path = "../../substrate/bin/node/runtime" } -chain-spec-builder = { package = "staging-chain-spec-builder", path = "../../substrate/bin/utils/chain-spec-builder" } -subkey = { path = "../../substrate/bin/utils/subkey" } -frame-system = { path = "../../substrate/frame/system", default-features = false } -frame-support = { path = "../../substrate/frame/support", default-features = false } -frame-executive = { path = "../../substrate/frame/executive", default-features = false } -pallet-example-single-block-migrations = { path = "../../substrate/frame/examples/single-block-migrations" } -frame-metadata-hash-extension = { path = "../../substrate/frame/metadata-hash-extension" } +polkadot-sdk = { features = ["runtime"], workspace = true, default-features = true } +node-cli = { workspace = true } +kitchensink-runtime = { workspace = true } +chain-spec-builder = { workspace = true, default-features = true } +subkey = { workspace = true, default-features = true } +frame-system = { workspace = true } +frame-support = { workspace = true } +frame-executive = { workspace = true } +pallet-example-single-block-migrations = { workspace = true, default-features = true } +frame-metadata-hash-extension = { workspace = true, default-features = true } # Substrate Client -sc-network = { path = "../../substrate/client/network" } -sc-rpc-api = { path = "../../substrate/client/rpc-api" } -sc-rpc = { path = "../../substrate/client/rpc" } -sc-client-db = { path = "../../substrate/client/db" } -sc-cli = { path = "../../substrate/client/cli" } -sc-consensus-aura = { path = "../../substrate/client/consensus/aura" } -sc-consensus-babe = { path = "../../substrate/client/consensus/babe" } -sc-consensus-grandpa = { path = "../../substrate/client/consensus/grandpa" } -sc-consensus-beefy = { path = "../../substrate/client/consensus/beefy" } -sc-consensus-manual-seal = { path = "../../substrate/client/consensus/manual-seal" } -sc-consensus-pow = { path = "../../substrate/client/consensus/pow" } -sc-executor = { path = "../../substrate/client/executor" } -sc-service = { path = "../../substrate/client/service" } -sc-chain-spec = { path = "../../substrate/client/chain-spec" } +sc-network = { workspace = true, default-features = true } +sc-rpc-api = { workspace = true, default-features = true } +sc-rpc = { workspace = true, default-features = true } +sc-client-db = { workspace = true, default-features = true } +sc-cli = { workspace = true, default-features = true } +sc-consensus-aura = { workspace = true, default-features = true } +sc-consensus-babe = { workspace = true, default-features = true } +sc-consensus-grandpa = { workspace = true, default-features = true } +sc-consensus-beefy = { workspace = true, default-features = true } +sc-consensus-manual-seal = { workspace = true, default-features = true } +sc-consensus-pow = { workspace = true, default-features = true } +sc-executor = { workspace = true, default-features = true } +sc-service = { workspace = true, default-features = true } +sc-chain-spec = { workspace = true, default-features = true } -substrate-wasm-builder = { path = "../../substrate/utils/wasm-builder" } +substrate-wasm-builder = { workspace = true, default-features = true } # Cumulus -cumulus-pallet-aura-ext = { path = "../../cumulus/pallets/aura-ext" } -cumulus-pallet-parachain-system = { path = "../../cumulus/pallets/parachain-system" } -parachain-info = { package = "staging-parachain-info", path = "../../cumulus/parachains/pallets/parachain-info" } -cumulus-primitives-proof-size-hostfunction = { path = "../../cumulus/primitives/proof-size-hostfunction" } -cumulus-client-service = { path = "../../cumulus/client/service" } -cumulus-primitives-storage-weight-reclaim = { path = "../../cumulus/primitives/storage-weight-reclaim" } +cumulus-pallet-aura-ext = { workspace = true, default-features = true } +cumulus-pallet-parachain-system = { workspace = true, default-features = true } +parachain-info = { workspace = true, default-features = true } +cumulus-primitives-proof-size-hostfunction = { workspace = true, default-features = true } +cumulus-client-service = { workspace = true, default-features = true } +cumulus-primitives-storage-weight-reclaim = { workspace = true, default-features = true } # Pallets and FRAME internals -pallet-aura = { path = "../../substrate/frame/aura" } -pallet-timestamp = { path = "../../substrate/frame/timestamp" } -pallet-balances = { path = "../../substrate/frame/balances" } -pallet-assets = { path = "../../substrate/frame/assets" } -pallet-preimage = { path = "../../substrate/frame/preimage" } -pallet-transaction-payment = { path = "../../substrate/frame/transaction-payment" } -pallet-utility = { path = "../../substrate/frame/utility" } -pallet-multisig = { path = "../../substrate/frame/multisig" } -pallet-proxy = { path = "../../substrate/frame/proxy" } -pallet-authorship = { path = "../../substrate/frame/authorship" } -pallet-collective = { path = "../../substrate/frame/collective" } -pallet-democracy = { path = "../../substrate/frame/democracy" } -pallet-uniques = { path = "../../substrate/frame/uniques" } -pallet-nfts = { path = "../../substrate/frame/nfts" } -pallet-scheduler = { path = "../../substrate/frame/scheduler" } +pallet-aura = { workspace = true, default-features = true } +pallet-timestamp = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +pallet-assets = { workspace = true, default-features = true } +pallet-preimage = { workspace = true, default-features = true } +pallet-transaction-payment = { workspace = true, default-features = true } +pallet-utility = { workspace = true, default-features = true } +pallet-multisig = { workspace = true, default-features = true } +pallet-proxy = { workspace = true, default-features = true } +pallet-authorship = { workspace = true, default-features = true } +pallet-collective = { workspace = true, default-features = true } +pallet-democracy = { workspace = true, default-features = true } +pallet-uniques = { workspace = true, default-features = true } +pallet-nfts = { workspace = true, default-features = true } +pallet-scheduler = { workspace = true, default-features = true } +pallet-referenda = { workspace = true, default-features = true } +pallet-broker = { workspace = true, default-features = true } +pallet-babe = { workspace = true, default-features = true } # Primitives -sp-io = { path = "../../substrate/primitives/io" } -sp-api = { path = "../../substrate/primitives/api" } -sp-core = { path = "../../substrate/primitives/core" } -sp-keyring = { path = "../../substrate/primitives/keyring" } -sp-runtime = { path = "../../substrate/primitives/runtime" } -sp-arithmetic = { path = "../../substrate/primitives/arithmetic" } -sp-genesis-builder = { path = "../../substrate/primitives/genesis-builder" } +sp-io = { workspace = true, default-features = true } +sp-std = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +sp-runtime-interface = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-arithmetic = { workspace = true, default-features = true } +sp-genesis-builder = { workspace = true, default-features = true } +sp-offchain = { workspace = true, default-features = true } +sp-version = { workspace = true, default-features = true } -# Misc pallet dependencies -pallet-referenda = { path = "../../substrate/frame/referenda" } -pallet-broker = { path = "../../substrate/frame/broker" } -pallet-babe = { path = "../../substrate/frame/babe" } - -sp-offchain = { path = "../../substrate/primitives/offchain" } -sp-version = { path = "../../substrate/primitives/version" } # XCM -xcm = { package = "staging-xcm", path = "../../polkadot/xcm" } -xcm-docs = { path = "../../polkadot/xcm/docs" } +xcm = { workspace = true, default-features = true } +xcm-docs = { workspace = true } # runtime guides -chain-spec-guide-runtime = { path = "./src/reference_docs/chain_spec_runtime" } +chain-spec-guide-runtime = { workspace = true } + +# Templates +minimal-template-runtime = { workspace = true } +solochain-template-runtime = { workspace = true } +parachain-template-runtime = { workspace = true } diff --git a/docs/sdk/src/guides/mod.rs b/docs/sdk/src/guides/mod.rs index f5f6d2b5e0c0768f1cff2f759769598c4703c601..485cdc30636f2751145188c5d13a99b7d6fd6726 100644 --- a/docs/sdk/src/guides/mod.rs +++ b/docs/sdk/src/guides/mod.rs @@ -1,7 +1,16 @@ //! # Polkadot SDK Docs Guides //! -//! This crate contains a collection of guides that are foundational to the developers of -//! Polkadot SDK. They are common user-journeys that are traversed in the Polkadot ecosystem. +//! This crate contains a collection of guides that are foundational to the developers of Polkadot +//! SDK. They are common user-journeys that are traversed in the Polkadot ecosystem. +//! +//! 1. [`crate::guides::your_first_pallet`] is your starting point with Polkadot SDK. It contains +//! the basics of +//! building a simple crypto currency with FRAME. +//! 2. [`crate::guides::your_first_runtime`] is the next step in your journey. It contains the +//! basics of building a runtime that contains this pallet, plus a few common pallets from FRAME. +//! +//! +//! Other guides are related to other miscellaneous topics and are listed as modules below. /// Write your first simple pallet, learning the most most basic features of FRAME along the way. pub mod your_first_pallet; @@ -11,18 +20,18 @@ pub mod your_first_pallet; pub mod your_first_runtime; /// Running the given runtime with a node. No specific consensus mechanism is used at this stage. -pub mod your_first_node; - -/// How to change the consensus engine of both the node and the runtime. -pub mod changing_consensus; +// TODO +// pub mod your_first_node; /// How to enhance a given runtime and node to be cumulus-enabled, run it as a parachain and connect /// it to a relay-chain. -pub mod cumulus_enabled_parachain; +// TODO +// pub mod cumulus_enabled_parachain; /// How to make a given runtime XCM-enabled, capable of sending messages (`Transact`) between itself /// and the relay chain to which it is connected. -pub mod xcm_enabled_parachain; +// TODO +// pub mod xcm_enabled_parachain; /// How to enable storage weight reclaiming in a parachain node and runtime. pub mod enable_pov_reclaim; diff --git a/docs/sdk/src/guides/your_first_pallet/mod.rs b/docs/sdk/src/guides/your_first_pallet/mod.rs index c6e0dd0edf8925105661591d0831d65ff8ed02be..da4624f5ac2b85dcf884798fefca42da229760e0 100644 --- a/docs/sdk/src/guides/your_first_pallet/mod.rs +++ b/docs/sdk/src/guides/your_first_pallet/mod.rs @@ -14,18 +14,14 @@ //! > FRAME-based runtimes use various techniques to re-use a currency pallet instead of writing //! > one. Further advanced FRAME related topics are discussed in [`crate::reference_docs`]. //! -//! ## Topics Covered +//! ## Writing Your First Pallet //! -//! The following FRAME topics are covered in this guide: +//! To get started, use one of the templates mentioned in [`crate::polkadot_sdk::templates`]. We +//! recommend using the `polkadot-sdk-minimal-template`. You might need to change small parts of +//! this guide, namely the crate/package names, based on which tutorial you use. //! -//! - [Storage](frame::pallet_macros::storage) -//! - [Call](frame::pallet_macros::call) -//! - [Event](frame::pallet_macros::event) -//! - [Error](frame::pallet_macros::error) -//! - Basics of testing a pallet -//! - [Constructing a runtime](frame::runtime::prelude::construct_runtime) -//! -//! ## Writing Your First Pallet +//! > Be aware that you can read the entire source code backing this tutorial by clicking on the +//! > [`source`](./mod.rs.html) button at the top right of the page. //! //! You should have studied the following modules as a prelude to this guide: //! @@ -33,16 +29,28 @@ //! - [`crate::reference_docs::trait_based_programming`] //! - [`crate::polkadot_sdk::frame_runtime`] //! +//! ## Topics Covered +//! +//! The following FRAME topics are covered in this guide: +//! +//! - [`pallet::storage`] +//! - [`pallet::call`] +//! - [`pallet::event`] +//! - [`pallet::error`] +//! - Basics of testing a pallet +//! - [Constructing a runtime](frame::runtime::prelude::construct_runtime) +//! //! ### Shell Pallet //! //! Consider the following as a "shell pallet". We continue building the rest of this pallet based //! on this template. //! -//! [`pallet::config`](frame::pallet_macros::config) and -//! [`pallet::pallet`](frame::pallet_macros::pallet) are both mandatory parts of any pallet. Refer -//! to the documentation of each to get an overview of what they do. +//! [`pallet::config`] and [`pallet::pallet`] are both mandatory parts of any pallet. Refer to the +//! documentation of each to get an overview of what they do. #![doc = docify::embed!("./src/guides/your_first_pallet/mod.rs", shell_pallet)] //! +//! All of the code that follows in this guide should live inside of the `mod pallet`. +//! //! ### Storage //! //! First, we will need to create two onchain storage declarations. @@ -55,15 +63,14 @@ //! > generic bounded type in the `Config` trait, and then specify it in the implementation. #![doc = docify::embed!("./src/guides/your_first_pallet/mod.rs", Balance)] //! -//! The definition of these two storage items, based on [`frame::pallet_macros::storage`] details, -//! is as follows: +//! The definition of these two storage items, based on [`pallet::storage`] details, is as follows: #![doc = docify::embed!("./src/guides/your_first_pallet/mod.rs", TotalIssuance)] #![doc = docify::embed!("./src/guides/your_first_pallet/mod.rs", Balances)] //! //! ### Dispatchables //! -//! Next, we will define the dispatchable functions. As per [`frame::pallet_macros::call`], these -//! will be defined as normal `fn`s attached to `struct Pallet`. +//! Next, we will define the dispatchable functions. As per [`pallet::call`], these will be defined +//! as normal `fn`s attached to `struct Pallet`. #![doc = docify::embed!("./src/guides/your_first_pallet/mod.rs", impl_pallet)] //! //! The logic of the functions is self-explanatory. Instead, we will focus on the FRAME-related @@ -79,7 +86,6 @@ //! was signed by `who`. #![doc = docify::embed!("../../substrate/frame/system/src/lib.rs", ensure_signed)] //! -//! //! - Where does `mutate`, `get` and `insert` and other storage APIs come from? All of them are //! explained in the corresponding `type`, for example, for `Balances::::insert`, you can look //! into [`frame::prelude::StorageMap::insert`]. @@ -95,8 +101,7 @@ //! //! - Why are all `get` and `mutate` functions returning an `Option`? This is the default behavior //! of FRAME storage APIs. You can learn more about how to override this by looking into -//! [`frame::pallet_macros::storage`], and -//! [`frame::prelude::ValueQuery`]/[`frame::prelude::OptionQuery`] +//! [`pallet::storage`], and [`frame::prelude::ValueQuery`]/[`frame::prelude::OptionQuery`] //! //! ### Improving Errors //! @@ -116,6 +121,25 @@ //! //! ### Your First (Test) Runtime //! +//! The typical testing code of a pallet lives in a module that imports some preludes useful for +//! testing, similar to: +//! +//! ``` +//! pub mod pallet { +//! // snip -- actually pallet code. +//! } +//! +//! #[cfg(test)] +//! mod tests { +//! // bring in the testing prelude of frame +//! use frame::testing_prelude::*; +//! // bring in all pallet items +//! use super::pallet::*; +//! +//! // snip -- rest of the testing code. +//! } +//! ``` +//! //! Next, we create a "test runtime" in order to test our pallet. Recall from //! [`crate::polkadot_sdk::frame_runtime`] that a runtime is a collection of pallets, expressed //! through [`frame::runtime::prelude::construct_runtime`]. All runtimes also have to include @@ -166,7 +190,6 @@ //! As noted above, the `T::AccountId` is now `u64`. Moreover, `Runtime` is replacing ``. //! This is why for example you see `Balances::::get(..)`. Finally, notice that the //! dispatchables are simply functions that can be called on top of the `Pallet` struct. -// TODO: hard to explain exactly `RuntimeOrigin::signed(ALICE)` at this point. //! //! Congratulations! You have written your first pallet and tested it! Next, we learn a few optional //! steps to improve our pallet. @@ -236,8 +259,7 @@ //! by one character. FRAME errors are exactly a solution to maintain readability, whilst fixing //! the drawbacks mentioned. In short, we use an enum to represent different variants of our //! error. These variants are then mapped in an efficient way (using only `u8` indices) to -//! [`sp_runtime::DispatchError::Module`]. Read more about this in -//! [`frame::pallet_macros::error`]. +//! [`sp_runtime::DispatchError::Module`]. Read more about this in [`pallet::error`]. //! //! - **Event**: Events are akin to the return type of dispatchables. They are mostly data blobs //! emitted by the runtime to let outside world know what is happening inside the pallet. Since @@ -246,20 +268,16 @@ //! use passive tense for event names (eg. `SomethingHappened`). This allows other sub-systems or //! external parties (eg. a light-node, a DApp) to listen to particular events happening, without //! needing to re-execute the whole state transition function. -// TODO: both need to be improved a lot at the pallet-macro rust-doc level. Also my explanation -// of event is probably not the best. //! //! With the explanation out of the way, let's see how these components can be added. Both follow a -//! fairly familiar syntax: normal Rust enums, with extra -//! [`#[frame::event]`](frame::pallet_macros::event) and -//! [`#[frame::error]`](frame::pallet_macros::error) attributes attached. +//! fairly familiar syntax: normal Rust enums, with extra [`pallet::event`] and [`pallet::error`] +//! attributes attached. #![doc = docify::embed!("./src/guides/your_first_pallet/mod.rs", Event)] #![doc = docify::embed!("./src/guides/your_first_pallet/mod.rs", Error)] //! -//! One slightly custom part of this is the [`#[pallet::generate_deposit(pub(super) fn -//! deposit_event)]`](frame::pallet_macros::generate_deposit) part. Without going into too -//! much detail, in order for a pallet to emit events to the rest of the system, it needs to do two -//! things: +//! One slightly custom part of this is the [`pallet::generate_deposit`] part. Without going into +//! too much detail, in order for a pallet to emit events to the rest of the system, it needs to do +//! two things: //! //! 1. Declare a type in its `Config` that refers to the overarching event type of the runtime. In //! short, by doing this, the pallet is expressing an important bound: `type RuntimeEvent: @@ -268,8 +286,8 @@ //! store it where needed. //! //! 2. But, doing this conversion and storing is too much to expect each pallet to define. FRAME -//! provides a default way of storing events, and this is what -//! [`pallet::generate_deposit`](frame::pallet_macros::generate_deposit) is doing. +//! provides a default way of storing events, and this is what [`pallet::generate_deposit`] is +//! doing. #![doc = docify::embed!("./src/guides/your_first_pallet/mod.rs", config_v2)] //! //! > These `Runtime*` types are better explained in @@ -297,10 +315,17 @@ //! - [`crate::reference_docs::defensive_programming`]. //! - [`crate::reference_docs::frame_origin`]. //! - [`crate::reference_docs::frame_runtime_types`]. -//! - The pallet we wrote in this guide was using `dev_mode`, learn more in -//! [`frame::pallet_macros::config`]. +//! - The pallet we wrote in this guide was using `dev_mode`, learn more in [`pallet::config`]. //! - Learn more about the individual pallet items/macros, such as event and errors and call, in //! [`frame::pallet_macros`]. +//! +//! [`pallet::storage`]: ../../../frame_support/pallet_macros/attr.config.html +//! [`pallet::call`]: ../../../frame_support/pallet_macros/attr.call.html +//! [`pallet::event`]: ../../../frame_support/pallet_macros/attr.event.html +//! [`pallet::error`]: ../../../frame_support/pallet_macros/attr.error.html +//! [`pallet::pallet`]: ../../../frame_support/pallet_macros/attr.pallet.html +//! [`pallet::config`]: ../../../frame_support/pallet_macros/attr.config.html +//! [`pallet::generate_deposit`]: ../../../frame_support/pallet_macros/attr.generate_deposit.html #[docify::export] #[frame::pallet(dev_mode)] @@ -418,16 +443,22 @@ pub mod pallet { #[cfg(any(test, doc))] pub(crate) mod tests { use crate::guides::your_first_pallet::pallet::*; + + #[docify::export(testing_prelude)] use frame::testing_prelude::*; - const ALICE: u64 = 1; - const BOB: u64 = 2; - const CHARLIE: u64 = 3; + + pub(crate) const ALICE: u64 = 1; + pub(crate) const BOB: u64 = 2; + pub(crate) const CHARLIE: u64 = 3; #[docify::export] + // This runtime is only used for testing, so it should be somewhere like `#[cfg(test)] mod + // tests { .. }` mod runtime { use super::*; // we need to reference our `mod pallet` as an identifier to pass to // `construct_runtime`. + // YOU HAVE TO CHANGE THIS LINE BASED ON YOUR TEMPLATE use crate::guides::your_first_pallet::pallet as pallet_currency; construct_runtime!( @@ -595,7 +626,7 @@ pub mod pallet { #[test] fn transfer_works() { StateBuilder::default().build_and_execute(|| { - // given the the initial state, when: + // given the initial state, when: assert_ok!(Pallet::::transfer(RuntimeOrigin::signed(ALICE), BOB, 50)); // then: @@ -617,7 +648,7 @@ pub mod pallet { #[test] fn transfer_from_non_existent_fails() { StateBuilder::default().build_and_execute(|| { - // given the the initial state, when: + // given the initial state, when: assert_err!( Pallet::::transfer(RuntimeOrigin::signed(CHARLIE), ALICE, 10), "NonExistentAccount" @@ -738,7 +769,7 @@ pub mod pallet_v2 { // the final assertion. System::set_block_number(ALICE); - // given the the initial state, when: + // given the initial state, when: assert_ok!(Pallet::::transfer(RuntimeOrigin::signed(ALICE), BOB, 50)); // then: diff --git a/docs/sdk/src/guides/your_first_runtime.rs b/docs/sdk/src/guides/your_first_runtime.rs index 3e02ef1b1b28eedb7cea0ce38fb8b372a0caaf60..c58abc1120c13f5d9d724f7dd78464380f8840bf 100644 --- a/docs/sdk/src/guides/your_first_runtime.rs +++ b/docs/sdk/src/guides/your_first_runtime.rs @@ -1 +1,3 @@ //! # Your first Runtime +//! +//! ๐Ÿšง diff --git a/docs/sdk/src/polkadot_sdk/templates.rs b/docs/sdk/src/polkadot_sdk/templates.rs index 4bf0e839c798fc55dd1fa0696c6bfe8411c32bc8..e87eb9c2bc8abe72538f4bc88a8f6348e1e90343 100644 --- a/docs/sdk/src/polkadot_sdk/templates.rs +++ b/docs/sdk/src/polkadot_sdk/templates.rs @@ -1,19 +1,33 @@ //! # Templates //! -//! ### Internal +//! This document enumerates a non-exhaustive list of templates that one can use to get started with +//! polkadot-sdk. //! -//! The following templates are maintained as a part of the `polkadot-sdk` repository: +//! > Know more tools/templates that are not listed here? please contribute them by opening a PR. //! -//! - classic [`substrate-node-template`]: is a white-labeled substrate-based blockchain with a -//! moderate amount of features. It can act as a great starting point for those who want to learn -//! Substrate/FRAME and want to have a template that is already doing something. -//! - [`substrate-minimal-template`]: Same as the above, but it contains the least amount of code in -//! both the node and runtime. It is a great starting point for those who want to deeply learn -//! Substrate and FRAME. -//! - classic [`cumulus-parachain-template`], which is the de-facto parachain template shipped with -//! Cumulus. It is the parachain-enabled version of [`substrate-node-template`]. +//! ## Internal //! -//! ### External Templates +//! The following [templates](https://github.com/paritytech/polkadot-sdk/blob/master/templates) are +//! maintained as a part of the `polkadot-sdk` repository: +//! +//! - `minimal_template_node`/[`minimal_template_runtime`]: A minimal template that contains the +//! least amount of features to be a functioning blockchain. Suitable for learning, development +//! and testing. This template is not meant to be used in production. +//! - `solochain_template_node`/[`solochain_template_runtime`]: Formerly known as +//! "substrate-node-template", is a white-labeled substrate-based blockchain (aka. solochain) that +//! contains moderate features, such as a basic consensus engine and some FRAME pallets. This +//! template can act as a good starting point for those who want to launch a solochain. +//! - `parachain_template_node`/[`parachain_template_runtime`]: A parachain template ready to be +//! connected to a test relay-chain. +//! +//! These templates are always kept up to date, and are mirrored to external repositories for easy +//! forking: +//! +//! - +//! - +//! - +//! +//! ## External Templates //! //! Noteworthy templates outside of this repository. //! @@ -22,23 +36,17 @@ //! - [`frontier-parachain-template`](https://github.com/paritytech/frontier-parachain-template): A //! parachain template for launching EVM-compatible parachains. //! -//! [`minimal-template`]: https://github.com/paritytech/polkadot-sdk/blob/master/templates/minimal/ -//! [`parachain-template`]: https://github.com/paritytech/polkadot-sdk/blob/master/templates/parachain/ - -// TODO: in general, we need to make a deliberate choice here of moving a few key templates to this -// repo (nothing stays in `substrate-developer-hub`) and the everything else should be community -// maintained. https://github.com/paritytech/polkadot-sdk-docs/issues/67 - -// TODO: we should rename `substrate-node-template` to `substrate-basic-template`, -// `substrate-blockchain-template`. `node` is confusing in the name. -// `substrate-blockchain-template` and `cumulus-parachain-template` go well together ๐Ÿค. https://github.com/paritytech/polkadot-sdk-docs/issues/67 - -// NOTE: a super important detail that I am looking forward to here is -// and -// . Meaning that I would not spend time on -// teaching someone too much detail about the ugly thing we call "node" nowadays. In the future, I -// am sure we will either have a better "node-builder" code that can actually be tested, or an -// "omni-node" that can run (almost) any wasm file. We should already build tutorials in this -// direction IMO. This also affects all the templates. If we have a good neat runtime file, which we -// are moving toward, and a good node-builder, we don't need all of these damn templates. These -// templates are only there because the boilerplate is super horrible atm. +//! ## OpenZeppelin +//! +//! In June 2023, OpenZeppelin was awarded a grant from the [Polkadot +//! treasury](https://polkadot.polkassembly.io/treasury/406) for building a number of Polkadot-sdk +//! based templates. These templates are expected to be a great starting point for developers. +//! +//! - +//! +//! ## POP-CLI +//! +//! Is a CLI tool capable of scaffolding a new polkadot-sdk-based project, possibly removing the +//! need for templates. +//! +//! - diff --git a/docs/sdk/src/reference_docs/blockchain_scalibility.rs b/docs/sdk/src/reference_docs/blockchain_scalibility.rs deleted file mode 100644 index e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 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 c6dd3af9d90be8039cf2aabbdf04964ff5dc886d..9cf921a492a515ee424f0e47674a9aef2414b034 100644 --- a/docs/sdk/src/reference_docs/chain_spec_runtime/Cargo.toml +++ b/docs/sdk/src/reference_docs/chain_spec_runtime/Cargo.toml @@ -10,44 +10,44 @@ edition.workspace = true publish = false [dependencies] -docify = "0.2.8" -parity-scale-codec = { version = "3.6.12", default-features = false } -scale-info = { version = "2.6.0", default-features = false } -serde = { workspace = true, default-features = false } +docify = { workspace = true } +codec = { workspace = true } +scale-info = { workspace = true } +serde = { workspace = true } serde_json = { workspace = true } # this is a frame-based runtime, thus importing `frame` with runtime feature enabled. -frame = { package = "polkadot-sdk-frame", path = "../../../../../substrate/frame", default-features = false, features = [ +frame = { features = [ "experimental", "runtime", -] } +], workspace = true } # pallets that we want to use -pallet-balances = { path = "../../../../../substrate/frame/balances", default-features = false } -pallet-sudo = { path = "../../../../../substrate/frame/sudo", default-features = false } -pallet-timestamp = { path = "../../../../../substrate/frame/timestamp", default-features = false } -pallet-transaction-payment = { path = "../../../../../substrate/frame/transaction-payment", default-features = false } -pallet-transaction-payment-rpc-runtime-api = { path = "../../../../../substrate/frame/transaction-payment/rpc/runtime-api", default-features = false } +pallet-balances = { workspace = true } +pallet-sudo = { workspace = true } +pallet-timestamp = { workspace = true } +pallet-transaction-payment = { workspace = true } +pallet-transaction-payment-rpc-runtime-api = { workspace = true } # genesis builder that allows us to interact with runtime genesis config -sp-genesis-builder = { path = "../../../../../substrate/primitives/genesis-builder", default-features = false } -sp-runtime = { path = "../../../../../substrate/primitives/runtime", default-features = false, features = ["serde"] } -sp-core = { path = "../../../../../substrate/primitives/core", default-features = false } -sp-std = { path = "../../../../../substrate/primitives/std", default-features = false } -sp-keyring = { path = "../../../../../substrate/primitives/keyring", default-features = false } -sp-application-crypto = { path = "../../../../../substrate/primitives/application-crypto", default-features = false, features = ["serde"] } +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 } [build-dependencies] -substrate-wasm-builder = { path = "../../../../../substrate/utils/wasm-builder", optional = true } +substrate-wasm-builder = { optional = true, workspace = true, default-features = true } [dev-dependencies] -chain-spec-builder = { package = "staging-chain-spec-builder", path = "../../../../../substrate/bin/utils/chain-spec-builder" } -sc-chain-spec = { path = "../../../../../substrate/client/chain-spec" } +chain-spec-builder = { workspace = true, default-features = true } +sc-chain-spec = { workspace = true, default-features = true } [features] default = ["std"] std = [ - "parity-scale-codec/std", + "codec/std", "scale-info/std", "frame/std", diff --git a/docs/sdk/src/reference_docs/consensus_swapping.rs b/docs/sdk/src/reference_docs/consensus_swapping.rs deleted file mode 100644 index e639761ee97b42fa68e1ba77250d490e28277e24..0000000000000000000000000000000000000000 --- a/docs/sdk/src/reference_docs/consensus_swapping.rs +++ /dev/null @@ -1,6 +0,0 @@ -//! Consensus Swapping -//! -//! Notes: -//! -//! - The typical workshop done by Joshy in some places where he swaps out the consensus to be PoW. -//! - This could also be a tutorial rather than a ref doc, depending on the size. diff --git a/docs/sdk/src/reference_docs/custom_host_functions.rs b/docs/sdk/src/reference_docs/custom_host_functions.rs new file mode 100644 index 0000000000000000000000000000000000000000..719b208a2bff7ed6fb1929cbdccae7dddda2ab00 --- /dev/null +++ b/docs/sdk/src/reference_docs/custom_host_functions.rs @@ -0,0 +1,27 @@ +//! # Custom Host Functions +//! +//! Host functions are functions that the wasm instance can use to communicate with the node. Learn +//! more about this in [`crate::reference_docs::wasm_meta_protocol`]. +//! +//! ## Finding Host Functions +//! +//! To declare a set of functions as host functions, you need to use the `#[runtime_interface]` +//! ([`sp_runtime_interface`]) attribute macro. The most notable set of host functions are those +//! that allow the runtime to access the chain state, namely [`sp_io::storage`]. Some other notable +//! host functions are also defined in [`sp_io`]. +//! +//! ## Adding New Host Functions +//! +//! > Adding a new host function is a big commitment and should be done with care. Namely, the nodes +//! > in the network need to support all host functions forever in order to be able to sync +//! > historical blocks. +//! +//! Adding host functions is only possible when you are using a node-template, so that you have +//! access to the boilerplate of building your node. +//! +//! A group of host functions can always be grouped to gether as a tuple: +#![doc = docify::embed!("../../substrate/primitives/io/src/lib.rs", SubstrateHostFunctions)] +//! +//! The host functions are attached to the node side's [`sc_executor::WasmExecutor`]. For example in +//! the minimal template, the setup looks as follows: +#![doc = docify::embed!("../../templates/minimal/node/src/service.rs", FullClient)] diff --git a/docs/sdk/src/reference_docs/fee_less_runtime.rs b/docs/sdk/src/reference_docs/fee_less_runtime.rs index 1213c26282537fdee2d04ebd452289f0e6bc759f..9146b30ec5774355ce91dd02a5bb010dcf6fbada 100644 --- a/docs/sdk/src/reference_docs/fee_less_runtime.rs +++ b/docs/sdk/src/reference_docs/fee_less_runtime.rs @@ -1,5 +1,6 @@ //! # Fee-Less Runtime //! +//! ๐Ÿšง Work In Progress ๐Ÿšง //! //! Notes: //! diff --git a/docs/sdk/src/reference_docs/frame_logging.rs b/docs/sdk/src/reference_docs/frame_logging.rs new file mode 100644 index 0000000000000000000000000000000000000000..301fa7ef83f827c3115a6a30bb8d1ad35b5bfd83 --- /dev/null +++ b/docs/sdk/src/reference_docs/frame_logging.rs @@ -0,0 +1,116 @@ +//! # FRAME Logging +//! +//! This reference docs briefly explores how to do logging and printing runtimes, mainly +//! FRAME-based. +//! +//! ## Using `println!` +//! +//! To recap, as with standard Rust, you can use `println!` _in your tests_, but it will only print +//! out if executed with `--nocapture`, or if the test panics. +//! +//! ``` +//! fn it_print() { +//! println!("Hello, world!"); +//! } +//! ``` +//! +//! within the pallet, if you want to use the standard `println!`, it needs to be wrapped in +//! [`sp_std::if_std`]. Of course, this means that this print code is only available to you in the +//! `std` compiler flag, and never present in a wasm build. +//! +//! ``` +//! // somewhere in your pallet. This is not a real pallet code. +//! mod pallet { +//! struct Pallet; +//! impl Pallet { +//! fn print() { +//! sp_std::if_std! { +//! println!("Hello, world!"); +//! } +//! } +//! } +//! } +//! ``` +//! +//! ## Using `log` +//! +//! First, ensure you are familiar with the `log` crate. In short, each log statement has: +//! +//! 1. `log-level`, signifying how important it is +//! 2. `log-target`, signifying to which component it belongs. +//! +//! Add log statements to your pallet as such: +//! +//! You can add the log crate to the `Cargo.toml` of the pallet. +//! +//! ```text +//! #[dependencies] +//! log = { version = "x.y.z", default-features = false } +//! +//! #[features] +//! std = [ +//! // snip -- other pallets +//! "log/std" +//! ] +//! ``` +//! +//! More conveniently, the `frame` umbrella crate re-exports the log crate as [`frame::log`]. +//! +//! Then, the pallet can use this crate to emit log statements. In this statement, we use the info +//! level, and the target is `pallet-example`. +//! +//! ``` +//! mod pallet { +//! struct Pallet; +//! +//! impl Pallet { +//! fn logs() { +//! frame::log::info!(target: "pallet-example", "Hello, world!"); +//! } +//! } +//! } +//! ``` +//! +//! This will in itself just emit the log messages, **but unless if captured by a logger, they will +//! not go anywhere**. [`sp_api`] provides a handy function to enable the runtime logging: +//! +//! ``` +//! // in your test +//! fn it_also_prints() { +//! sp_api::init_runtime_logger(); +//! // call into your pallet, and now it will print `log` statements. +//! } +//! ``` +//! +//! Alternatively, you can use [`sp_tracing::try_init_simple`]. +//! +//! `info`, `error` and `warn` logs are printed by default, but if you want lower level logs to also +//! be printed, you must to add the following compiler flag: +//! +//! ```text +//! RUST_LOG=pallet-example=trace cargo test +//! ``` +//! +//! ## Enabling Logs in Production +//! +//! All logs from the runtime are emitted by default, but there is a feature flag in [`sp_api`], +//! called `disable-logging`, that can be used to disable all logs in the runtime. This is useful +//! for production chains to reduce the size and overhead of the wasm runtime. +#![doc = docify::embed!("../../substrate/primitives/api/src/lib.rs", init_runtime_logger)] +//! +//! Similar to the above, the proper `RUST_LOG` must also be passed to your compiler flag when +//! compiling the runtime. +//! +//! ## Log Target Prefixing +//! +//! Many [`crate::polkadot_sdk::frame_runtime`] pallets emit logs with log target `runtime::`, for example `runtime::system`. This then allows one to run a node with a wasm blob +//! compiled with `LOG_TARGET=runtime=debug`, which enables the log target of all pallets who's log +//! target starts with `runtime`. +//! +//! ## Low Level Primitives +//! +//! Under the hood, logging is another instance of host functions under the hood (as defined in +//! [`crate::reference_docs::wasm_meta_protocol`]). The runtime uses a set of host functions under +//! [`sp_io::logging`] and [`sp_io::misc`] to emit all logs and prints. You typically do not need to +//! use these APIs directly. diff --git a/docs/sdk/src/reference_docs/frame_offchain_workers.rs b/docs/sdk/src/reference_docs/frame_offchain_workers.rs index 7999707e5ee018c4bb7634e7a506ff8fee8fa8ac..1ec9212e2306613b72ec4c6f433a68c92f5bb0d5 100644 --- a/docs/sdk/src/reference_docs/frame_offchain_workers.rs +++ b/docs/sdk/src/reference_docs/frame_offchain_workers.rs @@ -58,7 +58,6 @@ //! [`frame::pallet_macros::hooks`]. //! //! ``` -//! //! #[frame::pallet] //! pub mod pallet { //! use frame::prelude::*; diff --git a/docs/sdk/src/reference_docs/frame_system_accounts.rs b/docs/sdk/src/reference_docs/frame_system_accounts.rs index ae9d2c9e0cb3ca7a694d9e5330363c05f6f78cb0..523fe704308497d3116d36cfca086a617b3a9d3b 100644 --- a/docs/sdk/src/reference_docs/frame_system_accounts.rs +++ b/docs/sdk/src/reference_docs/frame_system_accounts.rs @@ -1,5 +1,7 @@ //! # FRAME Accounts //! +//! //! ๐Ÿšง Work In Progress ๐Ÿšง +//! //! How `frame_system` handles accountIds. Nonce. Consumers and Providers, reference counting. // - poorly understood topics, needs one great article to rul them all. diff --git a/docs/sdk/src/reference_docs/light_nodes.rs b/docs/sdk/src/reference_docs/light_nodes.rs deleted file mode 100644 index d6670bf03ab1a8e36ef1d8b80717d1b3833daff5..0000000000000000000000000000000000000000 --- a/docs/sdk/src/reference_docs/light_nodes.rs +++ /dev/null @@ -1,7 +0,0 @@ -//! # Light Clients -//! -//! -//! Notes: should contain only high level information about light clients, then link to how to set -//! it up in PAPI and SubXT -//! -//! diff --git a/docs/sdk/src/reference_docs/metadata.rs b/docs/sdk/src/reference_docs/metadata.rs index 702c1c30fd9cf2d09082b39fecf880065ebd5375..96f92ac0c412ba252092170e0788680300385901 100644 --- a/docs/sdk/src/reference_docs/metadata.rs +++ b/docs/sdk/src/reference_docs/metadata.rs @@ -1 +1,25 @@ //! # Metadata +//! +//! The existence of metadata in polkadot-sdk goes back to the (forkless) upgrade-ability of all +//! Substrate-based blockchains, which is achieved through +//! [`crate::reference_docs::wasm_meta_protocol`]. You can learn more about the details of how to +//! deal with these upgrades in [`crate::reference_docs::frame_runtime_upgrades_and_migrations`]. +//! +//! Another consequence of upgrade-ability is that as a UI, wallet, or generally an offchain entity, +//! it is hard to know the types internal to the runtime, specifically in light of the fact that +//! they can change at any point in time. +//! +//! This is why all Substrate-based runtimes must expose a [`sp_api::Metadata`] api, which mandates +//! the runtime to return a description of itself. The return type of this api is `Vec`, meaning +//! that it is up to the runtime developer to decide on the format of this. +//! +//! All [`crate::polkadot_sdk::frame_runtime`] based runtimes expose a specific metadata language, +//! maintained in which is adopted in the Polkadot +//! ecosystem. +//! +//! ## Metadata Explorers: +//! +//! A few noteworthy tools that inspect the (FRAME-based) metadata of a chain: +//! +//! +//! diff --git a/docs/sdk/src/reference_docs/mod.rs b/docs/sdk/src/reference_docs/mod.rs index 8e0431c48b6f69922fa37a38661175c621c774e4..688339b7e3806c0ed86db5caabc253b0d45e7c41 100644 --- a/docs/sdk/src/reference_docs/mod.rs +++ b/docs/sdk/src/reference_docs/mod.rs @@ -40,7 +40,6 @@ pub mod runtime_vs_smart_contract; pub mod extrinsic_encoding; /// Learn about the signed extensions that form a part of extrinsics. -// TODO: @jsdw https://github.com/paritytech/polkadot-sdk-docs/issues/42 pub mod signed_extensions; /// Learn about *Origins*, a topic in FRAME that enables complex account abstractions to be built. @@ -59,9 +58,11 @@ pub mod fee_less_runtime; /// Learn about metadata, the main means through which an upgradeable runtime communicates its /// properties to the outside world. -// TODO: @jsdw https://github.com/paritytech/polkadot-sdk-docs/issues/47 pub mod metadata; +/// Learn about how to add custom host functions to the node. +pub mod custom_host_functions; + /// Learn about how frame-system handles `account-ids`, nonces, consumers and providers. pub mod frame_system_accounts; @@ -78,26 +79,12 @@ pub mod frame_tokens; /// Learn about chain specification file and the genesis state of the blockchain. pub mod chain_spec_genesis; -/// Learn about all the memory limitations of the WASM runtime when it comes to memory usage. -// TODO: @kianenigma https://github.com/paritytech/polkadot-sdk-docs/issues/52 -pub mod wasm_memory; - /// Learn about Substrate's CLI, and how it can be extended. -// TODO: @kianenigma https://github.com/paritytech/polkadot-sdk-docs/issues/53 pub mod cli; -/// Learn about Substrate's consensus algorithms, and how you can switch between two. -// TODO: @JoshOrndorff @kianenigma https://github.com/paritytech/polkadot-sdk-docs/issues/54 -pub mod consensus_swapping; - /// Learn about Runtime Upgrades and best practices for writing Migrations. pub mod frame_runtime_upgrades_and_migrations; -/// Learn about light nodes, how they function, and how Substrate-based chains come -/// light-node-first out of the box. -// TODO: @jsdw @josepot https://github.com/paritytech/polkadot-sdk-docs/issues/68 -pub mod light_nodes; - /// Learn about the offchain workers, how they function, and how to use them, as provided by the /// [`frame`] APIs. pub mod frame_offchain_workers; @@ -106,6 +93,9 @@ pub mod frame_offchain_workers; /// together. pub mod frame_pallet_coupling; +/// Learn about how to do logging in FRAME-based runtimes. +pub mod frame_logging; + /// Learn about the Polkadot Umbrella crate that re-exports all other crates. pub mod umbrella_crate; diff --git a/docs/sdk/src/reference_docs/umbrella_crate.rs b/docs/sdk/src/reference_docs/umbrella_crate.rs index 9751b0ad5ad6d94a20e027e902ac055fa9e49181..0b3445cfc4bc0ce27b6dcb144618dd7001e6f20a 100644 --- a/docs/sdk/src/reference_docs/umbrella_crate.rs +++ b/docs/sdk/src/reference_docs/umbrella_crate.rs @@ -28,8 +28,9 @@ //! `node` feature. For docs.rs the manifest contains specific configuration to make it show up //! all re-exports. //! -//! There is a specific `zepter` check in place to ensure that the features of the umbrella are -//! correctly configured. This check is run in CI and locally when running `zepter`. +//! There is a specific [`zepter`](https://github.com/ggwpez/zepter) check in place to ensure that +//! the features of the umbrella are correctly configured. This check is run in CI and locally when +//! running `zepter`. //! //! ## Generation //! diff --git a/docs/sdk/src/reference_docs/wasm_memory.rs b/docs/sdk/src/reference_docs/wasm_memory.rs deleted file mode 100644 index 4f4cda31094e40e8f308dbb06de4ab0ecd828777..0000000000000000000000000000000000000000 --- a/docs/sdk/src/reference_docs/wasm_memory.rs +++ /dev/null @@ -1,7 +0,0 @@ -//! # WASM Memory Limitations. -//! -//! Notes: -//! -//! - Stack: Need to use `Box<_>` -//! - Heap: Substrate imposes a limit. PvF execution has its own limits -//! - Heap: There is also a maximum amount that a single allocation can have. diff --git a/docs/sdk/src/reference_docs/wasm_meta_protocol.rs b/docs/sdk/src/reference_docs/wasm_meta_protocol.rs index 37d1460f0e1a3737217ac0c80ec41de769db4c1a..0e91e65c55e36d99d6dfbe03e7cda3af09dad942 100644 --- a/docs/sdk/src/reference_docs/wasm_meta_protocol.rs +++ b/docs/sdk/src/reference_docs/wasm_meta_protocol.rs @@ -1,11 +1,13 @@ //! # WASM Meta Protocol //! //! All Substrate based chains adhere to a unique architectural design novel to the Polkadot -//! ecosystem. We refer to this design as the "WASM Meta Protocol". +//! ecosystem. We refer to this design as the "**WASM Meta Protocol**". //! //! Consider the fact that a traditional blockchain software is usually a monolithic artifact. -//! Upgrading any part of the system implies upgrading the entire system. This has historically led -//! to cumbersome forkful upgrades to be the status quo in the blockchain ecosystem. +//! **Upgrading any part of the system implies upgrading the entire system**. This has historically +//! led to cumbersome forkful upgrades to be the status quo in blockchain ecosystems. In other +//! words, the entire node software is the specification of the blockchain's [`state transition +//! function`](crate::reference_docs::blockchain_state_machines). //! //! Moreover, the idea of "storing code in the state" is explored in the context of smart contracts //! platforms, but has not been expanded further. @@ -15,17 +17,16 @@ //! that a smart contract platform stores the code of individual contracts in its state. As noted in //! [`crate::reference_docs::blockchain_state_machines`], this state transition function is called //! the **Runtime**, and WASM is chosen as the bytecode. The Runtime is stored under a special key -//! in the state (see -//! [`sp_core::storage::well_known_keys`](../../../sp_core/index.html)) and can be -//! updated as a part of the state transition function's execution, just like a user's account -//! balance can be updated. +//! in the state (see [`sp_core::storage::well_known_keys`]) and can be updated as a part of the +//! state transition function's execution, just like a user's account balance can be updated. //! //! > Note that while we drew an analogy between smart contracts and runtimes in the above, there //! > are fundamental differences between the two, explained in //! > [`crate::reference_docs::runtime_vs_smart_contract`]. //! -//! The rest of the system that is NOT the state transition function is called the **node**, and -//! is a normal binary that is compiled from Rust to different hardware targets. +//! The rest of the system that is NOT the state transition function is called the +//! [**Node**](crate::reference_docs::glossary#node), and is a normal binary that is compiled from +//! Rust to different hardware targets. //! //! This design enables all Substrate-based chains to be fork-less-ly upgradeable, because the //! Runtime can be updates on the fly, within the execution of a block, and the node is (for the @@ -47,15 +48,18 @@ #![doc = simple_mermaid::mermaid!("../../../mermaid/substrate_client_runtime.mmd")] //! //! A runtime must have a set of runtime APIs in order to have any meaningful blockchain -//! functionality, but it can also expose more APIs. See TODO as an example of how to add custom -//! runtime APIs to your FRAME-based runtime. +//! functionality, but it can also expose more APIs. See +//! [`crate::reference_docs::custom_runtime_api_rpc`] as an example of how to add custom runtime +//! APIs to your FRAME-based runtime. //! //! Similarly, for a runtime to be "compatible" with a node, the node must implement the full set of //! host functions that the runtime at any point in time requires. Given the fact that a runtime can //! evolve in time, and a blockchain node (typically) wishes to be capable of re-executing all the //! previous blocks, this means that a node must always maintain support for the old host functions. -//! This also implies that adding a new host function is a big commitment and should be done with -//! care. This is why, for example, adding a new host function to Polkadot always requires an RFC. +//! **This implies that adding a new host function is a big commitment and should be done with +//! care**. This is why, for example, adding a new host function to Polkadot always requires an RFC. +//! Learn how to add a new host function to your runtime in +//! [`crate::reference_docs::custom_host_functions`]. //! //! ## Node vs. Runtime //! @@ -90,11 +94,11 @@ //! //! In fact, [`sp_core::storage::well_known_keys`] are the only state keys that the node side is //! aware of. The rest of the state, including what logic the runtime has, what balance each user -//! has and such are all only comprehensible to the runtime. +//! has and such, are all only comprehensible to the runtime. #![doc = simple_mermaid::mermaid!("../../../mermaid/state.mmd")] //! //! In the above diagram, all of the state keys and values are opaque bytes to the node. The node -//! does not know what they mean, and it does not now what is the type of the corresponding value +//! does not know what they mean, and it does not know what is the type of the corresponding value //! (e.g. if it is a number of a vector). Contrary, the runtime knows both the meaning of their //! keys, and the type of the values. //! @@ -105,9 +109,50 @@ //! //! ## Native Runtime //! -//! TODO +//! Historically, the node software also kept a native copy of the runtime at the time of +//! compilation within it. This used to be called the "Native Runtime". The main purpose of the +//! native runtime used to be leveraging the faster execution time and better debugging +//! infrastructure of native code. However, neither of the two arguments strongly hold and the +//! native runtime is being fully removed from the node-sdk. //! +//! See: +//! +//! > Also, note that the flags [`sc_cli::ExecutionStrategy::Native`] is already a noop and all +//! > chains built with Substrate only use WASM execution. +//! +//! ### Runtime Versions +//! +//! An important detail of the native execution worth learning about is that the node software, +//! obviously, only uses the native runtime if it is the same code as with the wasm blob stored +//! onchain. Else, nodes who run the native runtime will come to a different state transition. How +//! do nodes determine if two runtimes are the same? Through the very important +//! [`sp_version::RuntimeVersion`]. All runtimes expose their version via a runtime api +//! ([`sp_api::Core::version`]) that returns this struct. The node software, or other applications, +//! inspect this struct to examine the identity of a runtime, and to determine if two runtimes are +//! the same. Namely, [`sp_version::RuntimeVersion::spec_version`] is the main key that implies two +//! runtimes are the same. +//! +//! Therefore, it is utmost important to make sure before any runtime upgrade, the spec version is +//! updated. //! //! ## Example: Block Execution. //! -//! TODO +//! As a final example to recap, let's look at how Substrate-based nodes execute blocks. Blocks are +//! received in the node side software as opaque blobs and in the networking layer. +//! +//! At some point, based on the consensus algorithm's rules, the node decides to import (aka. +//! *validate*) a block. +//! +//! * First, the node will then fetch the state of the parent hash of the block that wishes to be +//! imported. +//! * The runtime is fetched from this state, and placed into a WASM execution environment. +//! * The [`sp_api::Core::execute_block`] runtime API is called and the blocked is passed in as an +//! argument. +//! * The runtime will then execute the block, and update the state accordingly. Any state update is +//! issues via the [`sp_io::storage`] host functions. +//! * Both the runtime and node will check the state-root of the state after the block execution to +//! match the one claimed in the block header. +//! +//! > Example taken from [this +//! > lecture](https://polkadot-blockchain-academy.github.io/pba-book/substrate/wasm/page.html#example-2-block-import-9) +//! > of the Polkadot Blockchain Academy. diff --git a/master.wasm b/master.wasm new file mode 100644 index 0000000000000000000000000000000000000000..7ebb14371243afa4956a107374b27a4e686f0360 Binary files /dev/null and b/master.wasm differ diff --git a/modified.wasm b/modified.wasm new file mode 100644 index 0000000000000000000000000000000000000000..7ebb14371243afa4956a107374b27a4e686f0360 Binary files /dev/null and b/modified.wasm differ diff --git a/polkadot/Cargo.toml b/polkadot/Cargo.toml index 3aeec8d5961e35133233c35c38f57c2145c7f62c..512783de94806354f3d33cf32d73cca7b71faf16 100644 --- a/polkadot/Cargo.toml +++ b/polkadot/Cargo.toml @@ -25,32 +25,32 @@ default-run = "polkadot" workspace = true [dependencies] -color-eyre = { version = "0.6.1", default-features = false } -tikv-jemallocator = { version = "0.5.0", optional = true, features = ["unprefixed_malloc_on_supported_platforms"] } +color-eyre = { workspace = true } +tikv-jemallocator = { optional = true, features = ["unprefixed_malloc_on_supported_platforms"], workspace = true } # Crates in our workspace, defined as dependencies so we can pass them feature flags. -polkadot-cli = { path = "cli", features = ["rococo-native", "westend-native"] } -polkadot-node-core-pvf = { path = "node/core/pvf" } -polkadot-node-core-pvf-prepare-worker = { path = "node/core/pvf/prepare-worker" } -polkadot-overseer = { path = "node/overseer" } +polkadot-cli = { features = ["rococo-native", "westend-native"], workspace = true, default-features = true } +polkadot-node-core-pvf = { workspace = true, default-features = true } +polkadot-node-core-pvf-prepare-worker = { workspace = true, default-features = true } +polkadot-overseer = { workspace = true, default-features = true } # Needed for worker binaries. -polkadot-node-core-pvf-common = { path = "node/core/pvf/common" } -polkadot-node-core-pvf-execute-worker = { path = "node/core/pvf/execute-worker" } +polkadot-node-core-pvf-common = { workspace = true, default-features = true } +polkadot-node-core-pvf-execute-worker = { workspace = true, default-features = true } [target.'cfg(target_os = "linux")'.dependencies] tikv-jemallocator = { version = "0.5.0", features = ["unprefixed_malloc_on_supported_platforms"] } [dev-dependencies] -assert_cmd = "2.0.4" -nix = { version = "0.28.0", features = ["signal"] } -tempfile = "3.2.0" -tokio = "1.37" -substrate-rpc-client = { path = "../substrate/utils/frame/rpc/client" } -polkadot-core-primitives = { path = "core-primitives" } +assert_cmd = { workspace = true } +nix = { features = ["signal"], workspace = true } +tempfile = { workspace = true } +tokio = { workspace = true, default-features = true } +substrate-rpc-client = { workspace = true, default-features = true } +polkadot-core-primitives = { workspace = true, default-features = true } [build-dependencies] -substrate-build-script-utils = { path = "../substrate/utils/build-script-utils" } +substrate-build-script-utils = { workspace = true, default-features = true } [badges] maintenance = { status = "actively-developed" } diff --git a/polkadot/cli/Cargo.toml b/polkadot/cli/Cargo.toml index 1917dcd579c4c6a723acc7f5fcde086f6e8e5e53..9dcdb44ab64f54fd0c08e329679c721117facd14 100644 --- a/polkadot/cli/Cargo.toml +++ b/polkadot/cli/Cargo.toml @@ -18,33 +18,33 @@ wasm-opt = false crate-type = ["cdylib", "rlib"] [dependencies] -cfg-if = "1.0" -clap = { version = "4.5.3", features = ["derive"], optional = true } +cfg-if = { workspace = true } +clap = { features = ["derive"], optional = true, workspace = true } log = { workspace = true, default-features = true } thiserror = { workspace = true } -futures = "0.3.30" -pyroscope = { version = "0.5.3", optional = true } -pyroscope_pprofrs = { version = "0.2", optional = true } +futures = { workspace = true } +pyroscope = { optional = true, workspace = true } +pyroscope_pprofrs = { optional = true, workspace = true } -polkadot-service = { path = "../node/service", default-features = false, optional = true } +polkadot-service = { optional = true, workspace = true } -sp-core = { path = "../../substrate/primitives/core" } -sp-io = { path = "../../substrate/primitives/io" } -sp-keyring = { path = "../../substrate/primitives/keyring" } -sp-maybe-compressed-blob = { path = "../../substrate/primitives/maybe-compressed-blob" } -frame-benchmarking-cli = { path = "../../substrate/utils/frame/benchmarking-cli", optional = true } -sc-cli = { path = "../../substrate/client/cli", optional = true } -sc-service = { path = "../../substrate/client/service", optional = true } -polkadot-node-metrics = { path = "../node/metrics" } -polkadot-node-primitives = { path = "../node/primitives" } -sc-tracing = { path = "../../substrate/client/tracing", optional = true } -sc-sysinfo = { path = "../../substrate/client/sysinfo" } -sc-executor = { path = "../../substrate/client/executor" } -sc-storage-monitor = { path = "../../substrate/client/storage-monitor" } -sp-runtime = { path = "../../substrate/primitives/runtime" } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +sp-maybe-compressed-blob = { workspace = true, default-features = true } +frame-benchmarking-cli = { optional = true, workspace = true, default-features = true } +sc-cli = { optional = true, workspace = true, default-features = true } +sc-service = { optional = true, workspace = true, default-features = true } +polkadot-node-metrics = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +sc-tracing = { optional = true, workspace = true, default-features = true } +sc-sysinfo = { workspace = true, default-features = true } +sc-executor = { workspace = true, default-features = true } +sc-storage-monitor = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } [build-dependencies] -substrate-build-script-utils = { path = "../../substrate/utils/build-script-utils" } +substrate-build-script-utils = { workspace = true, default-features = true } [features] default = ["cli", "db", "full-node"] diff --git a/polkadot/core-primitives/Cargo.toml b/polkadot/core-primitives/Cargo.toml index 7d94196fa26dbbe95bfe543243c62099f1b4cb03..800434670f83bada72c95423081d89cd1ddeb46d 100644 --- a/polkadot/core-primitives/Cargo.toml +++ b/polkadot/core-primitives/Cargo.toml @@ -10,11 +10,11 @@ license.workspace = true workspace = true [dependencies] -sp-core = { path = "../../substrate/primitives/core", default-features = false } -sp-std = { path = "../../substrate/primitives/std", default-features = false } -sp-runtime = { path = "../../substrate/primitives/runtime", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +sp-core = { workspace = true } +sp-std = { workspace = true } +sp-runtime = { workspace = true } +scale-info = { features = ["derive"], workspace = true } +codec = { features = ["derive"], workspace = true } [features] default = ["std"] diff --git a/polkadot/erasure-coding/Cargo.toml b/polkadot/erasure-coding/Cargo.toml index 3c14fd95eee3b29988a87b68047f585c32c5bbc0..969742c5bb0aa792ea81b287f588b1315a48971d 100644 --- a/polkadot/erasure-coding/Cargo.toml +++ b/polkadot/erasure-coding/Cargo.toml @@ -10,17 +10,17 @@ license.workspace = true workspace = true [dependencies] -polkadot-primitives = { path = "../primitives" } -polkadot-node-primitives = { package = "polkadot-node-primitives", path = "../node/primitives" } -novelpoly = { package = "reed-solomon-novelpoly", version = "2.0.0" } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive", "std"] } -sp-core = { path = "../../substrate/primitives/core" } -sp-trie = { path = "../../substrate/primitives/trie" } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +novelpoly = { workspace = true } +codec = { features = ["derive", "std"], workspace = true } +sp-core = { workspace = true, default-features = true } +sp-trie = { workspace = true, default-features = true } thiserror = { workspace = true } [dev-dependencies] -quickcheck = { version = "1.0.3", default-features = false } -criterion = { version = "0.5.1", default-features = false, features = ["cargo_bench_support"] } +quickcheck = { workspace = true } +criterion = { features = ["cargo_bench_support"], workspace = true } [[bench]] name = "scaling_with_validators" diff --git a/polkadot/erasure-coding/fuzzer/Cargo.toml b/polkadot/erasure-coding/fuzzer/Cargo.toml index bd254f6d51651d27ac2a992285c80f9e1e272623..6f451f0319b23dee9ebbf08726dd4550f518e95d 100644 --- a/polkadot/erasure-coding/fuzzer/Cargo.toml +++ b/polkadot/erasure-coding/fuzzer/Cargo.toml @@ -10,10 +10,10 @@ publish = false workspace = true [dependencies] -polkadot-erasure-coding = { path = ".." } -honggfuzz = "0.5" -polkadot-primitives = { path = "../../primitives" } -polkadot-node-primitives = { path = "../../node/primitives" } +polkadot-erasure-coding = { workspace = true, default-features = true } +honggfuzz = { workspace = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } [[bin]] name = "reconstruct" diff --git a/polkadot/node/collation-generation/Cargo.toml b/polkadot/node/collation-generation/Cargo.toml index da5d10d7994970dde81b8530888c28c56dffb0b0..4b0a5f7248ab383884365105b164f27f2a090bf1 100644 --- a/polkadot/node/collation-generation/Cargo.toml +++ b/polkadot/node/collation-generation/Cargo.toml @@ -10,21 +10,21 @@ description = "Collator-side subsystem that handles incoming candidate submissio workspace = true [dependencies] -futures = "0.3.30" -gum = { package = "tracing-gum", path = "../gum" } -polkadot-erasure-coding = { path = "../../erasure-coding" } -polkadot-node-primitives = { path = "../primitives" } -polkadot-node-subsystem = { path = "../subsystem" } -polkadot-node-subsystem-util = { path = "../subsystem-util" } -polkadot-primitives = { path = "../../primitives" } -sp-core = { path = "../../../substrate/primitives/core" } -sp-maybe-compressed-blob = { path = "../../../substrate/primitives/maybe-compressed-blob" } +futures = { workspace = true } +gum = { workspace = true, default-features = true } +polkadot-erasure-coding = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-node-subsystem-util = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-maybe-compressed-blob = { workspace = true, default-features = true } thiserror = { workspace = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["bit-vec", "derive"] } +codec = { features = ["bit-vec", "derive"], workspace = true } [dev-dependencies] -polkadot-node-subsystem-test-helpers = { path = "../subsystem-test-helpers" } -polkadot-primitives-test-helpers = { path = "../../primitives/test-helpers" } -assert_matches = "1.4.0" -rstest = "0.18.2" -sp-keyring = { path = "../../../substrate/primitives/keyring" } +polkadot-node-subsystem-test-helpers = { workspace = true } +polkadot-primitives-test-helpers = { workspace = true } +assert_matches = { workspace = true } +rstest = { workspace = true } +sp-keyring = { workspace = true, default-features = true } diff --git a/polkadot/node/collation-generation/src/lib.rs b/polkadot/node/collation-generation/src/lib.rs index 0c2f8ee14a58033dce47947a4e923ea644213831..d38516a4ff713f32c98c4e616155c4cdffb8bfb8 100644 --- a/polkadot/node/collation-generation/src/lib.rs +++ b/polkadot/node/collation-generation/src/lib.rs @@ -147,11 +147,7 @@ impl CollationGenerationSubsystem { Ok(FromOrchestra::Communication { msg: CollationGenerationMessage::Reinitialize(config), }) => { - if self.config.is_none() { - gum::error!(target: LOG_TARGET, "no initial initialization"); - } else { - self.config = Some(Arc::new(config)); - } + self.config = Some(Arc::new(config)); false }, Ok(FromOrchestra::Communication { diff --git a/polkadot/node/core/approval-voting/Cargo.toml b/polkadot/node/core/approval-voting/Cargo.toml index 7da3d7ddd781485d673b29980b6787b99aea9da6..65985c0a5db930cf94922a6c8fde6e549021e7ef 100644 --- a/polkadot/node/core/approval-voting/Cargo.toml +++ b/polkadot/node/core/approval-voting/Cargo.toml @@ -10,51 +10,51 @@ description = "Approval Voting Subsystem of the Polkadot node" workspace = true [dependencies] -futures = "0.3.30" -futures-timer = "3.0.2" -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["bit-vec", "derive"] } -gum = { package = "tracing-gum", path = "../../gum" } -bitvec = { version = "1.0.0", default-features = false, features = ["alloc"] } -schnellru = "0.2.1" -merlin = "3.0" -schnorrkel = "0.11.4" -kvdb = "0.13.0" -derive_more = "0.99.17" +futures = { workspace = true } +futures-timer = { workspace = true } +codec = { features = ["bit-vec", "derive"], workspace = true } +gum = { workspace = true, default-features = true } +bitvec = { features = ["alloc"], workspace = true } +schnellru = { workspace = true } +merlin = { workspace = true, default-features = true } +schnorrkel = { workspace = true, default-features = true } +kvdb = { workspace = true } +derive_more = { workspace = true, default-features = true } thiserror = { workspace = true } -itertools = "0.11" +itertools = { workspace = true } -polkadot-node-subsystem = { path = "../../subsystem" } -polkadot-node-subsystem-util = { path = "../../subsystem-util" } -polkadot-overseer = { path = "../../overseer" } -polkadot-primitives = { path = "../../../primitives" } -polkadot-node-primitives = { path = "../../primitives" } -polkadot-node-jaeger = { path = "../../jaeger" } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-node-subsystem-util = { workspace = true, default-features = true } +polkadot-overseer = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-node-jaeger = { workspace = true, default-features = true } -sc-keystore = { path = "../../../../substrate/client/keystore", default-features = false } -sp-consensus = { path = "../../../../substrate/primitives/consensus/common", default-features = false } -sp-consensus-slots = { path = "../../../../substrate/primitives/consensus/slots", default-features = false } -sp-application-crypto = { path = "../../../../substrate/primitives/application-crypto", default-features = false, features = ["full_crypto"] } -sp-runtime = { path = "../../../../substrate/primitives/runtime", default-features = false } +sc-keystore = { workspace = true } +sp-consensus = { workspace = true } +sp-consensus-slots = { workspace = true } +sp-application-crypto = { features = ["full_crypto"], workspace = true } +sp-runtime = { workspace = true } # rand_core should match schnorrkel -rand_core = "0.6.2" -rand_chacha = { version = "0.3.1" } -rand = "0.8.5" +rand_core = { workspace = true } +rand_chacha = { workspace = true, default-features = true } +rand = { workspace = true, default-features = true } [dev-dependencies] -async-trait = "0.1.79" -parking_lot = "0.12.1" -sp-keyring = { path = "../../../../substrate/primitives/keyring" } -sp-keystore = { path = "../../../../substrate/primitives/keystore" } -sp-core = { path = "../../../../substrate/primitives/core" } -sp-consensus-babe = { path = "../../../../substrate/primitives/consensus/babe" } -polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } -assert_matches = "1.4.0" -kvdb-memorydb = "0.13.0" -polkadot-primitives-test-helpers = { path = "../../../primitives/test-helpers" } +async-trait = { workspace = true } +parking_lot = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-consensus-babe = { workspace = true, default-features = true } +polkadot-node-subsystem-test-helpers = { workspace = true } +assert_matches = { workspace = true } +kvdb-memorydb = { workspace = true } +polkadot-primitives-test-helpers = { workspace = true } log = { workspace = true, default-features = true } -env_logger = "0.11" +env_logger = { workspace = true } -polkadot-subsystem-bench = { path = "../../subsystem-bench" } +polkadot-subsystem-bench = { workspace = true } [[bench]] name = "approval-voting-regression-bench" diff --git a/polkadot/node/core/approval-voting/src/approval_checking.rs b/polkadot/node/core/approval-voting/src/approval_checking.rs index 8667d3639185fe14f9fb5a4c351b3fdd8d5d93a7..96eb25626de8c167255027e1320b079eb8f60e2a 100644 --- a/polkadot/node/core/approval-voting/src/approval_checking.rs +++ b/polkadot/node/core/approval-voting/src/approval_checking.rs @@ -23,6 +23,7 @@ use polkadot_primitives::ValidatorIndex; use crate::{ persisted_entries::{ApprovalEntry, CandidateEntry, TrancheEntry}, time::Tick, + MAX_RECORDED_NO_SHOW_VALIDATORS_PER_CANDIDATE, }; /// Result of counting the necessary tranches needed for approving a block. @@ -32,6 +33,7 @@ pub struct TranchesToApproveResult { pub required_tranches: RequiredTranches, /// The total number of no_shows at the moment we are doing the counting. pub total_observed_no_shows: usize, + pub no_show_validators: Vec, } /// The required tranches of assignments needed to determine whether a candidate is approved. @@ -188,6 +190,8 @@ struct State { /// The last tick at which a considered assignment was received. last_assignment_tick: Option, total_observed_no_shows: usize, + // The validator's index that are no-shows. + no_show_validators: Vec, } impl State { @@ -203,6 +207,7 @@ impl State { return TranchesToApproveResult { required_tranches: RequiredTranches::All, total_observed_no_shows: self.total_observed_no_shows, + no_show_validators: self.no_show_validators.clone(), } } @@ -217,6 +222,7 @@ impl State { last_assignment_tick: self.last_assignment_tick, }, total_observed_no_shows: self.total_observed_no_shows, + no_show_validators: self.no_show_validators.clone(), } } @@ -234,6 +240,7 @@ impl State { clock_drift, }, total_observed_no_shows: self.total_observed_no_shows, + no_show_validators: self.no_show_validators.clone(), } } else { TranchesToApproveResult { @@ -244,6 +251,7 @@ impl State { clock_drift, }, total_observed_no_shows: self.total_observed_no_shows, + no_show_validators: self.no_show_validators.clone(), } } } @@ -253,11 +261,12 @@ impl State { } fn advance( - &self, + mut self, new_assignments: usize, new_no_shows: usize, next_no_show: Option, last_assignment_tick: Option, + no_show_validators: Vec, ) -> State { let new_covered = if self.depth == 0 { new_assignments @@ -290,6 +299,17 @@ impl State { (self.depth, covering, uncovered) }; + // Make sure we don't store too many no-show validators, since this metric + // is valuable if there are just a few of them to identify the problematic + // validators. + // If there are a lot then we've got bigger problems and no need to make this + // array unnecessarily large. + if self.no_show_validators.len() + no_show_validators.len() < + MAX_RECORDED_NO_SHOW_VALIDATORS_PER_CANDIDATE + { + self.no_show_validators.extend(no_show_validators); + } + State { assignments, depth, @@ -299,6 +319,7 @@ impl State { next_no_show, last_assignment_tick, total_observed_no_shows: self.total_observed_no_shows + new_no_shows, + no_show_validators: self.no_show_validators, } } } @@ -354,8 +375,9 @@ fn count_no_shows( block_tick: Tick, no_show_duration: Tick, drifted_tick_now: Tick, -) -> (usize, Option) { +) -> (usize, Option, Vec) { let mut next_no_show = None; + let mut no_show_validators = Vec::new(); let no_shows = assignments .iter() .map(|(v_index, tick)| { @@ -379,12 +401,14 @@ fn count_no_shows( // the clock drift will be removed again to do the comparison above. next_no_show = super::min_prefer_some(next_no_show, Some(no_show_at + clock_drift)); } - + if is_no_show { + no_show_validators.push(*v_index); + } is_no_show }) .count(); - (no_shows, next_no_show) + (no_shows, next_no_show, no_show_validators) } /// Determine the amount of tranches of assignments needed to determine approval of a candidate. @@ -408,6 +432,7 @@ pub fn tranches_to_approve( next_no_show: None, last_assignment_tick: None, total_observed_no_shows: 0, + no_show_validators: Vec::new(), }; // The `ApprovalEntry` doesn't have any data for empty tranches. We still want to iterate over @@ -446,7 +471,7 @@ pub fn tranches_to_approve( // // While we count the no-shows, we also determine the next possible no-show we might // see within this tranche. - let (no_shows, next_no_show) = count_no_shows( + let (no_shows, next_no_show, no_show_validators) = count_no_shows( assignments, approvals, clock_drift, @@ -455,7 +480,7 @@ pub fn tranches_to_approve( drifted_tick_now, ); - let s = s.advance(n_assignments, no_shows, next_no_show, last_assignment_tick); + let s = s.advance(n_assignments, no_shows, next_no_show, last_assignment_tick, no_show_validators); let output = s.output(tranche, needed_approvals, n_validators, no_show_duration); *state = match output.required_tranches { @@ -1186,7 +1211,7 @@ mod tests { approvals.set(v_index, true); } - let (no_shows, next_no_show) = count_no_shows( + let (no_shows, next_no_show, _) = count_no_shows( &test.assignments, &approvals, test.clock_drift, @@ -1390,6 +1415,7 @@ mod tests { next_no_show: None, last_assignment_tick: None, total_observed_no_shows: 0, + no_show_validators: Default::default(), }; assert_eq!( @@ -1414,6 +1440,7 @@ mod tests { next_no_show: None, last_assignment_tick: None, total_observed_no_shows: 0, + no_show_validators: Default::default(), }; assert_eq!( diff --git a/polkadot/node/core/approval-voting/src/import.rs b/polkadot/node/core/approval-voting/src/import.rs index 59b6f91c0a82a44ebbea38e9bdf2d2ed210ec428..3ddef1e01c45b99ce797d64b78f2e2c88993471f 100644 --- a/polkadot/node/core/approval-voting/src/import.rs +++ b/polkadot/node/core/approval-voting/src/import.rs @@ -662,6 +662,7 @@ pub(crate) mod tests { per_block_assignments_gathering_times: LruMap::new(ByLength::new( MAX_BLOCKS_WITH_ASSIGNMENT_TIMESTAMPS, )), + no_show_stats: Default::default(), } } diff --git a/polkadot/node/core/approval-voting/src/lib.rs b/polkadot/node/core/approval-voting/src/lib.rs index eece6b15805c233c8a7e674bed79fe49a682de96..d4b6855a44d0e410bbec757cae25eb7bd4803acb 100644 --- a/polkadot/node/core/approval-voting/src/lib.rs +++ b/polkadot/node/core/approval-voting/src/lib.rs @@ -691,6 +691,7 @@ struct ApprovalStatus { tranche_now: DelayTranche, block_tick: Tick, last_no_shows: usize, + no_show_validators: Vec, } #[derive(Copy, Clone)] @@ -832,6 +833,51 @@ struct State { // tranches we trigger and why. per_block_assignments_gathering_times: LruMap>, + no_show_stats: NoShowStats, +} + +// Regularly dump the no-show stats at this block number frequency. +const NO_SHOW_DUMP_FREQUENCY: BlockNumber = 50; +// The maximum number of validators we record no-shows for, per candidate. +pub(crate) const MAX_RECORDED_NO_SHOW_VALIDATORS_PER_CANDIDATE: usize = 20; + +// No show stats per validator and per parachain. +// This is valuable information when we have to debug live network issue, because +// it gives information if things are going wrong only for some validators or just +// for some parachains. +#[derive(Debug, Clone, PartialEq, Eq, Default)] +struct NoShowStats { + per_validator_no_show: HashMap>, + per_parachain_no_show: HashMap, + last_dumped_block_number: BlockNumber, +} + +impl NoShowStats { + // Print the no-show stats if NO_SHOW_DUMP_FREQUENCY blocks have passed since the last + // print. + fn maybe_print(&mut self, current_block_number: BlockNumber) { + if self.last_dumped_block_number > current_block_number || + current_block_number - self.last_dumped_block_number < NO_SHOW_DUMP_FREQUENCY + { + return + } + if self.per_parachain_no_show.is_empty() && self.per_validator_no_show.is_empty() { + return + } + + gum::debug!( + target: LOG_TARGET, + "Validators with no_show {:?} and parachains with no_shows {:?} since {:}", + self.per_validator_no_show, + self.per_parachain_no_show, + self.last_dumped_block_number + ); + + self.last_dumped_block_number = current_block_number; + + self.per_validator_no_show.clear(); + self.per_parachain_no_show.clear(); + } } #[derive(Debug, Clone, PartialEq, Eq)] @@ -887,21 +933,25 @@ impl State { ); if let Some(approval_entry) = candidate_entry.approval_entry(&block_hash) { - let TranchesToApproveResult { required_tranches, total_observed_no_shows } = - approval_checking::tranches_to_approve( - approval_entry, - candidate_entry.approvals(), - tranche_now, - block_tick, - no_show_duration, - session_info.needed_approvals as _, - ); + let TranchesToApproveResult { + required_tranches, + total_observed_no_shows, + no_show_validators, + } = approval_checking::tranches_to_approve( + approval_entry, + candidate_entry.approvals(), + tranche_now, + block_tick, + no_show_duration, + session_info.needed_approvals as _, + ); let status = ApprovalStatus { required_tranches, block_tick, tranche_now, last_no_shows: total_observed_no_shows, + no_show_validators, }; Some((approval_entry, status)) @@ -1044,6 +1094,26 @@ impl State { }, } } + + fn record_no_shows( + &mut self, + session_index: SessionIndex, + para_id: u32, + no_show_validators: &Vec, + ) { + if !no_show_validators.is_empty() { + *self.no_show_stats.per_parachain_no_show.entry(para_id.into()).or_default() += 1; + } + for validator_index in no_show_validators { + *self + .no_show_stats + .per_validator_no_show + .entry(session_index) + .or_default() + .entry(*validator_index) + .or_default() += 1; + } + } } #[derive(Debug, Clone)] @@ -1096,6 +1166,7 @@ where per_block_assignments_gathering_times: LruMap::new(ByLength::new( MAX_BLOCKS_WITH_ASSIGNMENT_TIMESTAMPS, )), + no_show_stats: NoShowStats::default(), }; // `None` on start-up. Gets initialized/updated on leaf update @@ -1740,6 +1811,8 @@ async fn handle_from_overseer( "Imported new block.", ); + state.no_show_stats.maybe_print(block_batch.block_number); + for (c_hash, c_entry) in block_batch.imported_candidates { metrics.on_candidate_imported(); @@ -2904,7 +2977,8 @@ where let mut actions = Vec::new(); let block_hash = block_entry.block_hash(); let block_number = block_entry.block_number(); - + let session_index = block_entry.session(); + let para_id = candidate_entry.candidate_receipt().descriptor().para_id; let tick_now = state.clock.tick_now(); let (is_approved, status) = if let Some((approval_entry, status)) = state @@ -3000,7 +3074,9 @@ where if is_approved { approval_entry.mark_approved(); } - + if newly_approved { + state.record_no_shows(session_index, para_id.into(), &status.no_show_validators); + } actions.extend(schedule_wakeup_action( &approval_entry, block_hash, diff --git a/polkadot/node/core/approval-voting/src/tests.rs b/polkadot/node/core/approval-voting/src/tests.rs index 5cbae7f908fcb454dd8a4b6a6e63eb22563f17f5..64ae86bc013a5714868e2abcdd228f1f2b456af9 100644 --- a/polkadot/node/core/approval-voting/src/tests.rs +++ b/polkadot/node/core/approval-voting/src/tests.rs @@ -5068,6 +5068,7 @@ fn test_gathering_assignments_statements() { per_block_assignments_gathering_times: LruMap::new(ByLength::new( MAX_BLOCKS_WITH_ASSIGNMENT_TIMESTAMPS, )), + no_show_stats: NoShowStats::default(), }; for i in 0..200i32 { @@ -5162,6 +5163,7 @@ fn test_observe_assignment_gathering_status() { per_block_assignments_gathering_times: LruMap::new(ByLength::new( MAX_BLOCKS_WITH_ASSIGNMENT_TIMESTAMPS, )), + no_show_stats: NoShowStats::default(), }; let metrics_inner = MetricsInner { diff --git a/polkadot/node/core/av-store/Cargo.toml b/polkadot/node/core/av-store/Cargo.toml index 62f7ff0b61e64de81fa6b3c34987df042a865cbb..4274c8b576a3dc82cefbc22a7619bfe3206c181d 100644 --- a/polkadot/node/core/av-store/Cargo.toml +++ b/polkadot/node/core/av-store/Cargo.toml @@ -10,32 +10,32 @@ license.workspace = true workspace = true [dependencies] -futures = "0.3.30" -futures-timer = "3.0.2" -kvdb = "0.13.0" +futures = { workspace = true } +futures-timer = { workspace = true } +kvdb = { workspace = true } thiserror = { workspace = true } -gum = { package = "tracing-gum", path = "../../gum" } -bitvec = "1.0.0" +gum = { workspace = true, default-features = true } +bitvec = { workspace = true, default-features = true } -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } -polkadot-erasure-coding = { path = "../../../erasure-coding" } -polkadot-node-subsystem = { path = "../../subsystem" } -polkadot-node-subsystem-util = { path = "../../subsystem-util" } -polkadot-overseer = { path = "../../overseer" } -polkadot-primitives = { path = "../../../primitives" } -polkadot-node-primitives = { path = "../../primitives" } -sp-consensus = { path = "../../../../substrate/primitives/consensus/common", default-features = false } -polkadot-node-jaeger = { path = "../../jaeger" } +codec = { features = ["derive"], workspace = true, default-features = true } +polkadot-erasure-coding = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-node-subsystem-util = { workspace = true, default-features = true } +polkadot-overseer = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +sp-consensus = { workspace = true } +polkadot-node-jaeger = { workspace = true, default-features = true } [dev-dependencies] log = { workspace = true, default-features = true } -env_logger = "0.11" -assert_matches = "1.4.0" -kvdb-memorydb = "0.13.0" +env_logger = { workspace = true } +assert_matches = { workspace = true } +kvdb-memorydb = { workspace = true } -sp-core = { path = "../../../../substrate/primitives/core" } -polkadot-node-subsystem-util = { path = "../../subsystem-util" } -polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } -sp-keyring = { path = "../../../../substrate/primitives/keyring" } -parking_lot = "0.12.1" -polkadot-primitives-test-helpers = { path = "../../../primitives/test-helpers" } +sp-core = { workspace = true, default-features = true } +polkadot-node-subsystem-util = { workspace = true, default-features = true } +polkadot-node-subsystem-test-helpers = { workspace = true } +sp-keyring = { workspace = true, default-features = true } +parking_lot = { workspace = true, default-features = true } +polkadot-primitives-test-helpers = { workspace = true } diff --git a/polkadot/node/core/backing/Cargo.toml b/polkadot/node/core/backing/Cargo.toml index ffd6de076889413e6872e7c765d849798afb338a..1b52afc309bc9e301f879a720d253467a5359f13 100644 --- a/polkadot/node/core/backing/Cargo.toml +++ b/polkadot/node/core/backing/Cargo.toml @@ -10,28 +10,28 @@ description = "The Candidate Backing Subsystem. Tracks parachain candidates that workspace = true [dependencies] -futures = "0.3.30" -sp-keystore = { path = "../../../../substrate/primitives/keystore" } -polkadot-primitives = { path = "../../../primitives" } -polkadot-node-primitives = { path = "../../primitives" } -polkadot-node-subsystem = { path = "../../subsystem" } -polkadot-node-subsystem-util = { path = "../../subsystem-util" } -polkadot-erasure-coding = { path = "../../../erasure-coding" } -polkadot-statement-table = { path = "../../../statement-table" } -bitvec = { version = "1.0.0", default-features = false, features = ["alloc"] } -gum = { package = "tracing-gum", path = "../../gum" } +futures = { workspace = true } +sp-keystore = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-node-subsystem-util = { workspace = true, default-features = true } +polkadot-erasure-coding = { workspace = true, default-features = true } +polkadot-statement-table = { workspace = true, default-features = true } +bitvec = { features = ["alloc"], workspace = true } +gum = { workspace = true, default-features = true } thiserror = { workspace = true } -fatality = "0.1.1" -schnellru = "0.2.1" +fatality = { workspace = true } +schnellru = { workspace = true } [dev-dependencies] -sp-core = { path = "../../../../substrate/primitives/core" } -sp-application-crypto = { path = "../../../../substrate/primitives/application-crypto" } -sp-keyring = { path = "../../../../substrate/primitives/keyring" } -sc-keystore = { path = "../../../../substrate/client/keystore" } -sp-tracing = { path = "../../../../substrate/primitives/tracing" } -futures = { version = "0.3.30", features = ["thread-pool"] } -assert_matches = "1.4.0" -rstest = "0.18.2" -polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } -polkadot-primitives-test-helpers = { path = "../../../primitives/test-helpers" } +sp-core = { workspace = true, default-features = true } +sp-application-crypto = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +sc-keystore = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +futures = { features = ["thread-pool"], workspace = true } +assert_matches = { workspace = true } +rstest = { workspace = true } +polkadot-node-subsystem-test-helpers = { workspace = true } +polkadot-primitives-test-helpers = { workspace = true } diff --git a/polkadot/node/core/backing/src/lib.rs b/polkadot/node/core/backing/src/lib.rs index 38e8a93bb0482c074e1e968090db33d16e0a284d..1bda81c5197ef32e5659ab8393ef68384a288577 100644 --- a/polkadot/node/core/backing/src/lib.rs +++ b/polkadot/node/core/backing/src/lib.rs @@ -102,6 +102,7 @@ use polkadot_node_subsystem_util::{ runtime::{ self, prospective_parachains_mode, request_min_backing_votes, ProspectiveParachainsMode, }, + vstaging::{fetch_claim_queue, ClaimQueueSnapshot}, Validator, }; use polkadot_primitives::{ @@ -212,8 +213,6 @@ struct PerRelayParentState { parent: Hash, /// Session index. session_index: SessionIndex, - /// The `ParaId` assigned to the local validator at this relay parent. - assigned_para: Option, /// The `CoreIndex` assigned to the local validator at this relay parent. assigned_core: Option, /// The candidates that are backed by enough validators in their group, by hash. @@ -233,8 +232,11 @@ struct PerRelayParentState { /// If true, we're appending extra bits in the BackedCandidate validator indices bitfield, /// which represent the assigned core index. True if ElasticScalingMVP is enabled. inject_core_index: bool, - /// The core states for all cores. - cores: Vec, + /// The number of cores. + n_cores: u32, + /// Claim queue state. If the runtime API is not available, it'll be populated with info from + /// availability cores. + claim_queue: ClaimQueueSnapshot, /// The validator index -> group mapping at this relay parent. validator_to_group: Arc>>, /// The associated group rotation information. @@ -1004,20 +1006,19 @@ macro_rules! try_runtime_api { fn core_index_from_statement( validator_to_group: &IndexedVec>, group_rotation_info: &GroupRotationInfo, - cores: &[CoreState], + n_cores: u32, + claim_queue: &ClaimQueueSnapshot, statement: &SignedFullStatementWithPVD, ) -> Option { let compact_statement = statement.as_unchecked(); let candidate_hash = CandidateHash(*compact_statement.unchecked_payload().candidate_hash()); - let n_cores = cores.len(); - gum::trace!( target:LOG_TARGET, ?group_rotation_info, ?statement, ?validator_to_group, - n_cores = ?cores.len(), + n_cores, ?candidate_hash, "Extracting core index from statement" ); @@ -1029,7 +1030,7 @@ fn core_index_from_statement( ?group_rotation_info, ?statement, ?validator_to_group, - n_cores = ?cores.len() , + n_cores, ?candidate_hash, "Invalid validator index: {:?}", statement_validator_index @@ -1038,37 +1039,25 @@ fn core_index_from_statement( }; // First check if the statement para id matches the core assignment. - let core_index = group_rotation_info.core_for_group(*group_index, n_cores); + let core_index = group_rotation_info.core_for_group(*group_index, n_cores as _); - if core_index.0 as usize > n_cores { + if core_index.0 > n_cores { gum::warn!(target: LOG_TARGET, ?candidate_hash, ?core_index, n_cores, "Invalid CoreIndex"); return None } if let StatementWithPVD::Seconded(candidate, _pvd) = statement.payload() { let candidate_para_id = candidate.descriptor.para_id; - let assigned_para_id = match &cores[core_index.0 as usize] { - CoreState::Free => { - gum::debug!(target: LOG_TARGET, ?candidate_hash, "Invalid CoreIndex, core is not assigned to any para_id"); - return None - }, - CoreState::Occupied(occupied) => - if let Some(next) = &occupied.next_up_on_available { - next.para_id - } else { - return None - }, - CoreState::Scheduled(scheduled) => scheduled.para_id, - }; + let mut assigned_paras = claim_queue.iter_claims_for_core(&core_index); - if assigned_para_id != candidate_para_id { + if !assigned_paras.any(|id| id == &candidate_para_id) { gum::debug!( target: LOG_TARGET, ?candidate_hash, ?core_index, - ?assigned_para_id, + assigned_paras = ?claim_queue.iter_claims_for_core(&core_index).collect::>(), ?candidate_para_id, - "Invalid CoreIndex, core is assigned to a different para_id" + "Invalid CoreIndex, core is not assigned to this para_id" ); return None } @@ -1129,6 +1118,8 @@ async fn construct_per_relay_parent_state( Error::UtilError(TryFrom::try_from(e).expect("the conversion is infallible; qed")) })?; + let maybe_claim_queue = try_runtime_api!(fetch_claim_queue(ctx.sender(), parent).await); + let signing_context = SigningContext { parent_hash: parent, session_index }; let validator = match Validator::construct( &validators, @@ -1153,31 +1144,35 @@ async fn construct_per_relay_parent_state( let mut groups = HashMap::>::new(); let mut assigned_core = None; - let mut assigned_para = None; + + let has_claim_queue = maybe_claim_queue.is_some(); + let mut claim_queue = maybe_claim_queue.unwrap_or_default().0; for (idx, core) in cores.iter().enumerate() { - let core_para_id = match core { - CoreState::Scheduled(scheduled) => scheduled.para_id, - CoreState::Occupied(occupied) => - if mode.is_enabled() { + let core_index = CoreIndex(idx as _); + + if !has_claim_queue { + match core { + CoreState::Scheduled(scheduled) => + claim_queue.insert(core_index, [scheduled.para_id].into_iter().collect()), + CoreState::Occupied(occupied) if mode.is_enabled() => { // Async backing makes it legal to build on top of // occupied core. if let Some(next) = &occupied.next_up_on_available { - next.para_id + claim_queue.insert(core_index, [next.para_id].into_iter().collect()) } else { continue } - } else { - continue }, - CoreState::Free => continue, - }; + _ => continue, + }; + } else if !claim_queue.contains_key(&core_index) { + continue + } - let core_index = CoreIndex(idx as _); let group_index = group_rotation_info.group_for_core(core_index, n_cores); if let Some(g) = validator_groups.get(group_index.0 as usize) { if validator.as_ref().map_or(false, |v| g.contains(&v.index())) { - assigned_para = Some(core_para_id); assigned_core = Some(core_index); } groups.insert(core_index, g.clone()); @@ -1212,7 +1207,6 @@ async fn construct_per_relay_parent_state( parent, session_index, assigned_core, - assigned_para, backed: HashSet::new(), table: Table::new(table_config), table_context, @@ -1221,7 +1215,8 @@ async fn construct_per_relay_parent_state( fallbacks: HashMap::new(), minimum_backing_votes, inject_core_index, - cores, + n_cores: cores.len() as u32, + claim_queue: ClaimQueueSnapshot::from(claim_queue), validator_to_group: validator_to_group.clone(), group_rotation_info, })) @@ -1674,7 +1669,8 @@ async fn import_statement( let core = core_index_from_statement( &rp_state.validator_to_group, &rp_state.group_rotation_info, - &rp_state.cores, + rp_state.n_cores, + &rp_state.claim_queue, statement, ) .ok_or(Error::CoreIndexUnavailable)?; @@ -2098,12 +2094,14 @@ async fn handle_second_message( return Ok(()) } + let assigned_paras = rp_state.assigned_core.and_then(|core| rp_state.claim_queue.0.get(&core)); + // Sanity check that candidate is from our assignment. - if Some(candidate.descriptor().para_id) != rp_state.assigned_para { + if !matches!(assigned_paras, Some(paras) if paras.contains(&candidate.descriptor().para_id)) { gum::debug!( target: LOG_TARGET, our_assignment_core = ?rp_state.assigned_core, - our_assignment_para = ?rp_state.assigned_para, + our_assignment_paras = ?assigned_paras, collation = ?candidate.descriptor().para_id, "Subsystem asked to second for para outside of our assignment", ); @@ -2113,7 +2111,7 @@ async fn handle_second_message( gum::debug!( target: LOG_TARGET, our_assignment_core = ?rp_state.assigned_core, - our_assignment_para = ?rp_state.assigned_para, + our_assignment_paras = ?assigned_paras, collation = ?candidate.descriptor().para_id, "Current assignments vs collation", ); diff --git a/polkadot/node/core/backing/src/tests/mod.rs b/polkadot/node/core/backing/src/tests/mod.rs index bb23c7fbeb24f741ce065f2285caaa7fdb34c922..5f2bc7e18424390bbd012cdccc268c902820e4e3 100644 --- a/polkadot/node/core/backing/src/tests/mod.rs +++ b/polkadot/node/core/backing/src/tests/mod.rs @@ -42,7 +42,10 @@ use sp_application_crypto::AppCrypto; use sp_keyring::Sr25519Keyring; use sp_keystore::Keystore; use sp_tracing as _; -use std::{collections::HashMap, time::Duration}; +use std::{ + collections::{BTreeMap, HashMap, VecDeque}, + time::Duration, +}; mod prospective_parachains; @@ -75,6 +78,7 @@ pub(crate) struct TestState { validator_groups: (Vec>, GroupRotationInfo), validator_to_group: IndexedVec>, availability_cores: Vec, + claim_queue: BTreeMap>, head_data: HashMap, signing_context: SigningContext, relay_parent: Hash, @@ -130,6 +134,10 @@ impl Default for TestState { CoreState::Scheduled(ScheduledCore { para_id: chain_b, collator: None }), ]; + let mut claim_queue = BTreeMap::new(); + claim_queue.insert(CoreIndex(0), [chain_a].into_iter().collect()); + claim_queue.insert(CoreIndex(1), [chain_b].into_iter().collect()); + let mut head_data = HashMap::new(); head_data.insert(chain_a, HeadData(vec![4, 5, 6])); head_data.insert(chain_b, HeadData(vec![5, 6, 7])); @@ -153,6 +161,7 @@ impl Default for TestState { validator_groups: (validator_groups, group_rotation_info), validator_to_group, availability_cores, + claim_queue, head_data, validation_data, signing_context, @@ -338,6 +347,26 @@ async fn test_startup(virtual_overseer: &mut VirtualOverseer, test_state: &TestS tx.send(Ok(test_state.disabled_validators.clone())).unwrap(); } ); + + assert_matches!( + virtual_overseer.recv().await, + AllMessages::RuntimeApi( + RuntimeApiMessage::Request(parent, RuntimeApiRequest::Version(tx)) + ) if parent == test_state.relay_parent => { + tx.send(Ok(RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT)).unwrap(); + } + ); + + assert_matches!( + virtual_overseer.recv().await, + AllMessages::RuntimeApi( + RuntimeApiMessage::Request(parent, RuntimeApiRequest::ClaimQueue(tx)) + ) if parent == test_state.relay_parent => { + tx.send(Ok( + test_state.claim_queue.clone() + )).unwrap(); + } + ); } async fn assert_validation_requests( @@ -730,11 +759,16 @@ fn get_backed_candidate_preserves_order() { // Assign the second core to the same para as the first one. test_state.availability_cores[1] = CoreState::Scheduled(ScheduledCore { para_id: test_state.chain_ids[0], collator: None }); + *test_state.claim_queue.get_mut(&CoreIndex(1)).unwrap() = + [test_state.chain_ids[0]].into_iter().collect(); // Add another availability core for paraid 2. test_state.availability_cores.push(CoreState::Scheduled(ScheduledCore { para_id: test_state.chain_ids[1], collator: None, })); + test_state + .claim_queue + .insert(CoreIndex(2), [test_state.chain_ids[1]].into_iter().collect()); test_harness(test_state.keystore.clone(), |mut virtual_overseer| async move { test_startup(&mut virtual_overseer, &test_state).await; @@ -1103,7 +1137,8 @@ fn extract_core_index_from_statement_works() { let core_index_1 = core_index_from_statement( &test_state.validator_to_group, &test_state.validator_groups.1, - &test_state.availability_cores, + test_state.availability_cores.len() as _, + &test_state.claim_queue.clone().into(), &signed_statement_1, ) .unwrap(); @@ -1113,7 +1148,8 @@ fn extract_core_index_from_statement_works() { let core_index_2 = core_index_from_statement( &test_state.validator_to_group, &test_state.validator_groups.1, - &test_state.availability_cores, + test_state.availability_cores.len() as _, + &test_state.claim_queue.clone().into(), &signed_statement_2, ); @@ -1123,7 +1159,8 @@ fn extract_core_index_from_statement_works() { let core_index_3 = core_index_from_statement( &test_state.validator_to_group, &test_state.validator_groups.1, - &test_state.availability_cores, + test_state.availability_cores.len() as _, + &test_state.claim_queue.clone().into(), &signed_statement_3, ) .unwrap(); diff --git a/polkadot/node/core/backing/src/tests/prospective_parachains.rs b/polkadot/node/core/backing/src/tests/prospective_parachains.rs index 74490c84eb18ba5521b4a189635c0326655973e5..15bc0b4a113902ab118bb24f5075eb947b9d874c 100644 --- a/polkadot/node/core/backing/src/tests/prospective_parachains.rs +++ b/polkadot/node/core/backing/src/tests/prospective_parachains.rs @@ -212,6 +212,26 @@ async fn activate_leaf( tx.send(Ok(Vec::new())).unwrap(); } ); + + assert_matches!( + virtual_overseer.recv().await, + AllMessages::RuntimeApi( + RuntimeApiMessage::Request(parent, RuntimeApiRequest::Version(tx)) + ) if parent == hash => { + tx.send(Ok(RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT)).unwrap(); + } + ); + + assert_matches!( + virtual_overseer.recv().await, + AllMessages::RuntimeApi( + RuntimeApiMessage::Request(parent, RuntimeApiRequest::ClaimQueue(tx)) + ) if parent == hash => { + tx.send(Ok( + test_state.claim_queue.clone() + )).unwrap(); + } + ); } } diff --git a/polkadot/node/core/bitfield-signing/Cargo.toml b/polkadot/node/core/bitfield-signing/Cargo.toml index 335e733987b017c0ee68f85d6dede42e3128b83c..126a18a141661c49411b576d9730e255ca627692 100644 --- a/polkadot/node/core/bitfield-signing/Cargo.toml +++ b/polkadot/node/core/bitfield-signing/Cargo.toml @@ -10,15 +10,15 @@ description = "Bitfield signing subsystem for the Polkadot node" workspace = true [dependencies] -futures = "0.3.30" -gum = { package = "tracing-gum", path = "../../gum" } -polkadot-primitives = { path = "../../../primitives" } -polkadot-node-subsystem = { path = "../../subsystem" } -polkadot-node-subsystem-util = { path = "../../subsystem-util" } -sp-keystore = { path = "../../../../substrate/primitives/keystore" } -wasm-timer = "0.2.5" +futures = { workspace = true } +gum = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-node-subsystem-util = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +wasm-timer = { workspace = true } thiserror = { workspace = true } [dev-dependencies] -polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } -polkadot-primitives-test-helpers = { path = "../../../primitives/test-helpers" } +polkadot-node-subsystem-test-helpers = { workspace = true } +polkadot-primitives-test-helpers = { workspace = true } diff --git a/polkadot/node/core/candidate-validation/Cargo.toml b/polkadot/node/core/candidate-validation/Cargo.toml index a0b25e6c25f9ccd3c5ab2e2ddd38b1f0aa0433a5..e1a98f80783fa472309d012eb097ad28dac72d46 100644 --- a/polkadot/node/core/candidate-validation/Cargo.toml +++ b/polkadot/node/core/candidate-validation/Cargo.toml @@ -10,29 +10,29 @@ license.workspace = true workspace = true [dependencies] -async-trait = "0.1.79" -futures = "0.3.30" -futures-timer = "3.0.2" -gum = { package = "tracing-gum", path = "../../gum" } +async-trait = { workspace = true } +futures = { workspace = true } +futures-timer = { workspace = true } +gum = { workspace = true, default-features = true } -sp-maybe-compressed-blob = { package = "sp-maybe-compressed-blob", path = "../../../../substrate/primitives/maybe-compressed-blob" } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["bit-vec", "derive"] } +sp-maybe-compressed-blob = { workspace = true, default-features = true } +codec = { features = ["bit-vec", "derive"], workspace = true } -polkadot-primitives = { path = "../../../primitives" } -polkadot-parachain-primitives = { path = "../../../parachain" } -polkadot-node-primitives = { path = "../../primitives" } -polkadot-node-subsystem = { path = "../../subsystem" } -polkadot-node-subsystem-util = { path = "../../subsystem-util" } -polkadot-node-metrics = { path = "../../metrics" } -polkadot-overseer = { path = "../../overseer" } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-parachain-primitives = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-node-subsystem-util = { workspace = true, default-features = true } +polkadot-node-metrics = { workspace = true, default-features = true } +polkadot-overseer = { workspace = true, default-features = true } [target.'cfg(not(any(target_os = "android", target_os = "unknown")))'.dependencies] -polkadot-node-core-pvf = { path = "../pvf" } +polkadot-node-core-pvf = { workspace = true, default-features = true } [dev-dependencies] -sp-keyring = { path = "../../../../substrate/primitives/keyring" } -futures = { version = "0.3.30", features = ["thread-pool"] } -assert_matches = "1.4.0" -polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } -sp-core = { path = "../../../../substrate/primitives/core" } -polkadot-primitives-test-helpers = { path = "../../../primitives/test-helpers" } +sp-keyring = { workspace = true, default-features = true } +futures = { features = ["thread-pool"], workspace = true } +assert_matches = { workspace = true } +polkadot-node-subsystem-test-helpers = { workspace = true } +sp-core = { workspace = true, default-features = true } +polkadot-primitives-test-helpers = { workspace = true } diff --git a/polkadot/node/core/chain-api/Cargo.toml b/polkadot/node/core/chain-api/Cargo.toml index c58024876b9c77c371b9325c9da922a21211e698..a8e911e0c5c9586c31109462e1a9527c9d8246f2 100644 --- a/polkadot/node/core/chain-api/Cargo.toml +++ b/polkadot/node/core/chain-api/Cargo.toml @@ -10,20 +10,20 @@ description = "The Chain API subsystem provides access to chain related utility workspace = true [dependencies] -futures = "0.3.30" -gum = { package = "tracing-gum", path = "../../gum" } -polkadot-node-metrics = { path = "../../metrics" } -polkadot-node-subsystem = { path = "../../subsystem" } -polkadot-node-subsystem-types = { path = "../../subsystem-types" } -sc-client-api = { path = "../../../../substrate/client/api" } -sc-consensus-babe = { path = "../../../../substrate/client/consensus/babe" } +futures = { workspace = true } +gum = { workspace = true, default-features = true } +polkadot-node-metrics = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-node-subsystem-types = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-consensus-babe = { workspace = true, default-features = true } [dev-dependencies] -futures = { version = "0.3.30", features = ["thread-pool"] } -maplit = "1.0.2" -codec = { package = "parity-scale-codec", version = "3.6.12" } -polkadot-node-primitives = { path = "../../primitives" } -polkadot-primitives = { path = "../../../primitives" } -polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } -sp-core = { path = "../../../../substrate/primitives/core" } -sp-blockchain = { path = "../../../../substrate/primitives/blockchain" } +futures = { features = ["thread-pool"], workspace = true } +maplit = { workspace = true } +codec = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-node-subsystem-test-helpers = { workspace = true } +sp-core = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } diff --git a/polkadot/node/core/chain-selection/Cargo.toml b/polkadot/node/core/chain-selection/Cargo.toml index 2aa929653ccc2a2fa07b16a7ad0a4ada025afb5a..755d5cadeaaf388a4e21eff79699ae06368e8010 100644 --- a/polkadot/node/core/chain-selection/Cargo.toml +++ b/polkadot/node/core/chain-selection/Cargo.toml @@ -10,20 +10,20 @@ license.workspace = true workspace = true [dependencies] -futures = "0.3.30" -futures-timer = "3" -gum = { package = "tracing-gum", path = "../../gum" } -polkadot-primitives = { path = "../../../primitives" } -polkadot-node-primitives = { path = "../../primitives" } -polkadot-node-subsystem = { path = "../../subsystem" } -polkadot-node-subsystem-util = { path = "../../subsystem-util" } -kvdb = "0.13.0" +futures = { workspace = true } +futures-timer = { workspace = true } +gum = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-node-subsystem-util = { workspace = true, default-features = true } +kvdb = { workspace = true } thiserror = { workspace = true } -codec = { package = "parity-scale-codec", version = "3.6.12" } +codec = { workspace = true, default-features = true } [dev-dependencies] -polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } -sp-core = { path = "../../../../substrate/primitives/core" } -parking_lot = "0.12.1" -assert_matches = "1" -kvdb-memorydb = "0.13.0" +polkadot-node-subsystem-test-helpers = { workspace = true } +sp-core = { workspace = true, default-features = true } +parking_lot = { workspace = true, default-features = true } +assert_matches = { workspace = true } +kvdb-memorydb = { workspace = true } diff --git a/polkadot/node/core/dispute-coordinator/Cargo.toml b/polkadot/node/core/dispute-coordinator/Cargo.toml index 2c08cfa9b1efa623ae157c6fd60f10c9330d30d2..eb4600b235b9f2cfde8f030ebb3b9626d6ea8869 100644 --- a/polkadot/node/core/dispute-coordinator/Cargo.toml +++ b/polkadot/node/core/dispute-coordinator/Cargo.toml @@ -10,33 +10,33 @@ license.workspace = true workspace = true [dependencies] -futures = "0.3.30" -gum = { package = "tracing-gum", path = "../../gum" } -codec = { package = "parity-scale-codec", version = "3.6.12" } -kvdb = "0.13.0" +futures = { workspace = true } +gum = { workspace = true, default-features = true } +codec = { workspace = true, default-features = true } +kvdb = { workspace = true } thiserror = { workspace = true } -schnellru = "0.2.1" -fatality = "0.1.1" +schnellru = { workspace = true } +fatality = { workspace = true } -polkadot-primitives = { path = "../../../primitives" } -polkadot-node-primitives = { path = "../../primitives" } -polkadot-node-subsystem = { path = "../../subsystem" } -polkadot-node-subsystem-util = { path = "../../subsystem-util" } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-node-subsystem-util = { workspace = true, default-features = true } -sc-keystore = { path = "../../../../substrate/client/keystore" } +sc-keystore = { workspace = true, default-features = true } [dev-dependencies] -kvdb-memorydb = "0.13.0" -polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } -sp-keyring = { path = "../../../../substrate/primitives/keyring" } -sp-core = { path = "../../../../substrate/primitives/core" } -sp-keystore = { path = "../../../../substrate/primitives/keystore" } -assert_matches = "1.4.0" -polkadot-primitives-test-helpers = { path = "../../../primitives/test-helpers" } -futures-timer = "3.0.2" -sp-application-crypto = { path = "../../../../substrate/primitives/application-crypto" } -sp-tracing = { path = "../../../../substrate/primitives/tracing" } +kvdb-memorydb = { workspace = true } +polkadot-node-subsystem-test-helpers = { workspace = true } +sp-keyring = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +assert_matches = { workspace = true } +polkadot-primitives-test-helpers = { workspace = true } +futures-timer = { workspace = true } +sp-application-crypto = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } [features] # If not enabled, the dispute coordinator will do nothing. diff --git a/polkadot/node/core/parachains-inherent/Cargo.toml b/polkadot/node/core/parachains-inherent/Cargo.toml index 4f6090f90e9535a7cee8da2e333d5e66a0dea972..1e4953f40d0bd87bd5ef69bf3b91b66935e90fdc 100644 --- a/polkadot/node/core/parachains-inherent/Cargo.toml +++ b/polkadot/node/core/parachains-inherent/Cargo.toml @@ -10,13 +10,13 @@ description = "Parachains inherent data provider for Polkadot node" workspace = true [dependencies] -futures = "0.3.30" -futures-timer = "3.0.2" -gum = { package = "tracing-gum", path = "../../gum" } +futures = { workspace = true } +futures-timer = { workspace = true } +gum = { workspace = true, default-features = true } thiserror = { workspace = true } -async-trait = "0.1.79" -polkadot-node-subsystem = { path = "../../subsystem" } -polkadot-overseer = { path = "../../overseer" } -polkadot-primitives = { path = "../../../primitives" } -sp-blockchain = { path = "../../../../substrate/primitives/blockchain" } -sp-inherents = { path = "../../../../substrate/primitives/inherents" } +async-trait = { workspace = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-overseer = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-inherents = { workspace = true, default-features = true } diff --git a/polkadot/node/core/prospective-parachains/Cargo.toml b/polkadot/node/core/prospective-parachains/Cargo.toml index f3193153be8940760ae00e5dac59d837ce15660a..97da5a1e94a07947765ddc8311b23c8d03cb4f79 100644 --- a/polkadot/node/core/prospective-parachains/Cargo.toml +++ b/polkadot/node/core/prospective-parachains/Cargo.toml @@ -10,25 +10,26 @@ description = "The Prospective Parachains subsystem. Tracks and handles prospect workspace = true [dependencies] -futures = "0.3.30" -gum = { package = "tracing-gum", path = "../../gum" } -codec = { package = "parity-scale-codec", version = "3.6.12" } +futures = { workspace = true } +gum = { workspace = true, default-features = true } +codec = { workspace = true, default-features = true } thiserror = { workspace = true } -fatality = "0.1.1" -bitvec = "1" +fatality = { workspace = true } +bitvec = { workspace = true, default-features = true } -polkadot-primitives = { path = "../../../primitives" } -polkadot-node-primitives = { path = "../../primitives" } -polkadot-node-subsystem = { path = "../../subsystem" } -polkadot-node-subsystem-util = { path = "../../subsystem-util" } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-node-subsystem-util = { workspace = true, default-features = true } [dev-dependencies] -assert_matches = "1" -polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } -polkadot-node-subsystem-types = { path = "../../subsystem-types" } -polkadot-primitives-test-helpers = { path = "../../../primitives/test-helpers" } -sp-core = { path = "../../../../substrate/primitives/core" } -sc-keystore = { path = "../../../../substrate/client/keystore" } -sp-application-crypto = { path = "../../../../substrate/primitives/application-crypto" } -sp-keyring = { path = "../../../../substrate/primitives/keyring" } -sp-keystore = { path = "../../../../substrate/primitives/keystore" } +assert_matches = { workspace = true } +polkadot-node-subsystem-test-helpers = { workspace = true } +polkadot-node-subsystem-types = { workspace = true, default-features = true } +polkadot-primitives-test-helpers = { workspace = true } +sp-core = { workspace = true, default-features = true } +sc-keystore = { workspace = true, default-features = true } +sp-application-crypto = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +rstest = { workspace = true } diff --git a/polkadot/node/core/prospective-parachains/src/lib.rs b/polkadot/node/core/prospective-parachains/src/lib.rs index d5bb5ff76ba8e8e603f2ab6b915b6c8fdb2d5f3c..e4b6deffdf4a5280e23c8c4a81bdf2ae56bbb422 100644 --- a/polkadot/node/core/prospective-parachains/src/lib.rs +++ b/polkadot/node/core/prospective-parachains/src/lib.rs @@ -44,6 +44,7 @@ use polkadot_node_subsystem_util::{ inclusion_emulator::{Constraints, RelayChainBlockInfo}, request_session_index_for_child, runtime::{prospective_parachains_mode, ProspectiveParachainsMode}, + vstaging::fetch_claim_queue, }; use polkadot_primitives::{ async_backing::CandidatePendingAvailability, BlockNumber, CandidateHash, @@ -870,37 +871,51 @@ async fn fetch_backing_state( async fn fetch_upcoming_paras( ctx: &mut Context, relay_parent: Hash, -) -> JfyiErrorResult> { - let (tx, rx) = oneshot::channel(); - - // This'll have to get more sophisticated with parathreads, - // but for now we can just use the `AvailabilityCores`. - ctx.send_message(RuntimeApiMessage::Request( - relay_parent, - RuntimeApiRequest::AvailabilityCores(tx), - )) - .await; - - let cores = rx.await.map_err(JfyiError::RuntimeApiRequestCanceled)??; - let mut upcoming = HashSet::new(); - for core in cores { - match core { - CoreState::Occupied(occupied) => { - if let Some(next_up_on_available) = occupied.next_up_on_available { - upcoming.insert(next_up_on_available.para_id); - } - if let Some(next_up_on_time_out) = occupied.next_up_on_time_out { - upcoming.insert(next_up_on_time_out.para_id); +) -> JfyiErrorResult> { + Ok(match fetch_claim_queue(ctx.sender(), relay_parent).await? { + Some(claim_queue) => { + // Runtime supports claim queue - use it + claim_queue + .iter_all_claims() + .flat_map(|(_, paras)| paras.into_iter()) + .copied() + .collect() + }, + None => { + // fallback to availability cores - remove this branch once claim queue is released + // everywhere + let (tx, rx) = oneshot::channel(); + ctx.send_message(RuntimeApiMessage::Request( + relay_parent, + RuntimeApiRequest::AvailabilityCores(tx), + )) + .await; + + let cores = rx.await.map_err(JfyiError::RuntimeApiRequestCanceled)??; + + let mut upcoming = HashSet::with_capacity(cores.len()); + for core in cores { + match core { + CoreState::Occupied(occupied) => { + // core sharing won't work optimally with this branch because the collations + // can't be prepared in advance. + if let Some(next_up_on_available) = occupied.next_up_on_available { + upcoming.insert(next_up_on_available.para_id); + } + if let Some(next_up_on_time_out) = occupied.next_up_on_time_out { + upcoming.insert(next_up_on_time_out.para_id); + } + }, + CoreState::Scheduled(scheduled) => { + upcoming.insert(scheduled.para_id); + }, + CoreState::Free => {}, } - }, - CoreState::Scheduled(scheduled) => { - upcoming.insert(scheduled.para_id); - }, - CoreState::Free => {}, - } - } + } - Ok(upcoming.into_iter().collect()) + upcoming + }, + }) } // Fetch ancestors in descending order, up to the amount requested. diff --git a/polkadot/node/core/prospective-parachains/src/tests.rs b/polkadot/node/core/prospective-parachains/src/tests.rs index d2fc3cbd36235a09bf8ce8c38b231f3e0e27cf97..221fbf4c4e60365855b24bcfff7d89cfbcc6d205 100644 --- a/polkadot/node/core/prospective-parachains/src/tests.rs +++ b/polkadot/node/core/prospective-parachains/src/tests.rs @@ -26,11 +26,15 @@ use polkadot_node_subsystem::{ use polkadot_node_subsystem_test_helpers as test_helpers; use polkadot_primitives::{ async_backing::{AsyncBackingParams, BackingState, Constraints, InboundHrmpLimitations}, - CommittedCandidateReceipt, HeadData, Header, PersistedValidationData, ScheduledCore, + CommittedCandidateReceipt, CoreIndex, HeadData, Header, PersistedValidationData, ScheduledCore, ValidationCodeHash, }; use polkadot_primitives_test_helpers::make_candidate; -use std::sync::Arc; +use rstest::rstest; +use std::{ + collections::{BTreeMap, VecDeque}, + sync::Arc, +}; use test_helpers::mock::new_leaf; const ALLOWED_ANCESTRY_LEN: u32 = 3; @@ -70,7 +74,8 @@ fn dummy_constraints( } struct TestState { - availability_cores: Vec, + claim_queue: BTreeMap>, + runtime_api_version: u32, validation_code_hash: ValidationCodeHash, } @@ -79,13 +84,23 @@ impl Default for TestState { let chain_a = ParaId::from(1); let chain_b = ParaId::from(2); - let availability_cores = vec![ - CoreState::Scheduled(ScheduledCore { para_id: chain_a, collator: None }), - CoreState::Scheduled(ScheduledCore { para_id: chain_b, collator: None }), - ]; + let mut claim_queue = BTreeMap::new(); + claim_queue.insert(CoreIndex(0), [chain_a].into_iter().collect()); + claim_queue.insert(CoreIndex(1), [chain_b].into_iter().collect()); + let validation_code_hash = Hash::repeat_byte(42).into(); - Self { availability_cores, validation_code_hash } + Self { + validation_code_hash, + claim_queue, + runtime_api_version: RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT, + } + } +} + +impl TestState { + fn set_runtime_api_version(&mut self, version: u32) { + self.runtime_api_version = version; } } @@ -227,12 +242,39 @@ async fn handle_leaf_activation( assert_matches!( virtual_overseer.recv().await, AllMessages::RuntimeApi( - RuntimeApiMessage::Request(parent, RuntimeApiRequest::AvailabilityCores(tx)) + RuntimeApiMessage::Request(parent, RuntimeApiRequest::Version(tx)) ) if parent == *hash => { - tx.send(Ok(test_state.availability_cores.clone())).unwrap(); + tx.send( + Ok(test_state.runtime_api_version) + ).unwrap(); } ); + if test_state.runtime_api_version < RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT { + assert_matches!( + virtual_overseer.recv().await, + AllMessages::RuntimeApi( + RuntimeApiMessage::Request(parent, RuntimeApiRequest::AvailabilityCores(tx)) + ) if parent == *hash => { + tx.send(Ok(test_state.claim_queue.values().map(|paras| CoreState::Scheduled( + ScheduledCore { + para_id: *paras.front().unwrap(), + collator: None + } + )).collect())).unwrap(); + } + ); + } else { + assert_matches!( + virtual_overseer.recv().await, + AllMessages::RuntimeApi( + RuntimeApiMessage::Request(parent, RuntimeApiRequest::ClaimQueue(tx)) + ) if parent == *hash => { + tx.send(Ok(test_state.claim_queue.clone())).unwrap(); + } + ); + } + send_block_header(virtual_overseer, *hash, *number).await; // Check that subsystem job issues a request for ancestors. @@ -277,14 +319,16 @@ async fn handle_leaf_activation( ); } - for _ in 0..test_state.availability_cores.len() { + let paras: HashSet<_> = test_state.claim_queue.values().flatten().collect(); + + for _ in 0..paras.len() { let message = virtual_overseer.recv().await; // Get the para we are working with since the order is not deterministic. - let para_id = match message { + let para_id = match &message { AllMessages::RuntimeApi(RuntimeApiMessage::Request( _, RuntimeApiRequest::ParaBackingState(p_id, _), - )) => p_id, + )) => *p_id, _ => panic!("received unexpected message {:?}", message), }; @@ -505,9 +549,18 @@ fn should_do_no_work_if_async_backing_disabled_for_leaf() { // - Two for the same leaf A (one for parachain 1 and one for parachain 2) // - One for leaf B on parachain 1 // - One for leaf C on parachain 2 +// Also tests a claim queue size larger than 1. #[test] fn introduce_candidates_basic() { - let test_state = TestState::default(); + let mut test_state = TestState::default(); + + let chain_a = ParaId::from(1); + let chain_b = ParaId::from(2); + let mut claim_queue = BTreeMap::new(); + claim_queue.insert(CoreIndex(0), [chain_a, chain_b].into_iter().collect()); + + test_state.claim_queue = claim_queue; + let view = test_harness(|mut virtual_overseer| async move { // Leaf A let leaf_a = TestLeaf { @@ -2032,9 +2085,15 @@ fn check_pvd_query() { // Test simultaneously activating and deactivating leaves, and simultaneously deactivating // multiple leaves. -#[test] -fn correctly_updates_leaves() { - let test_state = TestState::default(); +// This test is parametrised with the runtime api version. For versions that don't support the claim +// queue API, we check that av-cores are used. +#[rstest] +#[case(RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT)] +#[case(8)] +fn correctly_updates_leaves(#[case] runtime_api_version: u32) { + let mut test_state = TestState::default(); + test_state.set_runtime_api_version(runtime_api_version); + let view = test_harness(|mut virtual_overseer| async move { // Leaf A let leaf_a = TestLeaf { @@ -2140,15 +2199,12 @@ fn correctly_updates_leaves() { fn persists_pending_availability_candidate() { let mut test_state = TestState::default(); let para_id = ParaId::from(1); - test_state.availability_cores = test_state - .availability_cores + test_state.claim_queue = test_state + .claim_queue .into_iter() - .filter(|core| match core { - CoreState::Scheduled(scheduled_core) => scheduled_core.para_id == para_id, - _ => false, - }) + .filter(|(_, paras)| matches!(paras.front(), Some(para) if para == ¶_id)) .collect(); - assert_eq!(test_state.availability_cores.len(), 1); + assert_eq!(test_state.claim_queue.len(), 1); test_harness(|mut virtual_overseer| async move { let para_head = HeadData(vec![1, 2, 3]); @@ -2237,18 +2293,15 @@ fn persists_pending_availability_candidate() { } #[test] -fn backwards_compatible() { +fn backwards_compatible_with_non_async_backing_params() { let mut test_state = TestState::default(); let para_id = ParaId::from(1); - test_state.availability_cores = test_state - .availability_cores + test_state.claim_queue = test_state + .claim_queue .into_iter() - .filter(|core| match core { - CoreState::Scheduled(scheduled_core) => scheduled_core.para_id == para_id, - _ => false, - }) + .filter(|(_, paras)| matches!(paras.front(), Some(para) if para == ¶_id)) .collect(); - assert_eq!(test_state.availability_cores.len(), 1); + assert_eq!(test_state.claim_queue.len(), 1); test_harness(|mut virtual_overseer| async move { let para_head = HeadData(vec![1, 2, 3]); @@ -2350,20 +2403,30 @@ fn uses_ancestry_only_within_session() { .await; assert_matches!( - virtual_overseer.recv().await, - AllMessages::RuntimeApi( - RuntimeApiMessage::Request(parent, RuntimeApiRequest::AsyncBackingParams(tx)) - ) if parent == hash => { - tx.send(Ok(AsyncBackingParams { max_candidate_depth: 0, allowed_ancestry_len: ancestry_len - })).unwrap(); } - ); + virtual_overseer.recv().await, + AllMessages::RuntimeApi( + RuntimeApiMessage::Request( + parent, + RuntimeApiRequest::AsyncBackingParams(tx) + )) if parent == hash => { + tx.send(Ok(AsyncBackingParams { max_candidate_depth: 0, allowed_ancestry_len: ancestry_len})).unwrap(); + }); assert_matches!( virtual_overseer.recv().await, AllMessages::RuntimeApi( - RuntimeApiMessage::Request(parent, RuntimeApiRequest::AvailabilityCores(tx)) + RuntimeApiMessage::Request(parent, RuntimeApiRequest::Version(tx)) + ) if parent == hash => { + tx.send(Ok(RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT)).unwrap(); + } + ); + + assert_matches!( + virtual_overseer.recv().await, + AllMessages::RuntimeApi( + RuntimeApiMessage::Request(parent, RuntimeApiRequest::ClaimQueue(tx)) ) if parent == hash => { - tx.send(Ok(Vec::new())).unwrap(); + tx.send(Ok(BTreeMap::new())).unwrap(); } ); diff --git a/polkadot/node/core/provisioner/Cargo.toml b/polkadot/node/core/provisioner/Cargo.toml index a81d22c6f82838c2d446a7d8cd0997013f161fa3..5869e494c70ff40365397d3ffa104f5bad6c421e 100644 --- a/polkadot/node/core/provisioner/Cargo.toml +++ b/polkadot/node/core/provisioner/Cargo.toml @@ -10,21 +10,21 @@ license.workspace = true workspace = true [dependencies] -bitvec = { version = "1.0.0", default-features = false, features = ["alloc"] } -futures = "0.3.30" -gum = { package = "tracing-gum", path = "../../gum" } +bitvec = { features = ["alloc"], workspace = true } +futures = { workspace = true } +gum = { workspace = true, default-features = true } thiserror = { workspace = true } -polkadot-primitives = { path = "../../../primitives" } -polkadot-node-primitives = { path = "../../primitives" } -polkadot-node-subsystem = { path = "../../subsystem" } -polkadot-node-subsystem-util = { path = "../../subsystem-util" } -futures-timer = "3.0.2" -fatality = "0.1.1" -schnellru = "0.2.1" +polkadot-primitives = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-node-subsystem-util = { workspace = true, default-features = true } +futures-timer = { workspace = true } +fatality = { workspace = true } +schnellru = { workspace = true } [dev-dependencies] -sp-application-crypto = { path = "../../../../substrate/primitives/application-crypto" } -sp-keystore = { path = "../../../../substrate/primitives/keystore" } -polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } -polkadot-primitives-test-helpers = { path = "../../../primitives/test-helpers" } -rstest = "0.18.2" +sp-application-crypto = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +polkadot-node-subsystem-test-helpers = { workspace = true } +polkadot-primitives-test-helpers = { workspace = true } +rstest = { workspace = true } diff --git a/polkadot/node/core/pvf-checker/Cargo.toml b/polkadot/node/core/pvf-checker/Cargo.toml index 6dec407e2d2d1f91bcdf72b73b1db376dcdd07d5..73ef17a2843aedcffc40c6456d5519e62265b605 100644 --- a/polkadot/node/core/pvf-checker/Cargo.toml +++ b/polkadot/node/core/pvf-checker/Cargo.toml @@ -10,24 +10,24 @@ license.workspace = true workspace = true [dependencies] -futures = "0.3.30" +futures = { workspace = true } thiserror = { workspace = true } -gum = { package = "tracing-gum", path = "../../gum" } +gum = { workspace = true, default-features = true } -polkadot-node-primitives = { path = "../../primitives" } -polkadot-node-subsystem = { path = "../../subsystem" } -polkadot-primitives = { path = "../../../primitives" } -polkadot-node-subsystem-util = { path = "../../subsystem-util" } -polkadot-overseer = { path = "../../overseer" } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-node-subsystem-util = { workspace = true, default-features = true } +polkadot-overseer = { workspace = true, default-features = true } -sp-keystore = { path = "../../../../substrate/primitives/keystore" } +sp-keystore = { workspace = true, default-features = true } [dev-dependencies] -sp-core = { path = "../../../../substrate/primitives/core" } -sp-runtime = { path = "../../../../substrate/primitives/runtime" } -sc-keystore = { path = "../../../../substrate/client/keystore" } -sp-keyring = { path = "../../../../substrate/primitives/keyring" } -polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } -polkadot-primitives-test-helpers = { path = "../../../primitives/test-helpers" } -sp-application-crypto = { path = "../../../../substrate/primitives/application-crypto" } -futures-timer = "3.0.2" +sp-core = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sc-keystore = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +polkadot-node-subsystem-test-helpers = { workspace = true } +polkadot-primitives-test-helpers = { workspace = true } +sp-application-crypto = { workspace = true, default-features = true } +futures-timer = { workspace = true } diff --git a/polkadot/node/core/pvf/Cargo.toml b/polkadot/node/core/pvf/Cargo.toml index 8aebe0b4c3f0c3875781ed537eadd4887ccf856b..7444f7927f568359fe2a33392468b1f38d1e400f 100644 --- a/polkadot/node/core/pvf/Cargo.toml +++ b/polkadot/node/core/pvf/Cargo.toml @@ -10,60 +10,60 @@ license.workspace = true workspace = true [dependencies] -always-assert = "0.1" -array-bytes = "6.2.2" -blake3 = "1.5" -cfg-if = "1.0" -futures = "0.3.30" -futures-timer = "3.0.2" -gum = { package = "tracing-gum", path = "../../gum" } -is_executable = { version = "1.0.1", optional = true } -pin-project = "1.0.9" -rand = "0.8.5" -slotmap = "1.0" -tempfile = "3.3.0" +always-assert = { workspace = true } +array-bytes = { workspace = true, default-features = true } +blake3 = { workspace = true } +cfg-if = { workspace = true } +futures = { workspace = true } +futures-timer = { workspace = true } +gum = { workspace = true, default-features = true } +is_executable = { optional = true, workspace = true } +pin-project = { workspace = true } +rand = { workspace = true, default-features = true } +slotmap = { workspace = true } +tempfile = { workspace = true } thiserror = { workspace = true } -tokio = { version = "1.24.2", features = ["fs", "process"] } +tokio = { features = ["fs", "process"], workspace = true, default-features = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", -] } +], workspace = true } -polkadot-parachain-primitives = { path = "../../../parachain" } -polkadot-core-primitives = { path = "../../../core-primitives" } -polkadot-node-core-pvf-common = { path = "common" } -polkadot-node-metrics = { path = "../../metrics" } -polkadot-node-primitives = { path = "../../primitives" } -polkadot-node-subsystem = { path = "../../subsystem" } -polkadot-primitives = { path = "../../../primitives" } +polkadot-parachain-primitives = { workspace = true, default-features = true } +polkadot-core-primitives = { workspace = true, default-features = true } +polkadot-node-core-pvf-common = { workspace = true, default-features = true } +polkadot-node-metrics = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } -sp-core = { path = "../../../../substrate/primitives/core" } -sp-maybe-compressed-blob = { path = "../../../../substrate/primitives/maybe-compressed-blob", optional = true } -polkadot-node-core-pvf-prepare-worker = { path = "prepare-worker", optional = true } -polkadot-node-core-pvf-execute-worker = { path = "execute-worker", optional = true } +sp-core = { workspace = true, default-features = true } +sp-maybe-compressed-blob = { optional = true, workspace = true, default-features = true } +polkadot-node-core-pvf-prepare-worker = { optional = true, workspace = true, default-features = true } +polkadot-node-core-pvf-execute-worker = { optional = true, workspace = true, default-features = true } [dev-dependencies] -assert_matches = "1.4.0" -criterion = { version = "0.5.1", default-features = false, features = [ +assert_matches = { workspace = true } +criterion = { features = [ "async_tokio", "cargo_bench_support", -] } -hex-literal = "0.4.1" +], workspace = true } +hex-literal = { workspace = true, default-features = true } -polkadot-node-core-pvf-common = { path = "common", features = ["test-utils"] } +polkadot-node-core-pvf-common = { features = ["test-utils"], workspace = true, default-features = true } # For benches and integration tests, depend on ourselves with the test-utils # feature. -polkadot-node-core-pvf = { path = "", features = ["test-utils"] } -rococo-runtime = { path = "../../../runtime/rococo" } +polkadot-node-core-pvf = { features = ["test-utils"], workspace = true, default-features = true } +rococo-runtime = { workspace = true } -test-parachain-adder = { path = "../../../parachain/test-parachains/adder" } -test-parachain-halt = { path = "../../../parachain/test-parachains/halt" } +test-parachain-adder = { workspace = true } +test-parachain-halt = { workspace = true } [target.'cfg(target_os = "linux")'.dev-dependencies] libc = "0.2.153" procfs = "0.16.0" rusty-fork = "0.3.0" -sc-sysinfo = { path = "../../../../substrate/client/sysinfo" } +sc-sysinfo = { workspace = true, default-features = true } [[bench]] name = "host_prepare_rococo_runtime" diff --git a/polkadot/node/core/pvf/common/Cargo.toml b/polkadot/node/core/pvf/common/Cargo.toml index 491f6cc49642cb3202f87bf189e7467cfb607230..18b3f959c95513763addc9ddf4ff82783e5c1a02 100644 --- a/polkadot/node/core/pvf/common/Cargo.toml +++ b/polkadot/node/core/pvf/common/Cargo.toml @@ -10,29 +10,29 @@ license.workspace = true workspace = true [dependencies] -cpu-time = "1.0.0" -futures = "0.3.30" -gum = { package = "tracing-gum", path = "../../../gum" } -libc = "0.2.152" -nix = { version = "0.28.0", features = ["resource", "sched"] } +cpu-time = { workspace = true } +futures = { workspace = true } +gum = { workspace = true, default-features = true } +libc = { workspace = true } +nix = { features = ["resource", "sched"], workspace = true } thiserror = { workspace = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", -] } +], workspace = true } -polkadot-parachain-primitives = { path = "../../../../parachain" } -polkadot-primitives = { path = "../../../../primitives" } +polkadot-parachain-primitives = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } -sc-executor = { path = "../../../../../substrate/client/executor" } -sc-executor-common = { path = "../../../../../substrate/client/executor/common" } -sc-executor-wasmtime = { path = "../../../../../substrate/client/executor/wasmtime" } +sc-executor = { workspace = true, default-features = true } +sc-executor-common = { workspace = true, default-features = true } +sc-executor-wasmtime = { workspace = true, default-features = true } -sp-core = { path = "../../../../../substrate/primitives/core" } -sp-crypto-hashing = { path = "../../../../../substrate/primitives/crypto/hashing" } -sp-externalities = { path = "../../../../../substrate/primitives/externalities" } -sp-io = { path = "../../../../../substrate/primitives/io" } -sp-tracing = { path = "../../../../../substrate/primitives/tracing" } +sp-core = { workspace = true, default-features = true } +sp-crypto-hashing = { workspace = true, default-features = true } +sp-externalities = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } [target.'cfg(target_os = "linux")'.dependencies] landlock = "0.3.0" @@ -41,8 +41,8 @@ landlock = "0.3.0" seccompiler = "0.4.0" [dev-dependencies] -assert_matches = "1.4.0" -tempfile = "3.3.0" +assert_matches = { workspace = true } +tempfile = { workspace = true } [features] # This feature is used to export test code to other crates without putting it in the production build. diff --git a/polkadot/node/core/pvf/common/src/executor_interface.rs b/polkadot/node/core/pvf/common/src/executor_interface.rs index 87491e70c5f2a0a06b22c8e2c902561d0745dbfd..47f9ed1604e781c045ea643d251da8e324c98287 100644 --- a/polkadot/node/core/pvf/common/src/executor_interface.rs +++ b/polkadot/node/core/pvf/common/src/executor_interface.rs @@ -215,19 +215,19 @@ type HostFunctions = ( struct ValidationExternalities(sp_externalities::Extensions); impl sp_externalities::Externalities for ValidationExternalities { - fn storage(&self, _: &[u8]) -> Option> { + fn storage(&mut self, _: &[u8]) -> Option> { panic!("storage: unsupported feature for parachain validation") } - fn storage_hash(&self, _: &[u8]) -> Option> { + fn storage_hash(&mut self, _: &[u8]) -> Option> { panic!("storage_hash: unsupported feature for parachain validation") } - fn child_storage_hash(&self, _: &ChildInfo, _: &[u8]) -> Option> { + fn child_storage_hash(&mut self, _: &ChildInfo, _: &[u8]) -> Option> { panic!("child_storage_hash: unsupported feature for parachain validation") } - fn child_storage(&self, _: &ChildInfo, _: &[u8]) -> Option> { + fn child_storage(&mut self, _: &ChildInfo, _: &[u8]) -> Option> { panic!("child_storage: unsupported feature for parachain validation") } @@ -275,11 +275,11 @@ impl sp_externalities::Externalities for ValidationExternalities { panic!("child_storage_root: unsupported feature for parachain validation") } - fn next_child_storage_key(&self, _: &ChildInfo, _: &[u8]) -> Option> { + fn next_child_storage_key(&mut self, _: &ChildInfo, _: &[u8]) -> Option> { panic!("next_child_storage_key: unsupported feature for parachain validation") } - fn next_storage_key(&self, _: &[u8]) -> Option> { + fn next_storage_key(&mut self, _: &[u8]) -> Option> { panic!("next_storage_key: unsupported feature for parachain validation") } diff --git a/polkadot/node/core/pvf/execute-worker/Cargo.toml b/polkadot/node/core/pvf/execute-worker/Cargo.toml index cf5b873e29d771e3806c8ec3085a7385b0d59b0b..f24b66dc4a0e8ba20f6b7a8205c7092a47c30245 100644 --- a/polkadot/node/core/pvf/execute-worker/Cargo.toml +++ b/polkadot/node/core/pvf/execute-worker/Cargo.toml @@ -10,17 +10,17 @@ license.workspace = true workspace = true [dependencies] -cpu-time = "1.0.0" -gum = { package = "tracing-gum", path = "../../../gum" } -cfg-if = "1.0" -nix = { version = "0.28.0", features = ["process", "resource", "sched"] } -libc = "0.2.152" +cpu-time = { workspace = true } +gum = { workspace = true, default-features = true } +cfg-if = { workspace = true } +nix = { features = ["process", "resource", "sched"], workspace = true } +libc = { workspace = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } -polkadot-node-core-pvf-common = { path = "../common" } -polkadot-parachain-primitives = { path = "../../../../parachain" } -polkadot-primitives = { path = "../../../../primitives" } +polkadot-node-core-pvf-common = { workspace = true, default-features = true } +polkadot-parachain-primitives = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } [features] builder = [] diff --git a/polkadot/node/core/pvf/prepare-worker/Cargo.toml b/polkadot/node/core/pvf/prepare-worker/Cargo.toml index f7daa0d7a89c3e65b3e6dee9ad3bcbe1e9ecf60e..9e0d01fc438b0257b87b9bf6791f466d8691049e 100644 --- a/polkadot/node/core/pvf/prepare-worker/Cargo.toml +++ b/polkadot/node/core/pvf/prepare-worker/Cargo.toml @@ -10,23 +10,23 @@ license.workspace = true workspace = true [dependencies] -blake3 = "1.5" -cfg-if = "1.0" -gum = { package = "tracing-gum", path = "../../../gum" } -libc = "0.2.152" -rayon = "1.5.1" -tracking-allocator = { package = "staging-tracking-allocator", path = "../../../tracking-allocator" } -tikv-jemalloc-ctl = { version = "0.5.0", optional = true } -tikv-jemallocator = { version = "0.5.0", optional = true } -nix = { version = "0.28.0", features = ["process", "resource", "sched"] } +blake3 = { workspace = true } +cfg-if = { workspace = true } +gum = { workspace = true, default-features = true } +libc = { workspace = true } +rayon = { workspace = true } +tracking-allocator = { workspace = true, default-features = true } +tikv-jemalloc-ctl = { optional = true, workspace = true } +tikv-jemallocator = { optional = true, workspace = true } +nix = { features = ["process", "resource", "sched"], workspace = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } -polkadot-node-core-pvf-common = { path = "../common" } -polkadot-primitives = { path = "../../../../primitives" } +polkadot-node-core-pvf-common = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } -sc-executor-common = { path = "../../../../../substrate/client/executor/common" } -sc-executor-wasmtime = { path = "../../../../../substrate/client/executor/wasmtime" } +sc-executor-common = { workspace = true, default-features = true } +sc-executor-wasmtime = { workspace = true, default-features = true } [target.'cfg(target_os = "linux")'.dependencies] tikv-jemallocator = "0.5.0" @@ -41,9 +41,9 @@ jemalloc-allocator = [ ] [dev-dependencies] -criterion = { version = "0.5.1", default-features = false, features = ["cargo_bench_support"] } -rococo-runtime = { path = "../../../../runtime/rococo" } -sp-maybe-compressed-blob = { path = "../../../../../substrate/primitives/maybe-compressed-blob" } +criterion = { features = ["cargo_bench_support"], workspace = true } +rococo-runtime = { workspace = true } +sp-maybe-compressed-blob = { workspace = true, default-features = true } [[bench]] name = "prepare_rococo_runtime" diff --git a/polkadot/node/core/runtime-api/Cargo.toml b/polkadot/node/core/runtime-api/Cargo.toml index 5524cc705457e45e18e6ea9919c567bf796225c7..834e4b300b9eba67c4764ac60e00261b66215250 100644 --- a/polkadot/node/core/runtime-api/Cargo.toml +++ b/polkadot/node/core/runtime-api/Cargo.toml @@ -10,23 +10,23 @@ license.workspace = true workspace = true [dependencies] -futures = "0.3.30" -gum = { package = "tracing-gum", path = "../../gum" } -schnellru = "0.2.1" +futures = { workspace = true } +gum = { workspace = true, default-features = true } +schnellru = { workspace = true } -sp-consensus-babe = { path = "../../../../substrate/primitives/consensus/babe" } +sp-consensus-babe = { workspace = true, default-features = true } -polkadot-primitives = { path = "../../../primitives" } -polkadot-node-metrics = { path = "../../metrics" } -polkadot-node-subsystem = { path = "../../subsystem" } -polkadot-node-subsystem-types = { path = "../../subsystem-types" } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-node-metrics = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-node-subsystem-types = { workspace = true, default-features = true } [dev-dependencies] -sp-api = { path = "../../../../substrate/primitives/api" } -sp-core = { path = "../../../../substrate/primitives/core" } -sp-keyring = { path = "../../../../substrate/primitives/keyring" } -async-trait = "0.1.79" -futures = { version = "0.3.30", features = ["thread-pool"] } -polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } -polkadot-node-primitives = { path = "../../primitives" } -polkadot-primitives-test-helpers = { path = "../../../primitives/test-helpers" } +sp-api = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +async-trait = { workspace = true } +futures = { features = ["thread-pool"], workspace = true } +polkadot-node-subsystem-test-helpers = { workspace = true } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-primitives-test-helpers = { workspace = true } diff --git a/polkadot/node/gum/Cargo.toml b/polkadot/node/gum/Cargo.toml index 0d887b9be5394c6b36f882d60f57d4ee2d9bf8eb..9b2df435a06a90e4cb0561e19ce4a85dd281b127 100644 --- a/polkadot/node/gum/Cargo.toml +++ b/polkadot/node/gum/Cargo.toml @@ -10,7 +10,7 @@ description = "Stick logs together with the TraceID as provided by tempo" workspace = true [dependencies] -coarsetime = "0.1.22" -tracing = "0.1.35" -gum-proc-macro = { package = "tracing-gum-proc-macro", path = "proc-macro" } -polkadot-primitives = { path = "../../primitives", features = ["std"] } +coarsetime = { workspace = true } +tracing = { workspace = true, default-features = true } +gum-proc-macro = { workspace = true, default-features = true } +polkadot-primitives = { features = ["std"], workspace = true, default-features = true } diff --git a/polkadot/node/gum/proc-macro/Cargo.toml b/polkadot/node/gum/proc-macro/Cargo.toml index 70126b4f43367ce11a1a23d462392b513ca1c028..da6364977cae25f16e8605f8024dc96aa86f6120 100644 --- a/polkadot/node/gum/proc-macro/Cargo.toml +++ b/polkadot/node/gum/proc-macro/Cargo.toml @@ -18,12 +18,12 @@ proc-macro = true [dependencies] syn = { features = ["extra-traits", "full"], workspace = true } quote = { workspace = true } -proc-macro2 = "1.0.56" -proc-macro-crate = "3.0.0" -expander = "2.0.0" +proc-macro2 = { workspace = true } +proc-macro-crate = { workspace = true } +expander = { workspace = true } [dev-dependencies] -assert_matches = "1.5.0" +assert_matches = { workspace = true } [features] diff --git a/polkadot/node/jaeger/Cargo.toml b/polkadot/node/jaeger/Cargo.toml index 18b0c417aaf3d5798d81b8a2d4b11e4ddcc5f5fc..90a6c80e3d0bd3ab2567933bf94d89b7a00dc1e9 100644 --- a/polkadot/node/jaeger/Cargo.toml +++ b/polkadot/node/jaeger/Cargo.toml @@ -10,15 +10,15 @@ description = "Polkadot Jaeger primitives, but equally useful for Grafana/Tempo" workspace = true [dependencies] -mick-jaeger = "0.1.8" -lazy_static = "1.4" -parking_lot = "0.12.1" -polkadot-primitives = { path = "../../primitives" } -polkadot-node-primitives = { path = "../primitives" } -sc-network = { path = "../../../substrate/client/network" } -sc-network-types = { path = "../../../substrate/client/network/types" } -sp-core = { path = "../../../substrate/primitives/core" } +mick-jaeger = { workspace = true } +lazy_static = { workspace = true } +parking_lot = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sc-network-types = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } thiserror = { workspace = true } -tokio = "1.37" +tokio = { workspace = true, default-features = true } log = { workspace = true, default-features = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } +codec = { workspace = true } diff --git a/polkadot/node/malus/Cargo.toml b/polkadot/node/malus/Cargo.toml index fec148f7d38150936d733dfadf2030f1eea2c76c..49434606a61c8dff08a7c075c06c998cc8395a5b 100644 --- a/polkadot/node/malus/Cargo.toml +++ b/polkadot/node/malus/Cargo.toml @@ -29,40 +29,40 @@ path = "../../src/bin/prepare-worker.rs" doc = false [dependencies] -polkadot-cli = { path = "../../cli", features = ["malus", "rococo-native", "westend-native"] } -polkadot-node-subsystem = { path = "../subsystem" } -polkadot-node-subsystem-util = { path = "../subsystem-util" } -polkadot-node-subsystem-types = { path = "../subsystem-types" } -polkadot-node-core-dispute-coordinator = { path = "../core/dispute-coordinator" } -polkadot-node-core-candidate-validation = { path = "../core/candidate-validation" } -polkadot-node-core-backing = { path = "../core/backing" } -polkadot-node-primitives = { path = "../primitives" } -polkadot-node-network-protocol = { path = "../network/protocol" } -polkadot-primitives = { path = "../../primitives" } -color-eyre = { version = "0.6.1", default-features = false } -assert_matches = "1.5" -async-trait = "0.1.79" -sp-keystore = { path = "../../../substrate/primitives/keystore" } -sp-core = { path = "../../../substrate/primitives/core" } -clap = { version = "4.5.3", features = ["derive"] } -futures = "0.3.30" -futures-timer = "3.0.2" -gum = { package = "tracing-gum", path = "../gum" } -polkadot-erasure-coding = { path = "../../erasure-coding" } -rand = "0.8.5" +polkadot-cli = { features = ["malus", "rococo-native", "westend-native"], workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-node-subsystem-util = { workspace = true, default-features = true } +polkadot-node-subsystem-types = { workspace = true, default-features = true } +polkadot-node-core-dispute-coordinator = { workspace = true, default-features = true } +polkadot-node-core-candidate-validation = { workspace = true, default-features = true } +polkadot-node-core-backing = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-node-network-protocol = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +color-eyre = { workspace = true } +assert_matches = { workspace = true } +async-trait = { workspace = true } +sp-keystore = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +clap = { features = ["derive"], workspace = true } +futures = { workspace = true } +futures-timer = { workspace = true } +gum = { workspace = true, default-features = true } +polkadot-erasure-coding = { workspace = true, default-features = true } +rand = { workspace = true, default-features = true } # Required for worker binaries to build. -polkadot-node-core-pvf-common = { path = "../core/pvf/common" } -polkadot-node-core-pvf-execute-worker = { path = "../core/pvf/execute-worker" } -polkadot-node-core-pvf-prepare-worker = { path = "../core/pvf/prepare-worker" } +polkadot-node-core-pvf-common = { workspace = true, default-features = true } +polkadot-node-core-pvf-execute-worker = { workspace = true, default-features = true } +polkadot-node-core-pvf-prepare-worker = { workspace = true, default-features = true } [dev-dependencies] -polkadot-node-subsystem-test-helpers = { path = "../subsystem-test-helpers" } -sp-core = { path = "../../../substrate/primitives/core" } -futures = { version = "0.3.30", features = ["thread-pool"] } +polkadot-node-subsystem-test-helpers = { workspace = true } +sp-core = { workspace = true, default-features = true } +futures = { features = ["thread-pool"], workspace = true } [build-dependencies] -substrate-build-script-utils = { path = "../../../substrate/utils/build-script-utils" } +substrate-build-script-utils = { workspace = true, default-features = true } [features] default = [] diff --git a/polkadot/node/metrics/Cargo.toml b/polkadot/node/metrics/Cargo.toml index 55df8d3daf6d17d142aa7980884c5ad9b4f0e568..f4ffbaf19497210afd24946c098c589e8b669f4d 100644 --- a/polkadot/node/metrics/Cargo.toml +++ b/polkadot/node/metrics/Cargo.toml @@ -10,32 +10,32 @@ license.workspace = true workspace = true [dependencies] -futures = "0.3.30" -futures-timer = "3.0.2" -gum = { package = "tracing-gum", path = "../gum" } +futures = { workspace = true } +futures-timer = { workspace = true } +gum = { workspace = true, default-features = true } -metered = { package = "prioritized-metered-channel", version = "0.6.1", default-features = false, features = ["futures_channel"] } +metered = { features = ["futures_channel"], workspace = true } # Both `sc-service` and `sc-cli` are required by runtime metrics `logger_hook()`. -sc-service = { path = "../../../substrate/client/service" } -sc-cli = { path = "../../../substrate/client/cli" } +sc-service = { workspace = true, default-features = true } +sc-cli = { workspace = true, default-features = true } -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../../substrate/utils/prometheus" } -sc-tracing = { path = "../../../substrate/client/tracing" } -codec = { package = "parity-scale-codec", version = "3.6.12" } -polkadot-primitives = { path = "../../primitives" } -bs58 = { version = "0.5.0", features = ["alloc"] } +prometheus-endpoint = { workspace = true, default-features = true } +sc-tracing = { workspace = true, default-features = true } +codec = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +bs58 = { features = ["alloc"], workspace = true, default-features = true } log = { workspace = true, default-features = true } [dev-dependencies] -assert_cmd = "2.0.4" -tempfile = "3.2.0" -hyper = { version = "0.14.20", default-features = false, features = ["http1", "tcp"] } -tokio = "1.37" -polkadot-test-service = { path = "../test/service", features = ["runtime-metrics"] } -substrate-test-utils = { path = "../../../substrate/test-utils" } -sc-service = { path = "../../../substrate/client/service" } -sp-keyring = { path = "../../../substrate/primitives/keyring" } -prometheus-parse = { version = "0.2.2" } +assert_cmd = { workspace = true } +tempfile = { workspace = true } +hyper = { features = ["http1", "tcp"], workspace = true } +tokio = { workspace = true, default-features = true } +polkadot-test-service = { features = ["runtime-metrics"], workspace = true } +substrate-test-utils = { workspace = true } +sc-service = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +prometheus-parse = { workspace = true } [features] default = [] diff --git a/polkadot/node/network/approval-distribution/Cargo.toml b/polkadot/node/network/approval-distribution/Cargo.toml index d80519b9e2e95aa4d958bff5b9a08e3bddb2cf3c..a85cde303b61bfb9281c022b68ea220af18251e6 100644 --- a/polkadot/node/network/approval-distribution/Cargo.toml +++ b/polkadot/node/network/approval-distribution/Cargo.toml @@ -10,32 +10,32 @@ license.workspace = true workspace = true [dependencies] -polkadot-node-metrics = { path = "../../metrics" } -polkadot-node-network-protocol = { path = "../protocol" } -polkadot-node-primitives = { path = "../../primitives" } -polkadot-node-subsystem = { path = "../../subsystem" } -polkadot-node-subsystem-util = { path = "../../subsystem-util" } -polkadot-primitives = { path = "../../../primitives" } -polkadot-node-jaeger = { path = "../../jaeger" } -rand = "0.8" -itertools = "0.11" +polkadot-node-metrics = { workspace = true, default-features = true } +polkadot-node-network-protocol = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-node-subsystem-util = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-node-jaeger = { workspace = true, default-features = true } +rand = { workspace = true, default-features = true } +itertools = { workspace = true } -futures = "0.3.30" -futures-timer = "3.0.2" -gum = { package = "tracing-gum", path = "../../gum" } -bitvec = { version = "1.0.0", default-features = false, features = ["alloc"] } +futures = { workspace = true } +futures-timer = { workspace = true } +gum = { workspace = true, default-features = true } +bitvec = { features = ["alloc"], workspace = true } [dev-dependencies] -sp-authority-discovery = { path = "../../../../substrate/primitives/authority-discovery" } -sp-core = { path = "../../../../substrate/primitives/core", features = ["std"] } +sp-authority-discovery = { workspace = true, default-features = true } +sp-core = { features = ["std"], workspace = true, default-features = true } -polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } -polkadot-primitives-test-helpers = { path = "../../../primitives/test-helpers" } +polkadot-node-subsystem-test-helpers = { workspace = true } +polkadot-primitives-test-helpers = { workspace = true } -assert_matches = "1.4.0" -schnorrkel = { version = "0.11.4", default-features = false } +assert_matches = { workspace = true } +schnorrkel = { workspace = true } # rand_core should match schnorrkel -rand_core = "0.6.2" -rand_chacha = "0.3.1" -env_logger = "0.11" +rand_core = { workspace = true } +rand_chacha = { workspace = true, default-features = true } +env_logger = { workspace = true } log = { workspace = true, default-features = true } diff --git a/polkadot/node/network/availability-distribution/Cargo.toml b/polkadot/node/network/availability-distribution/Cargo.toml index db3a0456d9adbe3bc94e5d69b0c3586a78206c8b..8c5574f244e4a0671e807cc46dcb1286bafaf3a2 100644 --- a/polkadot/node/network/availability-distribution/Cargo.toml +++ b/polkadot/node/network/availability-distribution/Cargo.toml @@ -10,35 +10,35 @@ license.workspace = true workspace = true [dependencies] -futures = "0.3.30" -gum = { package = "tracing-gum", path = "../../gum" } -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["std"] } -polkadot-primitives = { path = "../../../primitives" } -polkadot-erasure-coding = { path = "../../../erasure-coding" } -polkadot-node-network-protocol = { path = "../protocol" } -polkadot-node-subsystem = { path = "../../subsystem" } -polkadot-node-subsystem-util = { path = "../../subsystem-util" } -polkadot-node-primitives = { path = "../../primitives" } -sc-network = { path = "../../../../substrate/client/network" } -sp-core = { path = "../../../../substrate/primitives/core", features = ["std"] } -sp-keystore = { path = "../../../../substrate/primitives/keystore" } +futures = { workspace = true } +gum = { workspace = true, default-features = true } +codec = { features = ["std"], workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-erasure-coding = { workspace = true, default-features = true } +polkadot-node-network-protocol = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-node-subsystem-util = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sp-core = { features = ["std"], workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } thiserror = { workspace = true } -rand = "0.8.5" -derive_more = "0.99.17" -schnellru = "0.2.1" -fatality = "0.1.1" +rand = { workspace = true, default-features = true } +derive_more = { workspace = true, default-features = true } +schnellru = { workspace = true } +fatality = { workspace = true } [dev-dependencies] -polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } -sp-core = { path = "../../../../substrate/primitives/core", features = ["std"] } -sp-keyring = { path = "../../../../substrate/primitives/keyring" } -sp-tracing = { path = "../../../../substrate/primitives/tracing" } -sc-network = { path = "../../../../substrate/client/network" } -futures-timer = "3.0.2" -assert_matches = "1.4.0" -polkadot-primitives-test-helpers = { path = "../../../primitives/test-helpers" } -rstest = "0.18.2" -polkadot-subsystem-bench = { path = "../../subsystem-bench" } +polkadot-node-subsystem-test-helpers = { workspace = true } +sp-core = { features = ["std"], workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +futures-timer = { workspace = true } +assert_matches = { workspace = true } +polkadot-primitives-test-helpers = { workspace = true } +rstest = { workspace = true } +polkadot-subsystem-bench = { workspace = true } [[bench]] diff --git a/polkadot/node/network/availability-recovery/Cargo.toml b/polkadot/node/network/availability-recovery/Cargo.toml index 1c9c861e6f733ebf7e23ae323d6685c9ce26a66b..41f09b1f7044358697fe923ab56f745bfdce22e7 100644 --- a/polkadot/node/network/availability-recovery/Cargo.toml +++ b/polkadot/node/network/availability-recovery/Cargo.toml @@ -10,39 +10,39 @@ license.workspace = true workspace = true [dependencies] -futures = "0.3.30" -tokio = "1.37" -schnellru = "0.2.1" -rand = "0.8.5" -fatality = "0.1.1" +futures = { workspace = true } +tokio = { workspace = true, default-features = true } +schnellru = { workspace = true } +rand = { workspace = true, default-features = true } +fatality = { workspace = true } thiserror = { workspace = true } -async-trait = "0.1.79" -gum = { package = "tracing-gum", path = "../../gum" } - -polkadot-erasure-coding = { path = "../../../erasure-coding" } -polkadot-primitives = { path = "../../../primitives" } -polkadot-node-primitives = { path = "../../primitives" } -polkadot-node-subsystem = { path = "../../subsystem" } -polkadot-node-subsystem-util = { path = "../../subsystem-util" } -polkadot-node-network-protocol = { path = "../protocol" } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -sc-network = { path = "../../../../substrate/client/network" } +async-trait = { workspace = true } +gum = { workspace = true, default-features = true } + +polkadot-erasure-coding = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-node-subsystem-util = { workspace = true, default-features = true } +polkadot-node-network-protocol = { workspace = true, default-features = true } +codec = { features = ["derive"], workspace = true } +sc-network = { workspace = true, default-features = true } [dev-dependencies] -assert_matches = "1.4.0" -futures-timer = "3.0.2" -rstest = "0.18.2" +assert_matches = { workspace = true } +futures-timer = { workspace = true } +rstest = { workspace = true } log = { workspace = true, default-features = true } -sp-tracing = { path = "../../../../substrate/primitives/tracing" } -sp-core = { path = "../../../../substrate/primitives/core" } -sp-keyring = { path = "../../../../substrate/primitives/keyring" } -sp-application-crypto = { path = "../../../../substrate/primitives/application-crypto" } -sc-network = { path = "../../../../substrate/client/network" } +sp-tracing = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +sp-application-crypto = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } -polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } -polkadot-primitives-test-helpers = { path = "../../../primitives/test-helpers" } -polkadot-subsystem-bench = { path = "../../subsystem-bench" } +polkadot-node-subsystem-test-helpers = { workspace = true } +polkadot-primitives-test-helpers = { workspace = true } +polkadot-subsystem-bench = { workspace = true } [[bench]] name = "availability-recovery-regression-bench" diff --git a/polkadot/node/network/bitfield-distribution/Cargo.toml b/polkadot/node/network/bitfield-distribution/Cargo.toml index 6b5b784b7fd899713c4ccbce2f9dec649a50f933..b1becaf319d55068a811a6cd97dbbccc9702dcbb 100644 --- a/polkadot/node/network/bitfield-distribution/Cargo.toml +++ b/polkadot/node/network/bitfield-distribution/Cargo.toml @@ -10,26 +10,26 @@ license.workspace = true workspace = true [dependencies] -always-assert = "0.1" -futures = "0.3.30" -futures-timer = "3.0.2" -gum = { package = "tracing-gum", path = "../../gum" } -polkadot-primitives = { path = "../../../primitives" } -polkadot-node-subsystem = { path = "../../subsystem" } -polkadot-node-subsystem-util = { path = "../../subsystem-util" } -polkadot-node-network-protocol = { path = "../protocol" } -rand = "0.8" +always-assert = { workspace = true } +futures = { workspace = true } +futures-timer = { workspace = true } +gum = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-node-subsystem-util = { workspace = true, default-features = true } +polkadot-node-network-protocol = { workspace = true, default-features = true } +rand = { workspace = true, default-features = true } [dev-dependencies] -polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } -bitvec = { version = "1.0.0", default-features = false, features = ["alloc"] } -sp-core = { path = "../../../../substrate/primitives/core" } -sp-application-crypto = { path = "../../../../substrate/primitives/application-crypto" } -sp-authority-discovery = { path = "../../../../substrate/primitives/authority-discovery" } -sp-keystore = { path = "../../../../substrate/primitives/keystore" } -sp-keyring = { path = "../../../../substrate/primitives/keyring" } -maplit = "1.0.2" +polkadot-node-subsystem-test-helpers = { workspace = true } +bitvec = { features = ["alloc"], workspace = true } +sp-core = { workspace = true, default-features = true } +sp-application-crypto = { workspace = true, default-features = true } +sp-authority-discovery = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +maplit = { workspace = true } log = { workspace = true, default-features = true } -env_logger = "0.11" -assert_matches = "1.4.0" -rand_chacha = "0.3.1" +env_logger = { workspace = true } +assert_matches = { workspace = true } +rand_chacha = { workspace = true, default-features = true } diff --git a/polkadot/node/network/bridge/Cargo.toml b/polkadot/node/network/bridge/Cargo.toml index cd4e00ee1e4c596ed8c9798fd0009c95f6950a93..b4b5743853cd6dc2b43cce5d6b8c4d63bb893c8b 100644 --- a/polkadot/node/network/bridge/Cargo.toml +++ b/polkadot/node/network/bridge/Cargo.toml @@ -10,28 +10,28 @@ license.workspace = true workspace = true [dependencies] -always-assert = "0.1" -async-trait = "0.1.79" -futures = "0.3.30" -gum = { package = "tracing-gum", path = "../../gum" } -polkadot-primitives = { path = "../../../primitives" } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -sc-network = { path = "../../../../substrate/client/network" } -sp-consensus = { path = "../../../../substrate/primitives/consensus/common" } -polkadot-node-metrics = { path = "../../metrics" } -polkadot-node-network-protocol = { path = "../protocol" } -polkadot-node-subsystem = { path = "../../subsystem" } -polkadot-overseer = { path = "../../overseer" } -parking_lot = "0.12.1" -bytes = "1" -fatality = "0.1.1" +always-assert = { workspace = true } +async-trait = { workspace = true } +futures = { workspace = true } +gum = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +codec = { features = ["derive"], workspace = true } +sc-network = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +polkadot-node-metrics = { workspace = true, default-features = true } +polkadot-node-network-protocol = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-overseer = { workspace = true, default-features = true } +parking_lot = { workspace = true, default-features = true } +bytes = { workspace = true, default-features = true } +fatality = { workspace = true } thiserror = { workspace = true } [dev-dependencies] -assert_matches = "1.4.0" -polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } -polkadot-node-subsystem-util = { path = "../../subsystem-util" } -sp-core = { path = "../../../../substrate/primitives/core" } -sp-keyring = { path = "../../../../substrate/primitives/keyring" } -futures-timer = "3" -polkadot-primitives-test-helpers = { path = "../../../primitives/test-helpers" } +assert_matches = { workspace = true } +polkadot-node-subsystem-test-helpers = { workspace = true } +polkadot-node-subsystem-util = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +futures-timer = { workspace = true } +polkadot-primitives-test-helpers = { workspace = true } diff --git a/polkadot/node/network/bridge/src/validator_discovery.rs b/polkadot/node/network/bridge/src/validator_discovery.rs index b11af8a8a089c4aa64b26312562636b039068a78..f0ef038d5eb40708165f41dcdc5310b5dd44c951 100644 --- a/polkadot/node/network/bridge/src/validator_discovery.rs +++ b/polkadot/node/network/bridge/src/validator_discovery.rs @@ -88,16 +88,6 @@ impl Service { { gum::warn!(target: LOG_TARGET, err = ?e, "AuthorityDiscoveryService returned an invalid multiaddress"); } - // the addresses are known to be valid - // - // for peer-set management, the main protocol name should be used regardless of - // the negotiated version. - let _ = network_service - .remove_from_peers_set( - self.peerset_protocol_names.get_main_name(peer_set), - peers_to_remove, - ) - .await; network_service } diff --git a/polkadot/node/network/collator-protocol/Cargo.toml b/polkadot/node/network/collator-protocol/Cargo.toml index a56c1c7dfe9865dd82b78dda40a5e3aec228daf3..d41fc7ebe8ddb292aadd281c0b34288d8eb49e10 100644 --- a/polkadot/node/network/collator-protocol/Cargo.toml +++ b/polkadot/node/network/collator-protocol/Cargo.toml @@ -10,38 +10,38 @@ license.workspace = true workspace = true [dependencies] -bitvec = { version = "1.0.1", default-features = false, features = ["alloc"] } -futures = "0.3.30" -futures-timer = "3" -gum = { package = "tracing-gum", path = "../../gum" } - -sp-core = { path = "../../../../substrate/primitives/core" } -sp-runtime = { path = "../../../../substrate/primitives/runtime" } -sp-keystore = { path = "../../../../substrate/primitives/keystore" } - -polkadot-primitives = { path = "../../../primitives" } -polkadot-node-network-protocol = { path = "../protocol" } -polkadot-node-primitives = { path = "../../primitives" } -polkadot-node-subsystem-util = { path = "../../subsystem-util" } -polkadot-node-subsystem = { path = "../../subsystem" } -fatality = "0.1.1" +bitvec = { features = ["alloc"], workspace = true } +futures = { workspace = true } +futures-timer = { workspace = true } +gum = { workspace = true, default-features = true } + +sp-core = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } + +polkadot-primitives = { workspace = true, default-features = true } +polkadot-node-network-protocol = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-node-subsystem-util = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +fatality = { workspace = true } thiserror = { workspace = true } -tokio-util = "0.7.1" +tokio-util = { workspace = true } [dev-dependencies] log = { workspace = true, default-features = true } -env_logger = "0.11" -assert_matches = "1.4.0" -rstest = "0.18.2" - -sp-core = { path = "../../../../substrate/primitives/core", features = ["std"] } -sp-keyring = { path = "../../../../substrate/primitives/keyring" } -sc-keystore = { path = "../../../../substrate/client/keystore" } -sc-network = { path = "../../../../substrate/client/network" } -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["std"] } - -polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } -polkadot-primitives-test-helpers = { path = "../../../primitives/test-helpers" } +env_logger = { workspace = true } +assert_matches = { workspace = true } +rstest = { workspace = true } + +sp-core = { features = ["std"], workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +sc-keystore = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +codec = { features = ["std"], workspace = true, default-features = true } + +polkadot-node-subsystem-test-helpers = { workspace = true } +polkadot-primitives-test-helpers = { workspace = true } [features] default = [] diff --git a/polkadot/node/network/collator-protocol/src/collator_side/mod.rs b/polkadot/node/network/collator-protocol/src/collator_side/mod.rs index 80a85420b392b930f451689f22edffb4667a0588..5c201542eb560641c39c19cece9cc23fe076c90a 100644 --- a/polkadot/node/network/collator-protocol/src/collator_side/mod.rs +++ b/polkadot/node/network/collator-protocol/src/collator_side/mod.rs @@ -51,6 +51,7 @@ use polkadot_node_subsystem_util::{ get_availability_cores, get_group_rotation_info, prospective_parachains_mode, ProspectiveParachainsMode, RuntimeInfo, }, + vstaging::fetch_claim_queue, TimeoutExt, }; use polkadot_primitives::{ @@ -579,22 +580,27 @@ async fn determine_cores( let cores = get_availability_cores(sender, relay_parent).await?; let n_cores = cores.len(); let mut assigned_cores = Vec::new(); + let maybe_claim_queue = fetch_claim_queue(sender, relay_parent).await?; for (idx, core) in cores.iter().enumerate() { - let core_para_id = match core { - CoreState::Scheduled(scheduled) => Some(scheduled.para_id), - CoreState::Occupied(occupied) => - if relay_parent_mode.is_enabled() { - // With async backing we don't care about the core state, - // it is only needed for figuring our validators group. - Some(occupied.candidate_descriptor.para_id) - } else { - None - }, - CoreState::Free => None, + let core_is_scheduled = match maybe_claim_queue { + Some(ref claim_queue) => { + // Runtime supports claim queue - use it. + claim_queue + .iter_claims_for_core(&CoreIndex(idx as u32)) + .any(|para| para == ¶_id) + }, + None => match core { + CoreState::Scheduled(scheduled) if scheduled.para_id == para_id => true, + CoreState::Occupied(occupied) if relay_parent_mode.is_enabled() => + // With async backing we don't care about the core state, + // it is only needed for figuring our validators group. + occupied.next_up_on_available.as_ref().map(|c| c.para_id) == Some(para_id), + _ => false, + }, }; - if core_para_id == Some(para_id) { + if core_is_scheduled { assigned_cores.push(CoreIndex::from(idx as u32)); } } diff --git a/polkadot/node/network/collator-protocol/src/collator_side/tests/mod.rs b/polkadot/node/network/collator-protocol/src/collator_side/tests/mod.rs index a13e99df4ab477f14f09c147f31c8ea8eeeda7e4..13601ca7a0056508f06fdd3f2ed717ee4d2ea4b4 100644 --- a/polkadot/node/network/collator-protocol/src/collator_side/tests/mod.rs +++ b/polkadot/node/network/collator-protocol/src/collator_side/tests/mod.rs @@ -16,7 +16,11 @@ use super::*; -use std::{collections::HashSet, sync::Arc, time::Duration}; +use std::{ + collections::{BTreeMap, HashSet, VecDeque}, + sync::Arc, + time::Duration, +}; use assert_matches::assert_matches; use futures::{executor, future, Future}; @@ -66,7 +70,7 @@ struct TestState { group_rotation_info: GroupRotationInfo, validator_peer_id: Vec, relay_parent: Hash, - availability_cores: Vec, + claim_queue: BTreeMap>, local_peer_id: PeerId, collator_pair: CollatorPair, session_index: SessionIndex, @@ -105,8 +109,9 @@ impl Default for TestState { let group_rotation_info = GroupRotationInfo { session_start_block: 0, group_rotation_frequency: 100, now: 1 }; - let availability_cores = - vec![CoreState::Scheduled(ScheduledCore { para_id, collator: None }), CoreState::Free]; + let mut claim_queue = BTreeMap::new(); + claim_queue.insert(CoreIndex(0), [para_id].into_iter().collect()); + claim_queue.insert(CoreIndex(1), VecDeque::new()); let relay_parent = Hash::random(); @@ -133,7 +138,7 @@ impl Default for TestState { group_rotation_info, validator_peer_id, relay_parent, - availability_cores, + claim_queue, local_peer_id, collator_pair, session_index: 1, @@ -147,17 +152,14 @@ impl TestState { pub fn with_elastic_scaling() -> Self { let mut state = Self::default(); let para_id = state.para_id; - state - .availability_cores - .push(CoreState::Scheduled(ScheduledCore { para_id, collator: None })); - state - .availability_cores - .push(CoreState::Scheduled(ScheduledCore { para_id, collator: None })); + + state.claim_queue.insert(CoreIndex(2), [para_id].into_iter().collect()); + state.claim_queue.insert(CoreIndex(3), [para_id].into_iter().collect()); state } fn current_group_validator_indices(&self) -> &[ValidatorIndex] { - let core_num = self.availability_cores.len(); + let core_num = self.claim_queue.len(); let GroupIndex(group_idx) = self.group_rotation_info.group_for_core(CoreIndex(0), core_num); &self.session_info.validator_groups.get(GroupIndex::from(group_idx)).unwrap() } @@ -395,7 +397,36 @@ async fn distribute_collation_with_receipt( RuntimeApiRequest::AvailabilityCores(tx) )) => { assert_eq!(relay_parent, _relay_parent); - tx.send(Ok(test_state.availability_cores.clone())).unwrap(); + tx.send(Ok(test_state.claim_queue.values().map(|paras| + if let Some(para) = paras.front() { + CoreState::Scheduled(ScheduledCore { para_id: *para, collator: None }) + } else { + CoreState::Free + } + ).collect())).unwrap(); + } + ); + + assert_matches!( + overseer_recv(virtual_overseer).await, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( + _relay_parent, + RuntimeApiRequest::Version(tx) + )) => { + assert_eq!(relay_parent, _relay_parent); + tx.send(Ok(RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT)).unwrap(); + } + ); + + // obtain the claim queue schedule. + assert_matches!( + overseer_recv(virtual_overseer).await, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( + _relay_parent, + RuntimeApiRequest::ClaimQueue(tx) + )) => { + assert_eq!(relay_parent, _relay_parent); + tx.send(Ok(test_state.claim_queue.clone())).unwrap(); } ); diff --git a/polkadot/node/network/collator-protocol/src/collator_side/tests/prospective_parachains.rs b/polkadot/node/network/collator-protocol/src/collator_side/tests/prospective_parachains.rs index 0a0a85fb1f2750a54c909b523ab54564652d3354..ea8fdb0e04fbe0ba29303b62ae1d45c63d43cdf4 100644 --- a/polkadot/node/network/collator-protocol/src/collator_side/tests/prospective_parachains.rs +++ b/polkadot/node/network/collator-protocol/src/collator_side/tests/prospective_parachains.rs @@ -19,7 +19,7 @@ use super::*; use polkadot_node_subsystem::messages::ChainApiMessage; -use polkadot_primitives::{AsyncBackingParams, Header, OccupiedCore}; +use polkadot_primitives::{AsyncBackingParams, Header}; const ASYNC_BACKING_PARAMETERS: AsyncBackingParams = AsyncBackingParams { max_candidate_depth: 4, allowed_ancestry_len: 3 }; @@ -665,90 +665,3 @@ fn advertise_and_send_collation_by_hash() { }, ) } - -/// Tests that collator distributes collation built on top of occupied core. -#[test] -fn advertise_core_occupied() { - let mut test_state = TestState::default(); - let candidate = - TestCandidateBuilder { para_id: test_state.para_id, ..Default::default() }.build(); - test_state.availability_cores[0] = CoreState::Occupied(OccupiedCore { - next_up_on_available: None, - occupied_since: 0, - time_out_at: 0, - next_up_on_time_out: None, - availability: BitVec::default(), - group_responsible: GroupIndex(0), - candidate_hash: candidate.hash(), - candidate_descriptor: candidate.descriptor, - }); - - let local_peer_id = test_state.local_peer_id; - let collator_pair = test_state.collator_pair.clone(); - - test_harness( - local_peer_id, - collator_pair, - ReputationAggregator::new(|_| true), - |mut test_harness| async move { - let virtual_overseer = &mut test_harness.virtual_overseer; - - let head_a = Hash::from_low_u64_be(128); - let head_a_num: u32 = 64; - - // Grandparent of head `a`. - let head_b = Hash::from_low_u64_be(130); - - // Set collating para id. - overseer_send(virtual_overseer, CollatorProtocolMessage::CollateOn(test_state.para_id)) - .await; - // Activated leaf is `a`, but the collation will be based on `b`. - update_view(virtual_overseer, vec![(head_a, head_a_num)], 1).await; - - let pov = PoV { block_data: BlockData(vec![1, 2, 3]) }; - let candidate = TestCandidateBuilder { - para_id: test_state.para_id, - relay_parent: head_b, - pov_hash: pov.hash(), - ..Default::default() - } - .build(); - let candidate_hash = candidate.hash(); - distribute_collation_with_receipt( - virtual_overseer, - &test_state, - head_b, - true, - candidate, - pov, - Hash::zero(), - ) - .await; - - let validators = test_state.current_group_validator_authority_ids(); - let peer_ids = test_state.current_group_validator_peer_ids(); - - connect_peer( - virtual_overseer, - peer_ids[0], - CollationVersion::V2, - Some(validators[0].clone()), - ) - .await; - expect_declare_msg_v2(virtual_overseer, &test_state, &peer_ids[0]).await; - // Peer is aware of the leaf. - send_peer_view_change(virtual_overseer, &peer_ids[0], vec![head_a]).await; - - // Collation is advertised. - expect_advertise_collation_msg( - virtual_overseer, - &peer_ids[0], - head_b, - Some(vec![candidate_hash]), - ) - .await; - - test_harness - }, - ) -} diff --git a/polkadot/node/network/collator-protocol/src/validator_side/collation.rs b/polkadot/node/network/collator-protocol/src/validator_side/collation.rs index 001df1fb3da9b24a3c1acffc049cc7433903aea8..96ffe9f13db3562429eb68cdfdc05da801c33863 100644 --- a/polkadot/node/network/collator-protocol/src/validator_side/collation.rs +++ b/polkadot/node/network/collator-protocol/src/validator_side/collation.rs @@ -270,7 +270,7 @@ impl Collations { // We don't need to fetch any other collation when we already have seconded one. CollationStatus::Seconded => None, CollationStatus::Waiting => - if !self.is_seconded_limit_reached(relay_parent_mode) { + if self.is_seconded_limit_reached(relay_parent_mode) { None } else { self.waiting_queue.pop_front() @@ -280,7 +280,7 @@ impl Collations { } } - /// Checks the limit of seconded candidates for a given para. + /// Checks the limit of seconded candidates. pub(super) fn is_seconded_limit_reached( &self, relay_parent_mode: ProspectiveParachainsMode, @@ -293,7 +293,7 @@ impl Collations { } else { 1 }; - self.seconded_count < seconded_limit + self.seconded_count >= seconded_limit } } diff --git a/polkadot/node/network/collator-protocol/src/validator_side/mod.rs b/polkadot/node/network/collator-protocol/src/validator_side/mod.rs index 9f037a983e51c33cb734ee65fc496541d1082bf2..f5c9726f3f6a509a4966720f5e2011d173a9d318 100644 --- a/polkadot/node/network/collator-protocol/src/validator_side/mod.rs +++ b/polkadot/node/network/collator-protocol/src/validator_side/mod.rs @@ -19,7 +19,7 @@ use futures::{ }; use futures_timer::Delay; use std::{ - collections::{hash_map::Entry, HashMap, HashSet}, + collections::{hash_map::Entry, HashMap, HashSet, VecDeque}, future::Future, time::{Duration, Instant}, }; @@ -51,6 +51,7 @@ use polkadot_node_subsystem_util::{ backing_implicit_view::View as ImplicitView, reputation::{ReputationAggregator, REPUTATION_CHANGE_INTERVAL}, runtime::{prospective_parachains_mode, ProspectiveParachainsMode}, + vstaging::fetch_claim_queue, }; use polkadot_primitives::{ CandidateHash, CollatorId, CoreState, Hash, HeadData, Id as ParaId, OccupiedCoreAssumption, @@ -362,8 +363,8 @@ impl PeerData { #[derive(Debug)] struct GroupAssignments { - /// Current assignment. - current: Option, + /// Current assignments. + current: Vec, } struct PerRelayParent { @@ -376,7 +377,7 @@ impl PerRelayParent { fn new(mode: ProspectiveParachainsMode) -> Self { Self { prospective_parachains_mode: mode, - assignment: GroupAssignments { current: None }, + assignment: GroupAssignments { current: vec![] }, collations: Collations::default(), } } @@ -491,34 +492,34 @@ where .await .map_err(Error::CancelledAvailabilityCores)??; - let para_now = match polkadot_node_subsystem_util::signing_key_and_index(&validators, keystore) - .and_then(|(_, index)| polkadot_node_subsystem_util::find_validator_group(&groups, index)) - { - Some(group) => { - let core_now = rotation_info.core_for_group(group, cores.len()); - - cores.get(core_now.0 as usize).and_then(|c| match c { - CoreState::Occupied(core) if relay_parent_mode.is_enabled() => Some(core.para_id()), - CoreState::Scheduled(core) => Some(core.para_id), - CoreState::Occupied(_) | CoreState::Free => None, - }) - }, - None => { - gum::trace!(target: LOG_TARGET, ?relay_parent, "Not a validator"); - - return Ok(()) - }, + let core_now = if let Some(group) = + polkadot_node_subsystem_util::signing_key_and_index(&validators, keystore).and_then( + |(_, index)| polkadot_node_subsystem_util::find_validator_group(&groups, index), + ) { + rotation_info.core_for_group(group, cores.len()) + } else { + gum::trace!(target: LOG_TARGET, ?relay_parent, "Not a validator"); + return Ok(()) }; - // This code won't work well, if at all for on-demand parachains. For on-demand we'll - // have to be aware of which core the on-demand claim is going to be multiplexed - // onto. The on-demand claim will also have a known collator, and we should always - // allow an incoming connection from that collator. If not even connecting to them - // directly. - // - // However, this'll work fine for parachains, as each parachain gets a dedicated - // core. - if let Some(para_id) = para_now.as_ref() { + let paras_now = match fetch_claim_queue(sender, relay_parent).await.map_err(Error::Runtime)? { + // Runtime supports claim queue - use it + // + // `relay_parent_mode` is not examined here because if the runtime supports claim queue + // then it supports async backing params too (`ASYNC_BACKING_STATE_RUNTIME_REQUIREMENT` + // < `CLAIM_QUEUE_RUNTIME_REQUIREMENT`). + Some(mut claim_queue) => claim_queue.0.remove(&core_now), + // Claim queue is not supported by the runtime - use availability cores instead. + None => cores.get(core_now.0 as usize).and_then(|c| match c { + CoreState::Occupied(core) if relay_parent_mode.is_enabled() => + core.next_up_on_available.as_ref().map(|c| [c.para_id].into_iter().collect()), + CoreState::Scheduled(core) => Some([core.para_id].into_iter().collect()), + CoreState::Occupied(_) | CoreState::Free => None, + }), + } + .unwrap_or_else(|| VecDeque::new()); + + for para_id in paras_now.iter() { let entry = current_assignments.entry(*para_id).or_default(); *entry += 1; if *entry == 1 { @@ -531,7 +532,7 @@ where } } - *group_assignment = GroupAssignments { current: para_now }; + *group_assignment = GroupAssignments { current: paras_now.into_iter().collect() }; Ok(()) } @@ -542,7 +543,7 @@ fn remove_outgoing( ) { let GroupAssignments { current, .. } = per_relay_parent.assignment; - if let Some(cur) = current { + for cur in current { if let Entry::Occupied(mut occupied) = current_assignments.entry(cur) { *occupied.get_mut() -= 1; if *occupied.get() == 0 { @@ -857,7 +858,8 @@ async fn process_incoming_peer_message( peer_id = ?origin, ?collator_id, ?para_id, - "Declared as collator for unneeded para", + "Declared as collator for unneeded para. Current assignments: {:?}", + &state.current_assignments ); modify_reputation( @@ -1089,7 +1091,7 @@ where peer_data.collating_para().ok_or(AdvertisementError::UndeclaredCollator)?; // Check if this is assigned to us. - if assignment.current.map_or(true, |id| id != collator_para_id) { + if !assignment.current.contains(&collator_para_id) { return Err(AdvertisementError::InvalidAssignment) } @@ -1105,7 +1107,7 @@ where ) .map_err(AdvertisementError::Invalid)?; - if !per_relay_parent.collations.is_seconded_limit_reached(relay_parent_mode) { + if per_relay_parent.collations.is_seconded_limit_reached(relay_parent_mode) { return Err(AdvertisementError::SecondedLimitReached) } @@ -1197,7 +1199,7 @@ where }); let collations = &mut per_relay_parent.collations; - if !collations.is_seconded_limit_reached(relay_parent_mode) { + if collations.is_seconded_limit_reached(relay_parent_mode) { gum::trace!( target: LOG_TARGET, peer_id = ?peer_id, diff --git a/polkadot/node/network/collator-protocol/src/validator_side/tests/mod.rs b/polkadot/node/network/collator-protocol/src/validator_side/tests/mod.rs index 3f4459d8e65d1d092957273bb3c0a8b95b6648a8..44e25efd4dfcd30536fca2dc766dc1f18b1851b4 100644 --- a/polkadot/node/network/collator-protocol/src/validator_side/tests/mod.rs +++ b/polkadot/node/network/collator-protocol/src/validator_side/tests/mod.rs @@ -21,7 +21,12 @@ use sc_network::ProtocolName; use sp_core::{crypto::Pair, Encode}; use sp_keyring::Sr25519Keyring; use sp_keystore::Keystore; -use std::{iter, sync::Arc, time::Duration}; +use std::{ + collections::{BTreeMap, VecDeque}, + iter, + sync::Arc, + time::Duration, +}; use polkadot_node_network_protocol::{ our_view, @@ -37,7 +42,7 @@ use polkadot_node_subsystem::{ use polkadot_node_subsystem_test_helpers as test_helpers; use polkadot_node_subsystem_util::{reputation::add_reputation, TimeoutExt}; use polkadot_primitives::{ - CandidateReceipt, CollatorPair, CoreState, GroupIndex, GroupRotationInfo, HeadData, + CandidateReceipt, CollatorPair, CoreIndex, CoreState, GroupIndex, GroupRotationInfo, HeadData, OccupiedCore, PersistedValidationData, ScheduledCore, ValidatorId, ValidatorIndex, }; use polkadot_primitives_test_helpers::{ @@ -71,6 +76,7 @@ struct TestState { validator_groups: Vec>, group_rotation_info: GroupRotationInfo, cores: Vec, + claim_queue: BTreeMap>, } impl Default for TestState { @@ -104,7 +110,7 @@ impl Default for TestState { CoreState::Scheduled(ScheduledCore { para_id: chain_ids[0], collator: None }), CoreState::Free, CoreState::Occupied(OccupiedCore { - next_up_on_available: None, + next_up_on_available: Some(ScheduledCore { para_id: chain_ids[1], collator: None }), occupied_since: 0, time_out_at: 1, next_up_on_time_out: None, @@ -120,6 +126,11 @@ impl Default for TestState { }), ]; + let mut claim_queue = BTreeMap::new(); + claim_queue.insert(CoreIndex(0), [chain_ids[0]].into_iter().collect()); + claim_queue.insert(CoreIndex(1), VecDeque::new()); + claim_queue.insert(CoreIndex(2), [chain_ids[1]].into_iter().collect()); + Self { chain_ids, relay_parent, @@ -128,6 +139,7 @@ impl Default for TestState { validator_groups, group_rotation_info, cores, + claim_queue, } } } @@ -264,6 +276,26 @@ async fn respond_to_core_info_queries( let _ = tx.send(Ok(test_state.cores.clone())); } ); + + assert_matches!( + overseer_recv(virtual_overseer).await, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( + _, + RuntimeApiRequest::Version(tx), + )) => { + let _ = tx.send(Ok(RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT)); + } + ); + + assert_matches!( + overseer_recv(virtual_overseer).await, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( + _, + RuntimeApiRequest::ClaimQueue(tx), + )) => { + let _ = tx.send(Ok(test_state.claim_queue.clone())); + } + ); } /// Assert that the next message is a `CandidateBacking(Second())`. diff --git a/polkadot/node/network/collator-protocol/src/validator_side/tests/prospective_parachains.rs b/polkadot/node/network/collator-protocol/src/validator_side/tests/prospective_parachains.rs index 178dcb85e035f05c4136f7d7d7e2433a3713d00c..472731b506ab1c5d59a756a9e80b47016bcceb6c 100644 --- a/polkadot/node/network/collator-protocol/src/validator_side/tests/prospective_parachains.rs +++ b/polkadot/node/network/collator-protocol/src/validator_side/tests/prospective_parachains.rs @@ -72,6 +72,26 @@ async fn assert_assign_incoming( tx.send(Ok(test_state.cores.clone())).unwrap(); } ); + + assert_matches!( + overseer_recv(virtual_overseer).await, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( + parent, + RuntimeApiRequest::Version(tx), + )) if parent == hash => { + let _ = tx.send(Ok(RuntimeApiRequest::CLAIM_QUEUE_RUNTIME_REQUIREMENT)); + } + ); + + assert_matches!( + overseer_recv(virtual_overseer).await, + AllMessages::RuntimeApi(RuntimeApiMessage::Request( + parent, + RuntimeApiRequest::ClaimQueue(tx), + )) if parent == hash => { + let _ = tx.send(Ok(test_state.claim_queue.clone())); + } + ); } /// Handle a view update. diff --git a/polkadot/node/network/dispute-distribution/Cargo.toml b/polkadot/node/network/dispute-distribution/Cargo.toml index 08713209bb740737df26e36d2f4df7933914406b..ccf1b5daad7c3b7f3dd7d5525cb619781c01bce8 100644 --- a/polkadot/node/network/dispute-distribution/Cargo.toml +++ b/polkadot/node/network/dispute-distribution/Cargo.toml @@ -10,33 +10,33 @@ license.workspace = true workspace = true [dependencies] -futures = "0.3.30" -futures-timer = "3.0.2" -gum = { package = "tracing-gum", path = "../../gum" } -derive_more = "0.99.17" -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["std"] } -polkadot-primitives = { path = "../../../primitives" } -polkadot-erasure-coding = { path = "../../../erasure-coding" } -polkadot-node-subsystem = { path = "../../subsystem" } -polkadot-node-network-protocol = { path = "../protocol" } -polkadot-node-subsystem-util = { path = "../../subsystem-util" } -polkadot-node-primitives = { path = "../../primitives" } -sc-network = { path = "../../../../substrate/client/network" } -sp-application-crypto = { path = "../../../../substrate/primitives/application-crypto" } -sp-keystore = { path = "../../../../substrate/primitives/keystore" } +futures = { workspace = true } +futures-timer = { workspace = true } +gum = { workspace = true, default-features = true } +derive_more = { workspace = true, default-features = true } +codec = { features = ["std"], workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-erasure-coding = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-node-network-protocol = { workspace = true, default-features = true } +polkadot-node-subsystem-util = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sp-application-crypto = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } thiserror = { workspace = true } -fatality = "0.1.1" -schnellru = "0.2.1" -indexmap = "2.0.0" +fatality = { workspace = true } +schnellru = { workspace = true } +indexmap = { workspace = true } [dev-dependencies] -async-channel = "1.8.0" -async-trait = "0.1.79" -polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } -sp-keyring = { path = "../../../../substrate/primitives/keyring" } -sp-tracing = { path = "../../../../substrate/primitives/tracing" } -sc-keystore = { path = "../../../../substrate/client/keystore" } -futures-timer = "3.0.2" -assert_matches = "1.4.0" -lazy_static = "1.4.0" -polkadot-primitives-test-helpers = { path = "../../../primitives/test-helpers" } +async-channel = { workspace = true } +async-trait = { workspace = true } +polkadot-node-subsystem-test-helpers = { workspace = true } +sp-keyring = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +sc-keystore = { workspace = true, default-features = true } +futures-timer = { workspace = true } +assert_matches = { workspace = true } +lazy_static = { workspace = true } +polkadot-primitives-test-helpers = { workspace = true } diff --git a/polkadot/node/network/gossip-support/Cargo.toml b/polkadot/node/network/gossip-support/Cargo.toml index 2d6f2f954c667a8a97aff093f1fa734f6afce9aa..83fdc7e26191e6b2568a9733b163a0f0239f6709 100644 --- a/polkadot/node/network/gossip-support/Cargo.toml +++ b/polkadot/node/network/gossip-support/Cargo.toml @@ -10,34 +10,34 @@ license.workspace = true workspace = true [dependencies] -sp-application-crypto = { path = "../../../../substrate/primitives/application-crypto" } -sp-keystore = { path = "../../../../substrate/primitives/keystore" } -sp-core = { path = "../../../../substrate/primitives/core" } -sp-crypto-hashing = { path = "../../../../substrate/primitives/crypto/hashing" } -sc-network = { path = "../../../../substrate/client/network" } -sc-network-common = { path = "../../../../substrate/client/network/common" } +sp-application-crypto = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-crypto-hashing = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sc-network-common = { workspace = true, default-features = true } -polkadot-node-network-protocol = { path = "../protocol" } -polkadot-node-subsystem = { path = "../../subsystem" } -polkadot-node-subsystem-util = { path = "../../subsystem-util" } -polkadot-primitives = { path = "../../../primitives" } +polkadot-node-network-protocol = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-node-subsystem-util = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } -futures = "0.3.30" -futures-timer = "3.0.2" -rand = { version = "0.8.5", default-features = false } -rand_chacha = { version = "0.3.1", default-features = false } -gum = { package = "tracing-gum", path = "../../gum" } +futures = { workspace = true } +futures-timer = { workspace = true } +rand = { workspace = true } +rand_chacha = { workspace = true } +gum = { workspace = true, default-features = true } [dev-dependencies] -sp-keyring = { path = "../../../../substrate/primitives/keyring" } -sp-consensus-babe = { path = "../../../../substrate/primitives/consensus/babe" } -sp-tracing = { path = "../../../../substrate/primitives/tracing" } -sp-authority-discovery = { path = "../../../../substrate/primitives/authority-discovery" } +sp-keyring = { workspace = true, default-features = true } +sp-consensus-babe = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +sp-authority-discovery = { workspace = true, default-features = true } -polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } +polkadot-node-subsystem-test-helpers = { workspace = true } -assert_matches = "1.4.0" -async-trait = "0.1.79" -parking_lot = "0.12.1" -lazy_static = "1.4.0" -quickcheck = "1.0.3" +assert_matches = { workspace = true } +async-trait = { workspace = true } +parking_lot = { workspace = true, default-features = true } +lazy_static = { workspace = true } +quickcheck = { workspace = true, default-features = true } diff --git a/polkadot/node/network/protocol/Cargo.toml b/polkadot/node/network/protocol/Cargo.toml index 83145ce4013022b5567d45434c989bba732382c7..c9ae23d756cfc4d39d44286b7a567ed46969bf02 100644 --- a/polkadot/node/network/protocol/Cargo.toml +++ b/polkadot/node/network/protocol/Cargo.toml @@ -10,25 +10,25 @@ description = "Primitives types for the Node-side" workspace = true [dependencies] -async-channel = "1.8.0" -async-trait = "0.1.79" -hex = "0.4.3" -polkadot-primitives = { path = "../../../primitives" } -polkadot-node-primitives = { path = "../../primitives" } -polkadot-node-jaeger = { path = "../../jaeger" } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -sc-network = { path = "../../../../substrate/client/network" } -sc-network-types = { path = "../../../../substrate/client/network/types" } -sc-authority-discovery = { path = "../../../../substrate/client/authority-discovery" } -sp-runtime = { path = "../../../../substrate/primitives/runtime" } -strum = { version = "0.26.2", features = ["derive"] } -futures = "0.3.30" +async-channel = { workspace = true } +async-trait = { workspace = true } +hex = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-node-jaeger = { workspace = true, default-features = true } +codec = { features = ["derive"], workspace = true } +sc-network = { workspace = true, default-features = true } +sc-network-types = { workspace = true, default-features = true } +sc-authority-discovery = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +strum = { features = ["derive"], workspace = true, default-features = true } +futures = { workspace = true } thiserror = { workspace = true } -fatality = "0.1.1" -rand = "0.8" -derive_more = "0.99" -gum = { package = "tracing-gum", path = "../../gum" } -bitvec = "1" +fatality = { workspace = true } +rand = { workspace = true, default-features = true } +derive_more = { workspace = true, default-features = true } +gum = { workspace = true, default-features = true } +bitvec = { workspace = true, default-features = true } [dev-dependencies] -rand_chacha = "0.3.1" +rand_chacha = { workspace = true, default-features = true } diff --git a/polkadot/node/network/statement-distribution/Cargo.toml b/polkadot/node/network/statement-distribution/Cargo.toml index b044acd1a86d372019cd93b1c628601ae43a465d..2a9773ddde4bd316d3133086131399829ffc5626 100644 --- a/polkadot/node/network/statement-distribution/Cargo.toml +++ b/polkadot/node/network/statement-distribution/Cargo.toml @@ -10,39 +10,39 @@ license.workspace = true workspace = true [dependencies] -futures = "0.3.30" -futures-timer = "3.0.2" -gum = { package = "tracing-gum", path = "../../gum" } -polkadot-primitives = { path = "../../../primitives" } -sp-staking = { path = "../../../../substrate/primitives/staking", default-features = false } -sp-keystore = { path = "../../../../substrate/primitives/keystore" } -polkadot-node-subsystem = { path = "../../subsystem" } -polkadot-node-primitives = { path = "../../primitives" } -polkadot-node-subsystem-util = { path = "../../subsystem-util" } -polkadot-node-network-protocol = { path = "../protocol" } -arrayvec = "0.7.4" -indexmap = "2.0.0" -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +futures = { workspace = true } +futures-timer = { workspace = true } +gum = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +sp-staking = { workspace = true } +sp-keystore = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-node-subsystem-util = { workspace = true, default-features = true } +polkadot-node-network-protocol = { workspace = true, default-features = true } +arrayvec = { workspace = true } +indexmap = { workspace = true } +codec = { features = ["derive"], workspace = true } thiserror = { workspace = true } -fatality = "0.1.1" -bitvec = "1" +fatality = { workspace = true } +bitvec = { workspace = true, default-features = true } [dev-dependencies] -async-channel = "1.8.0" -assert_matches = "1.4.0" -polkadot-node-subsystem-test-helpers = { path = "../../subsystem-test-helpers" } -sp-authority-discovery = { path = "../../../../substrate/primitives/authority-discovery" } -sp-keyring = { path = "../../../../substrate/primitives/keyring" } -sp-core = { path = "../../../../substrate/primitives/core" } -sp-application-crypto = { path = "../../../../substrate/primitives/application-crypto" } -sp-keystore = { path = "../../../../substrate/primitives/keystore" } -sp-tracing = { path = "../../../../substrate/primitives/tracing" } -sc-keystore = { path = "../../../../substrate/client/keystore" } -sc-network = { path = "../../../../substrate/client/network" } -futures-timer = "3.0.2" -polkadot-primitives-test-helpers = { path = "../../../primitives/test-helpers" } -rand_chacha = "0.3" -polkadot-subsystem-bench = { path = "../../subsystem-bench" } +async-channel = { workspace = true } +assert_matches = { workspace = true } +polkadot-node-subsystem-test-helpers = { workspace = true } +sp-authority-discovery = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-application-crypto = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +sc-keystore = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +futures-timer = { workspace = true } +polkadot-primitives-test-helpers = { workspace = true } +rand_chacha = { workspace = true, default-features = true } +polkadot-subsystem-bench = { workspace = true } [[bench]] name = "statement-distribution-regression-bench" diff --git a/polkadot/node/network/statement-distribution/src/v2/mod.rs b/polkadot/node/network/statement-distribution/src/v2/mod.rs index 73416b193bbec518fa24e608bdfc17c9de436b50..2bb9c82c6a6fa00a84b5274a12f7e79398ca89f3 100644 --- a/polkadot/node/network/statement-distribution/src/v2/mod.rs +++ b/polkadot/node/network/statement-distribution/src/v2/mod.rs @@ -195,8 +195,8 @@ struct ActiveValidatorState { index: ValidatorIndex, // our validator group group: GroupIndex, - // the assignment of our validator group, if any. - assignment: Option, + // the assignments of our validator group, if any. + assignments: Vec, // the 'direct-in-group' communication at this relay-parent. cluster_tracker: ClusterTracker, } @@ -740,8 +740,8 @@ fn find_active_validator_state( let our_group = groups.by_validator_index(validator_index)?; let core_index = group_rotation_info.core_for_group(our_group, availability_cores.len()); - let para_assigned_to_core = if let Some(claim_queue) = maybe_claim_queue { - claim_queue.get_claim_for(core_index, 0) + let paras_assigned_to_core = if let Some(claim_queue) = maybe_claim_queue { + claim_queue.iter_claims_for_core(&core_index).copied().collect() } else { availability_cores .get(core_index.0 as usize) @@ -753,6 +753,8 @@ fn find_active_validator_state( .map(|scheduled_core| scheduled_core.para_id), CoreState::Free | CoreState::Occupied(_) => None, }) + .into_iter() + .collect() }; let group_validators = groups.get(our_group)?.to_owned(); @@ -760,7 +762,7 @@ fn find_active_validator_state( active: Some(ActiveValidatorState { index: validator_index, group: our_group, - assignment: para_assigned_to_core, + assignments: paras_assigned_to_core, cluster_tracker: ClusterTracker::new(group_validators, seconding_limit) .expect("group is non-empty because we are in it; qed"), }), @@ -1162,10 +1164,10 @@ pub(crate) async fn share_local_statement( None => return Ok(()), }; - let (local_index, local_assignment, local_group) = + let (local_index, local_assignments, local_group) = match per_relay_parent.active_validator_state() { None => return Err(JfyiError::InvalidShare), - Some(l) => (l.index, l.assignment, l.group), + Some(l) => (l.index, &l.assignments, l.group), }; // Two possibilities: either the statement is `Seconded` or we already @@ -1203,7 +1205,7 @@ pub(crate) async fn share_local_statement( return Err(JfyiError::InvalidShare) } - if local_assignment != Some(expected_para) || relay_parent != expected_relay_parent { + if !local_assignments.contains(&expected_para) || relay_parent != expected_relay_parent { return Err(JfyiError::InvalidShare) } @@ -2144,12 +2146,11 @@ async fn determine_groups_per_para( let n_cores = availability_cores.len(); // Determine the core indices occupied by each para at the current relay parent. To support - // on-demand parachains we also consider the core indices at next block if core has a candidate - // pending availability. - let para_core_indices: Vec<_> = if let Some(claim_queue) = maybe_claim_queue { + // on-demand parachains we also consider the core indices at next blocks. + let schedule: HashMap> = if let Some(claim_queue) = maybe_claim_queue { claim_queue - .iter_claims_at_depth(0) - .map(|(core_index, para)| (para, core_index)) + .iter_all_claims() + .map(|(core_index, paras)| (*core_index, paras.iter().copied().collect())) .collect() } else { availability_cores @@ -2157,12 +2158,12 @@ async fn determine_groups_per_para( .enumerate() .filter_map(|(index, core)| match core { CoreState::Scheduled(scheduled_core) => - Some((scheduled_core.para_id, CoreIndex(index as u32))), + Some((CoreIndex(index as u32), vec![scheduled_core.para_id])), CoreState::Occupied(occupied_core) => if max_candidate_depth >= 1 { - occupied_core - .next_up_on_available - .map(|scheduled_core| (scheduled_core.para_id, CoreIndex(index as u32))) + occupied_core.next_up_on_available.map(|scheduled_core| { + (CoreIndex(index as u32), vec![scheduled_core.para_id]) + }) } else { None }, @@ -2173,9 +2174,12 @@ async fn determine_groups_per_para( let mut groups_per_para = HashMap::new(); // Map from `CoreIndex` to `GroupIndex` and collect as `HashMap`. - for (para, core_index) in para_core_indices { + for (core_index, paras) in schedule { let group_index = group_rotation_info.group_for_core(core_index, n_cores); - groups_per_para.entry(para).or_insert_with(Vec::new).push(group_index) + + for para in paras { + groups_per_para.entry(para).or_insert_with(Vec::new).push(group_index); + } } groups_per_para diff --git a/polkadot/node/overseer/Cargo.toml b/polkadot/node/overseer/Cargo.toml index e77cead4a7565de9afd71d484c57e9fddc4e2d00..2253a5ae0c668c0c107f19ad15ef933c1cf17abc 100644 --- a/polkadot/node/overseer/Cargo.toml +++ b/polkadot/node/overseer/Cargo.toml @@ -10,30 +10,30 @@ description = "System overseer of the Polkadot node" workspace = true [dependencies] -sc-client-api = { path = "../../../substrate/client/api" } -sp-api = { path = "../../../substrate/primitives/api" } -futures = "0.3.30" -futures-timer = "3.0.2" -parking_lot = "0.12.1" -polkadot-node-network-protocol = { path = "../network/protocol" } -polkadot-node-primitives = { path = "../primitives" } -polkadot-node-subsystem-types = { path = "../subsystem-types" } -polkadot-node-metrics = { path = "../metrics" } -polkadot-primitives = { path = "../../primitives" } -orchestra = { version = "0.3.5", default-features = false, features = ["futures_channel"] } -gum = { package = "tracing-gum", path = "../gum" } -sp-core = { path = "../../../substrate/primitives/core" } -async-trait = "0.1.79" -tikv-jemalloc-ctl = { version = "0.5.0", optional = true } +sc-client-api = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +futures = { workspace = true } +futures-timer = { workspace = true } +parking_lot = { workspace = true, default-features = true } +polkadot-node-network-protocol = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-node-subsystem-types = { workspace = true, default-features = true } +polkadot-node-metrics = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +orchestra = { features = ["futures_channel"], workspace = true } +gum = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +async-trait = { workspace = true } +tikv-jemalloc-ctl = { optional = true, workspace = true } [dev-dependencies] -metered = { package = "prioritized-metered-channel", version = "0.6.1", default-features = false, features = ["futures_channel"] } -sp-core = { path = "../../../substrate/primitives/core" } -futures = { version = "0.3.30", features = ["thread-pool"] } -femme = "2.2.1" -assert_matches = "1.4.0" -polkadot-primitives-test-helpers = { path = "../../primitives/test-helpers" } -polkadot-node-subsystem-test-helpers = { path = "../subsystem-test-helpers" } +metered = { features = ["futures_channel"], workspace = true } +sp-core = { workspace = true, default-features = true } +futures = { features = ["thread-pool"], workspace = true } +femme = { workspace = true } +assert_matches = { workspace = true } +polkadot-primitives-test-helpers = { workspace = true } +polkadot-node-subsystem-test-helpers = { workspace = true } [target.'cfg(target_os = "linux")'.dependencies] tikv-jemalloc-ctl = "0.5.0" diff --git a/polkadot/node/primitives/Cargo.toml b/polkadot/node/primitives/Cargo.toml index 0a84e5dae2a589ef5cd165ce2825bf811751af94..cd642bf16ff9bf7d6ffeeea2ce0dac752128bd3c 100644 --- a/polkadot/node/primitives/Cargo.toml +++ b/polkadot/node/primitives/Cargo.toml @@ -10,24 +10,24 @@ license.workspace = true workspace = true [dependencies] -bounded-vec = "0.7" -futures = "0.3.30" -polkadot-primitives = { path = "../../primitives" } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -sp-core = { path = "../../../substrate/primitives/core" } -sp-application-crypto = { path = "../../../substrate/primitives/application-crypto" } -sp-consensus-babe = { path = "../../../substrate/primitives/consensus/babe" } -sp-keystore = { path = "../../../substrate/primitives/keystore" } -sp-maybe-compressed-blob = { path = "../../../substrate/primitives/maybe-compressed-blob" } -sp-runtime = { path = "../../../substrate/primitives/runtime" } -polkadot-parachain-primitives = { path = "../../parachain", default-features = false } -schnorrkel = "0.11.4" +bounded-vec = { workspace = true } +futures = { workspace = true } +polkadot-primitives = { workspace = true, default-features = true } +codec = { features = ["derive"], workspace = true } +sp-core = { workspace = true, default-features = true } +sp-application-crypto = { workspace = true, default-features = true } +sp-consensus-babe = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-maybe-compressed-blob = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +polkadot-parachain-primitives = { workspace = true } +schnorrkel = { workspace = true, default-features = true } thiserror = { workspace = true } -bitvec = { version = "1.0.0", default-features = false, features = ["alloc"] } +bitvec = { features = ["alloc"], workspace = true } serde = { features = ["derive"], workspace = true, default-features = true } [target.'cfg(not(target_os = "unknown"))'.dependencies] zstd = { version = "0.12.4", default-features = false } [dev-dependencies] -polkadot-erasure-coding = { path = "../../erasure-coding" } +polkadot-erasure-coding = { workspace = true, default-features = true } diff --git a/polkadot/node/primitives/src/lib.rs b/polkadot/node/primitives/src/lib.rs index aded1b8fe7342a9157720acda75a8d7a7f835334..ecf79eac2883e930213fb54e4bf16b8a266a0c42 100644 --- a/polkadot/node/primitives/src/lib.rs +++ b/polkadot/node/primitives/src/lib.rs @@ -59,7 +59,7 @@ pub use disputes::{ /// relatively rare. /// /// The associated worker binaries should use the same version as the node that spawns them. -pub const NODE_VERSION: &'static str = "1.12.0"; +pub const NODE_VERSION: &'static str = "1.13.0"; // For a 16-ary Merkle Prefix Trie, we can expect at most 16 32-byte hashes per node // plus some overhead: diff --git a/polkadot/node/service/Cargo.toml b/polkadot/node/service/Cargo.toml index ec5113d2c8a5f0bc40e404dbf78201c5b2a65102..23cd51d8a04c3b0cae8837219ea6bb352f2f9587 100644 --- a/polkadot/node/service/Cargo.toml +++ b/polkadot/node/service/Cargo.toml @@ -12,147 +12,147 @@ workspace = true [dependencies] # Substrate Client -sc-authority-discovery = { path = "../../../substrate/client/authority-discovery" } -sc-consensus-babe = { path = "../../../substrate/client/consensus/babe" } -sc-consensus-beefy = { path = "../../../substrate/client/consensus/beefy" } -sc-consensus-grandpa = { path = "../../../substrate/client/consensus/grandpa" } -mmr-gadget = { path = "../../../substrate/client/merkle-mountain-range" } -sp-mmr-primitives = { path = "../../../substrate/primitives/merkle-mountain-range" } -sc-block-builder = { path = "../../../substrate/client/block-builder" } -sc-chain-spec = { path = "../../../substrate/client/chain-spec" } -sc-client-api = { path = "../../../substrate/client/api" } -sc-client-db = { path = "../../../substrate/client/db" } -sc-consensus = { path = "../../../substrate/client/consensus/common" } -sc-consensus-slots = { path = "../../../substrate/client/consensus/slots" } -sc-executor = { path = "../../../substrate/client/executor" } -sc-network = { path = "../../../substrate/client/network" } -sc-network-common = { path = "../../../substrate/client/network/common" } -sc-network-sync = { path = "../../../substrate/client/network/sync" } -sc-transaction-pool = { path = "../../../substrate/client/transaction-pool" } -sc-transaction-pool-api = { path = "../../../substrate/client/transaction-pool/api" } -sc-sync-state-rpc = { path = "../../../substrate/client/sync-state-rpc" } -sc-keystore = { path = "../../../substrate/client/keystore" } -sc-basic-authorship = { path = "../../../substrate/client/basic-authorship" } -sc-offchain = { path = "../../../substrate/client/offchain" } -sc-sysinfo = { path = "../../../substrate/client/sysinfo" } -sc-service = { path = "../../../substrate/client/service", default-features = false } -sc-telemetry = { path = "../../../substrate/client/telemetry" } +sc-authority-discovery = { workspace = true, default-features = true } +sc-consensus-babe = { workspace = true, default-features = true } +sc-consensus-beefy = { workspace = true, default-features = true } +sc-consensus-grandpa = { workspace = true, default-features = true } +mmr-gadget = { workspace = true, default-features = true } +sp-mmr-primitives = { workspace = true, default-features = true } +sc-block-builder = { workspace = true, default-features = true } +sc-chain-spec = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-client-db = { workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } +sc-consensus-slots = { workspace = true, default-features = true } +sc-executor = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sc-network-common = { workspace = true, default-features = true } +sc-network-sync = { workspace = true, default-features = true } +sc-transaction-pool = { workspace = true, default-features = true } +sc-transaction-pool-api = { workspace = true, default-features = true } +sc-sync-state-rpc = { workspace = true, default-features = true } +sc-keystore = { workspace = true, default-features = true } +sc-basic-authorship = { workspace = true, default-features = true } +sc-offchain = { workspace = true, default-features = true } +sc-sysinfo = { workspace = true, default-features = true } +sc-service = { workspace = true } +sc-telemetry = { workspace = true, default-features = true } # Substrate Primitives -sp-authority-discovery = { path = "../../../substrate/primitives/authority-discovery" } -sp-consensus = { path = "../../../substrate/primitives/consensus/common" } -sp-consensus-beefy = { path = "../../../substrate/primitives/consensus/beefy" } -sp-consensus-grandpa = { path = "../../../substrate/primitives/consensus/grandpa" } -sp-inherents = { path = "../../../substrate/primitives/inherents" } -sp-keyring = { path = "../../../substrate/primitives/keyring" } -sp-api = { path = "../../../substrate/primitives/api" } -sp-block-builder = { path = "../../../substrate/primitives/block-builder" } -sp-blockchain = { path = "../../../substrate/primitives/blockchain" } -sp-core = { path = "../../../substrate/primitives/core" } -sp-io = { path = "../../../substrate/primitives/io" } -sp-keystore = { path = "../../../substrate/primitives/keystore" } -sp-offchain = { package = "sp-offchain", path = "../../../substrate/primitives/offchain" } -sp-runtime = { path = "../../../substrate/primitives/runtime" } -sp-session = { path = "../../../substrate/primitives/session" } -sp-storage = { path = "../../../substrate/primitives/storage" } -sp-transaction-pool = { path = "../../../substrate/primitives/transaction-pool" } -pallet-transaction-payment = { path = "../../../substrate/frame/transaction-payment" } -sp-timestamp = { path = "../../../substrate/primitives/timestamp" } -sp-consensus-babe = { path = "../../../substrate/primitives/consensus/babe" } -sp-state-machine = { path = "../../../substrate/primitives/state-machine" } -sp-weights = { path = "../../../substrate/primitives/weights" } -sp-version = { path = "../../../substrate/primitives/version" } +sp-authority-discovery = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-consensus-beefy = { workspace = true, default-features = true } +sp-consensus-grandpa = { workspace = true, default-features = true } +sp-inherents = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-block-builder = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-offchain = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-session = { workspace = true, default-features = true } +sp-storage = { workspace = true, default-features = true } +sp-transaction-pool = { workspace = true, default-features = true } +pallet-transaction-payment = { workspace = true, default-features = true } +sp-timestamp = { workspace = true, default-features = true } +sp-consensus-babe = { workspace = true, default-features = true } +sp-state-machine = { workspace = true, default-features = true } +sp-weights = { workspace = true, default-features = true } +sp-version = { workspace = true, default-features = true } # Substrate Pallets -pallet-babe = { path = "../../../substrate/frame/babe" } -pallet-staking = { path = "../../../substrate/frame/staking" } -pallet-transaction-payment-rpc-runtime-api = { path = "../../../substrate/frame/transaction-payment/rpc/runtime-api" } -frame-metadata-hash-extension = { path = "../../../substrate/frame/metadata-hash-extension", optional = true } -frame-system = { path = "../../../substrate/frame/system" } +pallet-babe = { workspace = true, default-features = true } +pallet-staking = { workspace = true, default-features = true } +pallet-transaction-payment-rpc-runtime-api = { workspace = true, default-features = true } +frame-metadata-hash-extension = { optional = true, workspace = true, default-features = true } +frame-system = { workspace = true, default-features = true } # Substrate Other -frame-system-rpc-runtime-api = { path = "../../../substrate/frame/system/rpc/runtime-api" } -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../../substrate/utils/prometheus" } -frame-support = { path = "../../../substrate/frame/support" } -frame-benchmarking-cli = { path = "../../../substrate/utils/frame/benchmarking-cli" } -frame-benchmarking = { path = "../../../substrate/frame/benchmarking" } +frame-system-rpc-runtime-api = { workspace = true, default-features = true } +prometheus-endpoint = { workspace = true, default-features = true } +frame-support = { workspace = true, default-features = true } +frame-benchmarking-cli = { workspace = true, default-features = true } +frame-benchmarking = { workspace = true, default-features = true } # External Crates -async-trait = "0.1.79" -futures = "0.3.30" -hex-literal = "0.4.1" -is_executable = "1.0.1" -gum = { package = "tracing-gum", path = "../gum" } +async-trait = { workspace = true } +futures = { workspace = true } +hex-literal = { workspace = true, default-features = true } +is_executable = { workspace = true } +gum = { workspace = true, default-features = true } log = { workspace = true, default-features = true } -schnellru = "0.2.1" +schnellru = { workspace = true } serde = { features = ["derive"], workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } thiserror = { workspace = true } -kvdb = "0.13.0" -kvdb-rocksdb = { version = "0.19.0", optional = true } -parity-db = { version = "0.4.12", optional = true } -codec = { package = "parity-scale-codec", version = "3.6.12" } -parking_lot = "0.12.1" -bitvec = { version = "1.0.1", optional = true } +kvdb = { workspace = true } +kvdb-rocksdb = { optional = true, workspace = true } +parity-db = { optional = true, workspace = true } +codec = { workspace = true, default-features = true } +parking_lot = { workspace = true, default-features = true } +bitvec = { optional = true, workspace = true, default-features = true } # Polkadot -polkadot-core-primitives = { path = "../../core-primitives" } -polkadot-node-core-parachains-inherent = { path = "../core/parachains-inherent" } -polkadot-overseer = { path = "../overseer" } -polkadot-parachain-primitives = { path = "../../parachain" } -polkadot-primitives = { path = "../../primitives" } -polkadot-node-primitives = { path = "../primitives" } -polkadot-rpc = { path = "../../rpc" } -polkadot-node-subsystem = { path = "../subsystem" } -polkadot-node-subsystem-util = { path = "../subsystem-util" } -polkadot-node-subsystem-types = { path = "../subsystem-types" } -polkadot-runtime-parachains = { path = "../../runtime/parachains" } -polkadot-node-network-protocol = { path = "../network/protocol" } +polkadot-core-primitives = { workspace = true, default-features = true } +polkadot-node-core-parachains-inherent = { workspace = true, default-features = true } +polkadot-overseer = { workspace = true, default-features = true } +polkadot-parachain-primitives = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-rpc = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-node-subsystem-util = { workspace = true, default-features = true } +polkadot-node-subsystem-types = { workspace = true, default-features = true } +polkadot-runtime-parachains = { workspace = true, default-features = true } +polkadot-node-network-protocol = { workspace = true, default-features = true } # Polkadot Runtime Constants -rococo-runtime-constants = { path = "../../runtime/rococo/constants", optional = true } -westend-runtime-constants = { path = "../../runtime/westend/constants", optional = true } +rococo-runtime-constants = { optional = true, workspace = true, default-features = true } +westend-runtime-constants = { optional = true, workspace = true, default-features = true } # Polkadot Runtimes -westend-runtime = { path = "../../runtime/westend", optional = true } -rococo-runtime = { path = "../../runtime/rococo", optional = true } +westend-runtime = { optional = true, workspace = true } +rococo-runtime = { optional = true, workspace = true } # Polkadot Subsystems -polkadot-approval-distribution = { path = "../network/approval-distribution", optional = true } -polkadot-availability-bitfield-distribution = { path = "../network/bitfield-distribution", optional = true } -polkadot-availability-distribution = { path = "../network/availability-distribution", optional = true } -polkadot-availability-recovery = { path = "../network/availability-recovery", optional = true } -polkadot-collator-protocol = { path = "../network/collator-protocol", optional = true } -polkadot-dispute-distribution = { path = "../network/dispute-distribution", optional = true } -polkadot-gossip-support = { path = "../network/gossip-support", optional = true } -polkadot-network-bridge = { path = "../network/bridge", optional = true } -polkadot-node-collation-generation = { path = "../collation-generation", optional = true } -polkadot-node-core-approval-voting = { path = "../core/approval-voting", optional = true } -polkadot-node-core-av-store = { path = "../core/av-store", optional = true } -polkadot-node-core-backing = { path = "../core/backing", optional = true } -polkadot-node-core-bitfield-signing = { path = "../core/bitfield-signing", optional = true } -polkadot-node-core-candidate-validation = { path = "../core/candidate-validation", optional = true } -polkadot-node-core-chain-api = { path = "../core/chain-api", optional = true } -polkadot-node-core-chain-selection = { path = "../core/chain-selection", optional = true } -polkadot-node-core-dispute-coordinator = { path = "../core/dispute-coordinator", optional = true } -polkadot-node-core-prospective-parachains = { path = "../core/prospective-parachains", optional = true } -polkadot-node-core-provisioner = { path = "../core/provisioner", optional = true } -polkadot-node-core-pvf = { path = "../core/pvf", optional = true } -polkadot-node-core-pvf-checker = { path = "../core/pvf-checker", optional = true } -polkadot-node-core-runtime-api = { path = "../core/runtime-api", optional = true } -polkadot-statement-distribution = { path = "../network/statement-distribution", optional = true } - -xcm = { package = "staging-xcm", path = "../../xcm" } -xcm-fee-payment-runtime-api = { path = "../../xcm/xcm-fee-payment-runtime-api" } +polkadot-approval-distribution = { optional = true, workspace = true, default-features = true } +polkadot-availability-bitfield-distribution = { optional = true, workspace = true, default-features = true } +polkadot-availability-distribution = { optional = true, workspace = true, default-features = true } +polkadot-availability-recovery = { optional = true, workspace = true, default-features = true } +polkadot-collator-protocol = { optional = true, workspace = true, default-features = true } +polkadot-dispute-distribution = { optional = true, workspace = true, default-features = true } +polkadot-gossip-support = { optional = true, workspace = true, default-features = true } +polkadot-network-bridge = { optional = true, workspace = true, default-features = true } +polkadot-node-collation-generation = { optional = true, workspace = true, default-features = true } +polkadot-node-core-approval-voting = { optional = true, workspace = true, default-features = true } +polkadot-node-core-av-store = { optional = true, workspace = true, default-features = true } +polkadot-node-core-backing = { optional = true, workspace = true, default-features = true } +polkadot-node-core-bitfield-signing = { optional = true, workspace = true, default-features = true } +polkadot-node-core-candidate-validation = { optional = true, workspace = true, default-features = true } +polkadot-node-core-chain-api = { optional = true, workspace = true, default-features = true } +polkadot-node-core-chain-selection = { optional = true, workspace = true, default-features = true } +polkadot-node-core-dispute-coordinator = { optional = true, workspace = true, default-features = true } +polkadot-node-core-prospective-parachains = { optional = true, workspace = true, default-features = true } +polkadot-node-core-provisioner = { optional = true, workspace = true, default-features = true } +polkadot-node-core-pvf = { optional = true, workspace = true, default-features = true } +polkadot-node-core-pvf-checker = { optional = true, workspace = true, default-features = true } +polkadot-node-core-runtime-api = { optional = true, workspace = true, default-features = true } +polkadot-statement-distribution = { optional = true, workspace = true, default-features = true } + +xcm = { workspace = true, default-features = true } +xcm-runtime-apis = { workspace = true, default-features = true } [dev-dependencies] -polkadot-test-client = { path = "../test/client" } -polkadot-node-subsystem-test-helpers = { path = "../subsystem-test-helpers" } -polkadot-primitives-test-helpers = { path = "../../primitives/test-helpers" } -env_logger = "0.11" -assert_matches = "1.5.0" -serial_test = "2.0.0" -tempfile = "3.2" +polkadot-test-client = { workspace = true } +polkadot-node-subsystem-test-helpers = { workspace = true } +polkadot-primitives-test-helpers = { workspace = true } +env_logger = { workspace = true } +assert_matches = { workspace = true } +serial_test = { workspace = true } +tempfile = { workspace = true } [features] default = ["db", "full-node"] @@ -217,7 +217,7 @@ runtime-benchmarks = [ "sc-service/runtime-benchmarks", "sp-runtime/runtime-benchmarks", "westend-runtime?/runtime-benchmarks", - "xcm-fee-payment-runtime-api/runtime-benchmarks", + "xcm-runtime-apis/runtime-benchmarks", ] try-runtime = [ "frame-support/try-runtime", diff --git a/polkadot/node/service/src/fake_runtime_api.rs b/polkadot/node/service/src/fake_runtime_api.rs index dd8a0a7e635bc67e298f31f537f9c41fa207b6a5..debf3690aead9bb3ea97f4631b4070185ba1714c 100644 --- a/polkadot/node/service/src/fake_runtime_api.rs +++ b/polkadot/node/service/src/fake_runtime_api.rs @@ -398,30 +398,30 @@ sp_api::impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::fees::XcmPaymentApi for Runtime { - fn query_acceptable_payment_assets(_: xcm::Version) -> Result, xcm_fee_payment_runtime_api::fees::Error> { + impl xcm_runtime_apis::fees::XcmPaymentApi for Runtime { + fn query_acceptable_payment_assets(_: xcm::Version) -> Result, xcm_runtime_apis::fees::Error> { unimplemented!() } - fn query_weight_to_asset_fee(_: Weight, _: VersionedAssetId) -> Result { + fn query_weight_to_asset_fee(_: Weight, _: VersionedAssetId) -> Result { unimplemented!() } - fn query_xcm_weight(_: VersionedXcm<()>) -> Result { + fn query_xcm_weight(_: VersionedXcm<()>) -> Result { unimplemented!() } - fn query_delivery_fees(_: VersionedLocation, _: VersionedXcm<()>) -> Result { + fn query_delivery_fees(_: VersionedLocation, _: VersionedXcm<()>) -> Result { unimplemented!() } } - impl xcm_fee_payment_runtime_api::dry_run::DryRunApi for Runtime { - fn dry_run_call(_: (), _: ()) -> Result, xcm_fee_payment_runtime_api::dry_run::Error> { + impl xcm_runtime_apis::dry_run::DryRunApi for Runtime { + fn dry_run_call(_: (), _: ()) -> Result, xcm_runtime_apis::dry_run::Error> { unimplemented!() } - fn dry_run_xcm(_: VersionedLocation, _: VersionedXcm<()>) -> Result, xcm_fee_payment_runtime_api::dry_run::Error> { + fn dry_run_xcm(_: VersionedLocation, _: VersionedXcm<()>) -> Result, xcm_runtime_apis::dry_run::Error> { unimplemented!() } } diff --git a/polkadot/node/subsystem-bench/Cargo.toml b/polkadot/node/subsystem-bench/Cargo.toml index 5001104f929a2dc2c596567c8b7febd8088e09f2..0325613d25f9a716f9a0189e8bb9db91d9051e8c 100644 --- a/polkadot/node/subsystem-bench/Cargo.toml +++ b/polkadot/node/subsystem-bench/Cargo.toml @@ -20,76 +20,76 @@ path = "src/cli/subsystem-bench.rs" doc = false [dependencies] -polkadot-node-subsystem = { path = "../subsystem" } -polkadot-node-subsystem-util = { path = "../subsystem-util" } -polkadot-node-subsystem-types = { path = "../subsystem-types" } -polkadot-node-primitives = { path = "../primitives" } -polkadot-primitives = { path = "../../primitives" } -polkadot-node-network-protocol = { path = "../network/protocol" } -polkadot-availability-recovery = { path = "../network/availability-recovery", features = ["subsystem-benchmarks"] } -polkadot-availability-distribution = { path = "../network/availability-distribution" } -polkadot-statement-distribution = { path = "../network/statement-distribution" } -polkadot-node-core-av-store = { path = "../core/av-store" } -polkadot-node-core-chain-api = { path = "../core/chain-api" } -polkadot-availability-bitfield-distribution = { path = "../network/bitfield-distribution" } -color-eyre = { version = "0.6.1", default-features = false } -polkadot-overseer = { path = "../overseer" } -colored = "2.0.4" -assert_matches = "1.5" -async-trait = "0.1.79" -sp-keystore = { path = "../../../substrate/primitives/keystore" } -sc-keystore = { path = "../../../substrate/client/keystore" } -sp-core = { path = "../../../substrate/primitives/core" } -clap = { version = "4.5.3", features = ["derive"] } -futures = "0.3.30" -futures-timer = "3.0.2" -bincode = "1.3.3" -sha1 = "0.10.6" -hex = "0.4.3" -gum = { package = "tracing-gum", path = "../gum" } -polkadot-erasure-coding = { package = "polkadot-erasure-coding", path = "../../erasure-coding" } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-node-subsystem-util = { workspace = true, default-features = true } +polkadot-node-subsystem-types = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-node-network-protocol = { workspace = true, default-features = true } +polkadot-availability-recovery = { features = ["subsystem-benchmarks"], workspace = true, default-features = true } +polkadot-availability-distribution = { workspace = true, default-features = true } +polkadot-statement-distribution = { workspace = true, default-features = true } +polkadot-node-core-av-store = { workspace = true, default-features = true } +polkadot-node-core-chain-api = { workspace = true, default-features = true } +polkadot-availability-bitfield-distribution = { workspace = true, default-features = true } +color-eyre = { workspace = true } +polkadot-overseer = { workspace = true, default-features = true } +colored = { workspace = true } +assert_matches = { workspace = true } +async-trait = { workspace = true } +sp-keystore = { workspace = true, default-features = true } +sc-keystore = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +clap = { features = ["derive"], workspace = true } +futures = { workspace = true } +futures-timer = { workspace = true } +bincode = { workspace = true } +sha1 = { workspace = true } +hex = { workspace = true, default-features = true } +gum = { workspace = true, default-features = true } +polkadot-erasure-coding = { workspace = true, default-features = true } log = { workspace = true, default-features = true } -env_logger = "0.11" -rand = "0.8.5" +env_logger = { workspace = true } +rand = { workspace = true, default-features = true } # `rand` only supports uniform distribution, we need normal distribution for latency. -rand_distr = "0.4.3" -bitvec = "1.0.1" -kvdb-memorydb = "0.13.0" +rand_distr = { workspace = true } +bitvec = { workspace = true, default-features = true } +kvdb-memorydb = { workspace = true } -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive", "std"] } -tokio = { version = "1.24.2", features = ["parking_lot", "rt-multi-thread"] } -clap-num = "1.0.2" -polkadot-node-subsystem-test-helpers = { path = "../subsystem-test-helpers" } -sp-keyring = { path = "../../../substrate/primitives/keyring" } -sp-application-crypto = { path = "../../../substrate/primitives/application-crypto" } -sc-network = { path = "../../../substrate/client/network" } -sc-network-types = { path = "../../../substrate/client/network/types" } -sc-service = { path = "../../../substrate/client/service" } -sp-consensus = { path = "../../../substrate/primitives/consensus/common" } -polkadot-node-metrics = { path = "../metrics" } -itertools = "0.11" -polkadot-primitives-test-helpers = { path = "../../primitives/test-helpers" } -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../../substrate/utils/prometheus" } -prometheus = { version = "0.13.0", default-features = false } +codec = { features = ["derive", "std"], workspace = true, default-features = true } +tokio = { features = ["parking_lot", "rt-multi-thread"], workspace = true, default-features = true } +clap-num = { workspace = true } +polkadot-node-subsystem-test-helpers = { workspace = true } +sp-keyring = { workspace = true, default-features = true } +sp-application-crypto = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sc-network-types = { workspace = true, default-features = true } +sc-service = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +polkadot-node-metrics = { workspace = true, default-features = true } +itertools = { workspace = true } +polkadot-primitives-test-helpers = { workspace = true } +prometheus-endpoint = { workspace = true, default-features = true } +prometheus = { workspace = true } serde = { workspace = true, default-features = true } serde_yaml = { workspace = true } serde_json = { workspace = true } -polkadot-node-core-approval-voting = { path = "../core/approval-voting" } -polkadot-approval-distribution = { path = "../network/approval-distribution" } -sp-consensus-babe = { path = "../../../substrate/primitives/consensus/babe" } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-timestamp = { path = "../../../substrate/primitives/timestamp" } +polkadot-node-core-approval-voting = { workspace = true, default-features = true } +polkadot-approval-distribution = { workspace = true, default-features = true } +sp-consensus-babe = { workspace = true, default-features = true } +sp-runtime = { workspace = true } +sp-timestamp = { workspace = true, default-features = true } -schnorrkel = { version = "0.11.4", default-features = false } +schnorrkel = { workspace = true } # rand_core should match schnorrkel -rand_core = "0.6.2" -rand_chacha = { version = "0.3.1" } -paste = "1.0.14" -orchestra = { version = "0.3.5", default-features = false, features = ["futures_channel"] } -pyroscope = { version = "0.5.7" } -pyroscope_pprofrs = "0.2.7" -strum = { version = "0.24", features = ["derive"] } +rand_core = { workspace = true } +rand_chacha = { workspace = true, default-features = true } +paste = { workspace = true, default-features = true } +orchestra = { features = ["futures_channel"], workspace = true } +pyroscope = { workspace = true } +pyroscope_pprofrs = { workspace = true } +strum = { features = ["derive"], workspace = true, default-features = true } [features] default = [] diff --git a/polkadot/node/subsystem-bench/src/lib/approval/mod.rs b/polkadot/node/subsystem-bench/src/lib/approval/mod.rs index 5c0c65b11cdb5db521ba0045b83f937f72e6b246..b033be9986f4853a2671d4686772dd8dea2c249d 100644 --- a/polkadot/node/subsystem-bench/src/lib/approval/mod.rs +++ b/polkadot/node/subsystem-bench/src/lib/approval/mod.rs @@ -60,7 +60,7 @@ use polkadot_node_subsystem_util::metrics::Metrics; use polkadot_overseer::Handle as OverseerHandleReal; use polkadot_primitives::{ BlockNumber, CandidateEvent, CandidateIndex, CandidateReceipt, Hash, Header, Slot, - ValidatorIndex, + ValidatorIndex, ASSIGNMENT_KEY_TYPE_ID, }; use prometheus::Registry; use sc_keystore::LocalKeystore; @@ -68,6 +68,7 @@ use sc_service::SpawnTaskHandle; use serde::{Deserialize, Serialize}; use sp_consensus_babe::Epoch as BabeEpoch; use sp_core::H256; +use sp_keystore::Keystore; use std::{ cmp::max, collections::{HashMap, HashSet}, @@ -785,6 +786,12 @@ fn build_overseer( let db: polkadot_node_subsystem_util::database::kvdb_impl::DbAdapter = polkadot_node_subsystem_util::database::kvdb_impl::DbAdapter::new(db, &[]); let keystore = LocalKeystore::in_memory(); + keystore + .sr25519_generate_new( + ASSIGNMENT_KEY_TYPE_ID, + Some(state.test_authorities.key_seeds.get(NODE_UNDER_TEST as usize).unwrap().as_str()), + ) + .unwrap(); let system_clock = PastSystemClock::new(SystemClock {}, state.delta_tick_from_generated.clone()); diff --git a/polkadot/node/subsystem-bench/src/lib/mock/runtime_api.rs b/polkadot/node/subsystem-bench/src/lib/mock/runtime_api.rs index be9dbd55cb6f9898a879e7bbaa6c5f5b9c303484..ee45ea05c925a433394de3e3e5e2c315dac0aff2 100644 --- a/polkadot/node/subsystem-bench/src/lib/mock/runtime_api.rs +++ b/polkadot/node/subsystem-bench/src/lib/mock/runtime_api.rs @@ -28,7 +28,7 @@ use polkadot_node_subsystem_types::OverseerSignal; use polkadot_primitives::{ node_features, AsyncBackingParams, CandidateEvent, CandidateReceipt, CoreState, GroupIndex, GroupRotationInfo, IndexedVec, NodeFeatures, OccupiedCore, ScheduledCore, SessionIndex, - SessionInfo, ValidatorIndex, + SessionInfo, ValidationCode, ValidatorIndex, }; use sp_consensus_babe::Epoch as BabeEpoch; use sp_core::H256; @@ -288,6 +288,15 @@ impl MockRuntimeApi { }; tx.send(Ok((groups, group_rotation_info))).unwrap(); }, + RuntimeApiMessage::Request( + _parent, + RuntimeApiRequest::ValidationCodeByHash(_, tx), + ) => { + let validation_code = ValidationCode(Vec::new()); + if let Err(err) = tx.send(Ok(Some(validation_code))) { + gum::error!(target: LOG_TARGET, ?err, "validation code wasn't received"); + } + }, // Long term TODO: implement more as needed. message => { unimplemented!("Unexpected runtime-api message: {:?}", message) diff --git a/polkadot/node/subsystem-test-helpers/Cargo.toml b/polkadot/node/subsystem-test-helpers/Cargo.toml index 57678e8e8d4a1057ec843f097c2cd9811f33a6bb..d3229291673c6da0b1ba12d6983c678ed2d5a343 100644 --- a/polkadot/node/subsystem-test-helpers/Cargo.toml +++ b/polkadot/node/subsystem-test-helpers/Cargo.toml @@ -11,19 +11,19 @@ license.workspace = true workspace = true [dependencies] -async-trait = "0.1.79" -futures = "0.3.30" -parking_lot = "0.12.1" -polkadot-node-subsystem = { path = "../subsystem" } -polkadot-erasure-coding = { path = "../../erasure-coding" } -polkadot-node-subsystem-util = { path = "../subsystem-util" } -polkadot-primitives = { path = "../../primitives" } -polkadot-node-primitives = { path = "../primitives" } +async-trait = { workspace = true } +futures = { workspace = true } +parking_lot = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-erasure-coding = { workspace = true, default-features = true } +polkadot-node-subsystem-util = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } -sc-client-api = { path = "../../../substrate/client/api" } -sc-utils = { path = "../../../substrate/client/utils" } -sp-core = { path = "../../../substrate/primitives/core" } -sp-keystore = { path = "../../../substrate/primitives/keystore" } -sc-keystore = { path = "../../../substrate/client/keystore" } -sp-keyring = { path = "../../../substrate/primitives/keyring" } -sp-application-crypto = { path = "../../../substrate/primitives/application-crypto" } +sc-client-api = { workspace = true, default-features = true } +sc-utils = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sc-keystore = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +sp-application-crypto = { workspace = true, default-features = true } diff --git a/polkadot/node/subsystem-types/Cargo.toml b/polkadot/node/subsystem-types/Cargo.toml index 0178b193cba8c88f2cc7b4a980beae8f7de106ff..c8fc324699e1754cb0d476a97ef29c8fea4ede74 100644 --- a/polkadot/node/subsystem-types/Cargo.toml +++ b/polkadot/node/subsystem-types/Cargo.toml @@ -10,26 +10,26 @@ license.workspace = true workspace = true [dependencies] -derive_more = "0.99.17" -fatality = "0.1.1" -futures = "0.3.30" -polkadot-primitives = { path = "../../primitives" } -polkadot-node-primitives = { path = "../primitives" } -polkadot-node-network-protocol = { path = "../network/protocol" } -polkadot-statement-table = { path = "../../statement-table" } -polkadot-node-jaeger = { path = "../jaeger" } -orchestra = { version = "0.3.5", default-features = false, features = ["futures_channel"] } -sc-network = { path = "../../../substrate/client/network" } -sc-network-types = { path = "../../../substrate/client/network/types" } -sp-api = { path = "../../../substrate/primitives/api" } -sp-blockchain = { path = "../../../substrate/primitives/blockchain" } -sp-consensus-babe = { path = "../../../substrate/primitives/consensus/babe" } -sp-runtime = { path = "../../../substrate/primitives/runtime" } -sp-authority-discovery = { path = "../../../substrate/primitives/authority-discovery" } -sc-client-api = { path = "../../../substrate/client/api" } -sc-transaction-pool-api = { path = "../../../substrate/client/transaction-pool/api" } -smallvec = "1.8.0" -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../../substrate/utils/prometheus" } +derive_more = { workspace = true, default-features = true } +fatality = { workspace = true } +futures = { workspace = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-node-network-protocol = { workspace = true, default-features = true } +polkadot-statement-table = { workspace = true, default-features = true } +polkadot-node-jaeger = { workspace = true, default-features = true } +orchestra = { features = ["futures_channel"], workspace = true } +sc-network = { workspace = true, default-features = true } +sc-network-types = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-consensus-babe = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-authority-discovery = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-transaction-pool-api = { workspace = true, default-features = true } +smallvec = { workspace = true, default-features = true } +prometheus-endpoint = { workspace = true, default-features = true } thiserror = { workspace = true } -async-trait = "0.1.79" -bitvec = { version = "1.0.0", default-features = false, features = ["alloc"] } +async-trait = { workspace = true } +bitvec = { features = ["alloc"], workspace = true } diff --git a/polkadot/node/subsystem-util/Cargo.toml b/polkadot/node/subsystem-util/Cargo.toml index b7fb75b94b2c726cb0171b48b023a9d9517970ac..98ea21f250eda7874f03ba1aeffd482fedbc8808 100644 --- a/polkadot/node/subsystem-util/Cargo.toml +++ b/polkadot/node/subsystem-util/Cargo.toml @@ -10,47 +10,47 @@ license.workspace = true workspace = true [dependencies] -async-trait = "0.1.79" -futures = "0.3.30" -futures-channel = "0.3.23" -itertools = "0.11" -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -parking_lot = "0.12.1" -pin-project = "1.0.9" -rand = "0.8.5" +async-trait = { workspace = true } +futures = { workspace = true } +futures-channel = { workspace = true } +itertools = { workspace = true } +codec = { features = ["derive"], workspace = true } +parking_lot = { workspace = true, default-features = true } +pin-project = { workspace = true } +rand = { workspace = true, default-features = true } thiserror = { workspace = true } -fatality = "0.1.1" -gum = { package = "tracing-gum", path = "../gum" } -derive_more = "0.99.17" -schnellru = "0.2.1" +fatality = { workspace = true } +gum = { workspace = true, default-features = true } +derive_more = { workspace = true, default-features = true } +schnellru = { workspace = true } -polkadot-erasure-coding = { path = "../../erasure-coding" } -polkadot-node-subsystem = { path = "../subsystem" } -polkadot-node-subsystem-types = { path = "../subsystem-types" } -polkadot-node-jaeger = { path = "../jaeger" } -polkadot-node-metrics = { path = "../metrics" } -polkadot-node-network-protocol = { path = "../network/protocol" } -polkadot-primitives = { path = "../../primitives" } -polkadot-node-primitives = { path = "../primitives" } -polkadot-overseer = { path = "../overseer" } -metered = { package = "prioritized-metered-channel", version = "0.6.1", default-features = false, features = ["futures_channel"] } +polkadot-erasure-coding = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-node-subsystem-types = { workspace = true, default-features = true } +polkadot-node-jaeger = { workspace = true, default-features = true } +polkadot-node-metrics = { workspace = true, default-features = true } +polkadot-node-network-protocol = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-overseer = { workspace = true, default-features = true } +metered = { features = ["futures_channel"], workspace = true } -sp-core = { path = "../../../substrate/primitives/core" } -sp-application-crypto = { path = "../../../substrate/primitives/application-crypto" } -sp-keystore = { path = "../../../substrate/primitives/keystore" } -sc-client-api = { path = "../../../substrate/client/api" } +sp-core = { workspace = true, default-features = true } +sp-application-crypto = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } -kvdb = "0.13.0" -parity-db = { version = "0.4.12" } +kvdb = { workspace = true } +parity-db = { workspace = true } [dev-dependencies] -assert_matches = "1.4.0" -env_logger = "0.11" -futures = { version = "0.3.30", features = ["thread-pool"] } +assert_matches = { workspace = true } +env_logger = { workspace = true } +futures = { features = ["thread-pool"], workspace = true } log = { workspace = true, default-features = true } -polkadot-node-subsystem-test-helpers = { path = "../subsystem-test-helpers" } -lazy_static = "1.4.0" -polkadot-primitives-test-helpers = { path = "../../primitives/test-helpers" } -kvdb-shared-tests = "0.11.0" -tempfile = "3.1.0" -kvdb-memorydb = "0.13.0" +polkadot-node-subsystem-test-helpers = { workspace = true } +lazy_static = { workspace = true } +polkadot-primitives-test-helpers = { workspace = true } +kvdb-shared-tests = { workspace = true } +tempfile = { workspace = true } +kvdb-memorydb = { workspace = true } diff --git a/polkadot/node/subsystem-util/src/vstaging.rs b/polkadot/node/subsystem-util/src/vstaging.rs index b166a54f75c46ebfe4dd8d06af32a3dea3495b7a..b6cd73f412b33a10c814be9813e0cd14bd843934 100644 --- a/polkadot/node/subsystem-util/src/vstaging.rs +++ b/polkadot/node/subsystem-util/src/vstaging.rs @@ -31,7 +31,7 @@ const LOG_TARGET: &'static str = "parachain::subsystem-util-vstaging"; /// A snapshot of the runtime claim queue at an arbitrary relay chain block. #[derive(Default)] -pub struct ClaimQueueSnapshot(BTreeMap>); +pub struct ClaimQueueSnapshot(pub BTreeMap>); impl From>> for ClaimQueueSnapshot { fn from(claim_queue_snapshot: BTreeMap>) -> Self { @@ -56,6 +56,19 @@ impl ClaimQueueSnapshot { .iter() .filter_map(move |(core_index, paras)| Some((*core_index, *paras.get(depth)?))) } + + /// Returns an iterator over all claims on the given core. + pub fn iter_claims_for_core( + &self, + core_index: &CoreIndex, + ) -> impl Iterator + '_ { + self.0.get(core_index).map(|c| c.iter()).into_iter().flatten() + } + + /// Returns an iterator over the whole claim queue. + pub fn iter_all_claims(&self) -> impl Iterator)> + '_ { + self.0.iter() + } } // TODO: https://github.com/paritytech/polkadot-sdk/issues/1940 diff --git a/polkadot/node/subsystem/Cargo.toml b/polkadot/node/subsystem/Cargo.toml index c59c1f88e33995aef7578da58e28d086668f14ee..8edfea9e26bf5d2176b672c9d24bb1e0251b33ae 100644 --- a/polkadot/node/subsystem/Cargo.toml +++ b/polkadot/node/subsystem/Cargo.toml @@ -10,6 +10,6 @@ license.workspace = true workspace = true [dependencies] -polkadot-overseer = { path = "../overseer" } -polkadot-node-subsystem-types = { path = "../subsystem-types" } -polkadot-node-jaeger = { path = "../jaeger" } +polkadot-overseer = { workspace = true, default-features = true } +polkadot-node-subsystem-types = { workspace = true, default-features = true } +polkadot-node-jaeger = { workspace = true, default-features = true } diff --git a/polkadot/node/test/client/Cargo.toml b/polkadot/node/test/client/Cargo.toml index 0b49866ee2aec4f9676241a50271a16657b221e0..587af659fbd2dfeb142c4f307ce71a92b0fae35b 100644 --- a/polkadot/node/test/client/Cargo.toml +++ b/polkadot/node/test/client/Cargo.toml @@ -10,35 +10,35 @@ license.workspace = true workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } # Polkadot dependencies -polkadot-test-runtime = { path = "../../../runtime/test-runtime" } -polkadot-test-service = { path = "../service" } -polkadot-primitives = { path = "../../../primitives" } -polkadot-node-subsystem = { path = "../../subsystem" } +polkadot-test-runtime = { workspace = true } +polkadot-test-service = { workspace = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } # Substrate dependencies -substrate-test-client = { path = "../../../../substrate/test-utils/client" } -sc-service = { path = "../../../../substrate/client/service" } -sc-block-builder = { path = "../../../../substrate/client/block-builder" } -sc-consensus = { path = "../../../../substrate/client/consensus/common" } -sc-offchain = { path = "../../../../substrate/client/offchain" } -sp-blockchain = { path = "../../../../substrate/primitives/blockchain" } -sp-runtime = { path = "../../../../substrate/primitives/runtime" } -sp-inherents = { path = "../../../../substrate/primitives/inherents" } -sp-core = { path = "../../../../substrate/primitives/core" } -sp-api = { path = "../../../../substrate/primitives/api" } -sp-timestamp = { path = "../../../../substrate/primitives/timestamp" } -sp-consensus = { path = "../../../../substrate/primitives/consensus/common" } -sp-consensus-babe = { path = "../../../../substrate/primitives/consensus/babe" } -sp-state-machine = { path = "../../../../substrate/primitives/state-machine" } -sp-io = { path = "../../../../substrate/primitives/io" } -frame-benchmarking = { path = "../../../../substrate/frame/benchmarking" } +substrate-test-client = { workspace = true } +sc-service = { workspace = true, default-features = true } +sc-block-builder = { workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } +sc-offchain = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-inherents = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-timestamp = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-consensus-babe = { workspace = true, default-features = true } +sp-state-machine = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +frame-benchmarking = { workspace = true, default-features = true } [dev-dependencies] -sp-keyring = { path = "../../../../substrate/primitives/keyring" } -futures = "0.3.30" +sp-keyring = { workspace = true, default-features = true } +futures = { workspace = true } [features] runtime-benchmarks = [ diff --git a/polkadot/node/test/service/Cargo.toml b/polkadot/node/test/service/Cargo.toml index 3fc6d060870b1c36940cd7b75e50cddcf55782d3..8eb6105f98e2571bab0257694ccac49ae47c2ca9 100644 --- a/polkadot/node/test/service/Cargo.toml +++ b/polkadot/node/test/service/Cargo.toml @@ -10,60 +10,60 @@ license.workspace = true workspace = true [dependencies] -futures = "0.3.30" -hex = "0.4.3" -gum = { package = "tracing-gum", path = "../../gum" } -rand = "0.8.5" +futures = { workspace = true } +hex = { workspace = true, default-features = true } +gum = { workspace = true, default-features = true } +rand = { workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } -tempfile = "3.2.0" -tokio = "1.37" +tempfile = { workspace = true } +tokio = { workspace = true, default-features = true } # Polkadot dependencies -polkadot-overseer = { path = "../../overseer" } -polkadot-primitives = { path = "../../../primitives" } -polkadot-parachain-primitives = { path = "../../../parachain" } -polkadot-rpc = { path = "../../../rpc" } -polkadot-runtime-common = { path = "../../../runtime/common" } -polkadot-service = { path = "../../service" } -polkadot-node-subsystem = { path = "../../subsystem" } -polkadot-node-primitives = { path = "../../primitives" } -polkadot-test-runtime = { path = "../../../runtime/test-runtime" } -test-runtime-constants = { path = "../../../runtime/test-runtime/constants" } -polkadot-runtime-parachains = { path = "../../../runtime/parachains" } +polkadot-overseer = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-parachain-primitives = { workspace = true, default-features = true } +polkadot-rpc = { workspace = true, default-features = true } +polkadot-runtime-common = { workspace = true, default-features = true } +polkadot-service = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-test-runtime = { workspace = true } +test-runtime-constants = { workspace = true, default-features = true } +polkadot-runtime-parachains = { workspace = true, default-features = true } # Substrate dependencies -sp-authority-discovery = { path = "../../../../substrate/primitives/authority-discovery" } -sc-authority-discovery = { path = "../../../../substrate/client/authority-discovery" } -sc-consensus-babe = { path = "../../../../substrate/client/consensus/babe" } -sp-consensus-babe = { path = "../../../../substrate/primitives/consensus/babe" } -sp-consensus = { path = "../../../../substrate/primitives/consensus/common" } -frame-system = { path = "../../../../substrate/frame/system" } -sc-consensus-grandpa = { path = "../../../../substrate/client/consensus/grandpa" } -sp-consensus-grandpa = { path = "../../../../substrate/primitives/consensus/grandpa" } -sp-inherents = { path = "../../../../substrate/primitives/inherents" } -pallet-staking = { path = "../../../../substrate/frame/staking" } -pallet-balances = { path = "../../../../substrate/frame/balances" } -pallet-transaction-payment = { path = "../../../../substrate/frame/transaction-payment" } -sc-chain-spec = { path = "../../../../substrate/client/chain-spec" } -sc-cli = { path = "../../../../substrate/client/cli" } -sc-client-api = { path = "../../../../substrate/client/api" } -sc-consensus = { path = "../../../../substrate/client/consensus/common" } -sc-network = { path = "../../../../substrate/client/network" } -sc-tracing = { path = "../../../../substrate/client/tracing" } -sc-transaction-pool = { path = "../../../../substrate/client/transaction-pool" } -sc-service = { path = "../../../../substrate/client/service", default-features = false } -sp-arithmetic = { path = "../../../../substrate/primitives/arithmetic" } -sp-blockchain = { path = "../../../../substrate/primitives/blockchain" } -sp-core = { path = "../../../../substrate/primitives/core" } -sp-keyring = { path = "../../../../substrate/primitives/keyring" } -sp-runtime = { path = "../../../../substrate/primitives/runtime" } -sp-state-machine = { path = "../../../../substrate/primitives/state-machine" } -substrate-test-client = { path = "../../../../substrate/test-utils/client" } +sp-authority-discovery = { workspace = true, default-features = true } +sc-authority-discovery = { workspace = true, default-features = true } +sc-consensus-babe = { workspace = true, default-features = true } +sp-consensus-babe = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +frame-system = { workspace = true, default-features = true } +sc-consensus-grandpa = { workspace = true, default-features = true } +sp-consensus-grandpa = { workspace = true, default-features = true } +sp-inherents = { workspace = true, default-features = true } +pallet-staking = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +pallet-transaction-payment = { workspace = true, default-features = true } +sc-chain-spec = { workspace = true, default-features = true } +sc-cli = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sc-tracing = { workspace = true, default-features = true } +sc-transaction-pool = { workspace = true, default-features = true } +sc-service = { workspace = true } +sp-arithmetic = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-state-machine = { workspace = true, default-features = true } +substrate-test-client = { workspace = true } [dev-dependencies] -pallet-balances = { path = "../../../../substrate/frame/balances", default-features = false } -substrate-test-utils = { path = "../../../../substrate/test-utils" } -tokio = { version = "1.37", features = ["macros"] } +pallet-balances = { workspace = true } +substrate-test-utils = { workspace = true } +tokio = { features = ["macros"], workspace = true, default-features = true } [features] runtime-metrics = ["polkadot-test-runtime/runtime-metrics"] diff --git a/polkadot/node/zombienet-backchannel/Cargo.toml b/polkadot/node/zombienet-backchannel/Cargo.toml index 31662ccfc464913989e479a12e4bd976451498dc..a9bf1f5ef093a905de7ca96c515a5a1b2c9cd17b 100644 --- a/polkadot/node/zombienet-backchannel/Cargo.toml +++ b/polkadot/node/zombienet-backchannel/Cargo.toml @@ -12,14 +12,14 @@ license.workspace = true workspace = true [dependencies] -tokio = { version = "1.24.2", default-features = false, features = ["macros", "net", "rt-multi-thread", "sync"] } -url = "2.3.1" -tokio-tungstenite = "0.20.1" -futures-util = "0.3.30" -lazy_static = "1.4.0" -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } -reqwest = { version = "0.11", features = ["rustls-tls"], default-features = false } +tokio = { features = ["macros", "net", "rt-multi-thread", "sync"], workspace = true } +url = { workspace = true } +tokio-tungstenite = { workspace = true } +futures-util = { workspace = true, default-features = true } +lazy_static = { workspace = true } +codec = { features = ["derive"], workspace = true, default-features = true } +reqwest = { features = ["rustls-tls"], workspace = true } thiserror = { workspace = true } -gum = { package = "tracing-gum", path = "../gum" } +gum = { workspace = true, default-features = true } serde = { features = ["derive"], workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } diff --git a/polkadot/parachain/Cargo.toml b/polkadot/parachain/Cargo.toml index 11e8e3ce6d843cf410ce4a2c0bfb2ceacde9ce3e..1491af0148e0b16da53078935b802ae3287f6c36 100644 --- a/polkadot/parachain/Cargo.toml +++ b/polkadot/parachain/Cargo.toml @@ -13,15 +13,15 @@ workspace = true # note: special care is taken to avoid inclusion of `sp-io` externals when compiling # this crate for WASM. This is critical to avoid forcing all parachain WASM into implementing # various unnecessary Substrate-specific endpoints. -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive", "serde"] } -sp-std = { path = "../../substrate/primitives/std", default-features = false } -sp-runtime = { path = "../../substrate/primitives/runtime", default-features = false, features = ["serde"] } -sp-core = { path = "../../substrate/primitives/core", default-features = false, features = ["serde"] } -sp-weights = { path = "../../substrate/primitives/weights", default-features = false } -polkadot-core-primitives = { path = "../core-primitives", default-features = false } -derive_more = "0.99.11" -bounded-collections = { version = "0.2.0", default-features = false, features = ["serde"] } +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 } +polkadot-core-primitives = { workspace = true } +derive_more = { workspace = true, default-features = true } +bounded-collections = { features = ["serde"], workspace = true } # all optional crates. serde = { features = ["alloc", "derive"], workspace = true } diff --git a/polkadot/parachain/test-parachains/Cargo.toml b/polkadot/parachain/test-parachains/Cargo.toml index c58b11a11b01f9fb16d80fbe836cdcc956a84890..9f35653f957f3ba8423c5a1e47ca08a05d6bf6c5 100644 --- a/polkadot/parachain/test-parachains/Cargo.toml +++ b/polkadot/parachain/test-parachains/Cargo.toml @@ -11,14 +11,14 @@ publish = false workspace = true [dependencies] -tiny-keccak = { version = "2.0.2", features = ["keccak"] } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +tiny-keccak = { features = ["keccak"], workspace = true } +codec = { features = ["derive"], workspace = true } -test-parachain-adder = { path = "adder" } -test-parachain-halt = { path = "halt" } +test-parachain-adder = { workspace = true } +test-parachain-halt = { workspace = true } [dev-dependencies] -sp-core = { path = "../../../substrate/primitives/core" } +sp-core = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/polkadot/parachain/test-parachains/adder/Cargo.toml b/polkadot/parachain/test-parachains/adder/Cargo.toml index e0bbe177eedced788de07dc5bf753b4a2f9bb66e..1661112a7b3263caa55a9ced38b08f33ac6e3d2f 100644 --- a/polkadot/parachain/test-parachains/adder/Cargo.toml +++ b/polkadot/parachain/test-parachains/adder/Cargo.toml @@ -12,17 +12,17 @@ publish = false workspace = true [dependencies] -polkadot-parachain-primitives = { path = "../..", default-features = false, features = ["wasm-api"] } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -sp-std = { path = "../../../../substrate/primitives/std", default-features = false } -tiny-keccak = { version = "2.0.2", features = ["keccak"] } -dlmalloc = { version = "0.2.4", features = ["global"] } +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 } # We need to make sure the global allocator is disabled until we have support of full substrate externalities -sp-io = { path = "../../../../substrate/primitives/io", default-features = false, features = ["disable_allocator"] } +sp-io = { features = ["disable_allocator"], workspace = true } [build-dependencies] -substrate-wasm-builder = { path = "../../../../substrate/utils/wasm-builder" } +substrate-wasm-builder = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/polkadot/parachain/test-parachains/adder/collator/Cargo.toml b/polkadot/parachain/test-parachains/adder/collator/Cargo.toml index 996735e8c8bf8e641de15acf4bb2bd2e126c94fe..061378a76a82eb8edcf8823d7ee3d43d7d3fc7e9 100644 --- a/polkadot/parachain/test-parachains/adder/collator/Cargo.toml +++ b/polkadot/parachain/test-parachains/adder/collator/Cargo.toml @@ -15,30 +15,30 @@ name = "adder-collator" path = "src/main.rs" [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -clap = { version = "4.5.3", features = ["derive"] } -futures = "0.3.30" -futures-timer = "3.0.2" +codec = { features = ["derive"], workspace = true } +clap = { features = ["derive"], workspace = true } +futures = { workspace = true } +futures-timer = { workspace = true } log = { workspace = true, default-features = true } -test-parachain-adder = { path = ".." } -polkadot-primitives = { path = "../../../../primitives" } -polkadot-cli = { path = "../../../../cli" } -polkadot-service = { path = "../../../../node/service", features = ["rococo-native"] } -polkadot-node-primitives = { path = "../../../../node/primitives" } -polkadot-node-subsystem = { path = "../../../../node/subsystem" } +test-parachain-adder = { workspace = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-cli = { workspace = true, default-features = true } +polkadot-service = { features = ["rococo-native"], workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } -sc-cli = { path = "../../../../../substrate/client/cli" } -sp-core = { path = "../../../../../substrate/primitives/core" } -sc-service = { path = "../../../../../substrate/client/service" } +sc-cli = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sc-service = { workspace = true, default-features = true } [dev-dependencies] -polkadot-parachain-primitives = { path = "../../.." } -polkadot-test-service = { path = "../../../../node/test/service" } -polkadot-node-core-pvf = { path = "../../../../node/core/pvf", features = ["test-utils"] } +polkadot-parachain-primitives = { workspace = true, default-features = true } +polkadot-test-service = { workspace = true } +polkadot-node-core-pvf = { features = ["test-utils"], workspace = true, default-features = true } -substrate-test-utils = { path = "../../../../../substrate/test-utils" } -sc-service = { path = "../../../../../substrate/client/service" } -sp-keyring = { path = "../../../../../substrate/primitives/keyring" } +substrate-test-utils = { workspace = true } +sc-service = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } -tokio = { version = "1.24.2", features = ["macros"] } +tokio = { features = ["macros"], workspace = true, default-features = true } diff --git a/polkadot/parachain/test-parachains/halt/Cargo.toml b/polkadot/parachain/test-parachains/halt/Cargo.toml index 1bdd4392ad313dbdcf62d36bd04cab7330fdf3fb..f8272f6ed19681adf3faa57dfac3c4f126db6839 100644 --- a/polkadot/parachain/test-parachains/halt/Cargo.toml +++ b/polkadot/parachain/test-parachains/halt/Cargo.toml @@ -14,8 +14,8 @@ workspace = true [dependencies] [build-dependencies] -substrate-wasm-builder = { path = "../../../../substrate/utils/wasm-builder" } -rustversion = "1.0.6" +substrate-wasm-builder = { workspace = true, default-features = true } +rustversion = { workspace = true } [features] default = ["std"] diff --git a/polkadot/parachain/test-parachains/undying/Cargo.toml b/polkadot/parachain/test-parachains/undying/Cargo.toml index 4d3d2abaeafed85dea9a415da47b620981f1e5ca..2466c6a0d69d766f53aafab6c59ae35915570f23 100644 --- a/polkadot/parachain/test-parachains/undying/Cargo.toml +++ b/polkadot/parachain/test-parachains/undying/Cargo.toml @@ -12,18 +12,18 @@ license.workspace = true workspace = true [dependencies] -polkadot-parachain-primitives = { path = "../..", default-features = false, features = ["wasm-api"] } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -sp-std = { path = "../../../../substrate/primitives/std", default-features = false } -tiny-keccak = { version = "2.0.2", features = ["keccak"] } -dlmalloc = { version = "0.2.4", features = ["global"] } +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 } # We need to make sure the global allocator is disabled until we have support of full substrate externalities -sp-io = { path = "../../../../substrate/primitives/io", default-features = false, features = ["disable_allocator"] } +sp-io = { features = ["disable_allocator"], workspace = true } [build-dependencies] -substrate-wasm-builder = { path = "../../../../substrate/utils/wasm-builder" } +substrate-wasm-builder = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/polkadot/parachain/test-parachains/undying/collator/Cargo.toml b/polkadot/parachain/test-parachains/undying/collator/Cargo.toml index 288549c2c268ab93a3b39d5bc2e184a28b7dc158..5760258c70ea5757f5fda90abbfe5a41e5ee0fb4 100644 --- a/polkadot/parachain/test-parachains/undying/collator/Cargo.toml +++ b/polkadot/parachain/test-parachains/undying/collator/Cargo.toml @@ -15,30 +15,30 @@ name = "undying-collator" path = "src/main.rs" [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -clap = { version = "4.5.3", features = ["derive"] } -futures = "0.3.30" -futures-timer = "3.0.2" +codec = { features = ["derive"], workspace = true } +clap = { features = ["derive"], workspace = true } +futures = { workspace = true } +futures-timer = { workspace = true } log = { workspace = true, default-features = true } -test-parachain-undying = { path = ".." } -polkadot-primitives = { path = "../../../../primitives" } -polkadot-cli = { path = "../../../../cli" } -polkadot-service = { path = "../../../../node/service", features = ["rococo-native"] } -polkadot-node-primitives = { path = "../../../../node/primitives" } -polkadot-node-subsystem = { path = "../../../../node/subsystem" } +test-parachain-undying = { workspace = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-cli = { workspace = true, default-features = true } +polkadot-service = { features = ["rococo-native"], workspace = true, default-features = true } +polkadot-node-primitives = { workspace = true, default-features = true } +polkadot-node-subsystem = { workspace = true, default-features = true } -sc-cli = { path = "../../../../../substrate/client/cli" } -sp-core = { path = "../../../../../substrate/primitives/core" } -sc-service = { path = "../../../../../substrate/client/service" } +sc-cli = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sc-service = { workspace = true, default-features = true } [dev-dependencies] -polkadot-parachain-primitives = { path = "../../.." } -polkadot-test-service = { path = "../../../../node/test/service" } -polkadot-node-core-pvf = { path = "../../../../node/core/pvf", features = ["test-utils"] } +polkadot-parachain-primitives = { workspace = true, default-features = true } +polkadot-test-service = { workspace = true } +polkadot-node-core-pvf = { features = ["test-utils"], workspace = true, default-features = true } -substrate-test-utils = { path = "../../../../../substrate/test-utils" } -sc-service = { path = "../../../../../substrate/client/service" } -sp-keyring = { path = "../../../../../substrate/primitives/keyring" } +substrate-test-utils = { workspace = true } +sc-service = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } -tokio = { version = "1.24.2", features = ["macros"] } +tokio = { features = ["macros"], workspace = true, default-features = true } diff --git a/polkadot/primitives/Cargo.toml b/polkadot/primitives/Cargo.toml index d6df077b88b771ce556db3cc056745a5254a6bc5..c0b510a8fe9d0118fba52f7c8869210c3121969c 100644 --- a/polkadot/primitives/Cargo.toml +++ b/polkadot/primitives/Cargo.toml @@ -10,28 +10,28 @@ description = "Shared primitives used by Polkadot runtime" workspace = true [dependencies] -bitvec = { version = "1.0.0", default-features = false, features = ["alloc", "serde"] } -hex-literal = "0.4.1" -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["bit-vec", "derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["bit-vec", "derive", "serde"] } -log = { workspace = true, default-features = false } +bitvec = { features = ["alloc", "serde"], workspace = true } +hex-literal = { workspace = true, default-features = true } +codec = { features = ["bit-vec", "derive"], workspace = true } +scale-info = { features = ["bit-vec", "derive", "serde"], workspace = true } +log = { workspace = true } serde = { features = ["alloc", "derive"], workspace = true } -sp-application-crypto = { path = "../../substrate/primitives/application-crypto", default-features = false, features = ["serde"] } -sp-inherents = { path = "../../substrate/primitives/inherents", default-features = false } -sp-core = { path = "../../substrate/primitives/core", default-features = false } -sp-runtime = { path = "../../substrate/primitives/runtime", default-features = false } -sp-api = { path = "../../substrate/primitives/api", default-features = false } -sp-arithmetic = { path = "../../substrate/primitives/arithmetic", default-features = false, features = ["serde"] } -sp-authority-discovery = { path = "../../substrate/primitives/authority-discovery", default-features = false, features = ["serde"] } -sp-consensus-slots = { path = "../../substrate/primitives/consensus/slots", default-features = false, features = ["serde"] } -sp-io = { path = "../../substrate/primitives/io", default-features = false } -sp-keystore = { path = "../../substrate/primitives/keystore", optional = true, default-features = false } -sp-staking = { path = "../../substrate/primitives/staking", default-features = false, features = ["serde"] } -sp-std = { package = "sp-std", path = "../../substrate/primitives/std", default-features = false } +sp-application-crypto = { features = ["serde"], workspace = true } +sp-inherents = { workspace = true } +sp-core = { workspace = true } +sp-runtime = { workspace = true } +sp-api = { workspace = true } +sp-arithmetic = { features = ["serde"], workspace = true } +sp-authority-discovery = { features = ["serde"], workspace = true } +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 = { path = "../core-primitives", default-features = false } -polkadot-parachain-primitives = { path = "../parachain", default-features = false } +polkadot-core-primitives = { workspace = true } +polkadot-parachain-primitives = { workspace = true } [features] default = ["std"] diff --git a/polkadot/primitives/test-helpers/Cargo.toml b/polkadot/primitives/test-helpers/Cargo.toml index fab9480cfdeb9876c2556ae78a690775bf16d7a8..a44996ad6ef2dfdbeeea6c75fadb397d500eafec 100644 --- a/polkadot/primitives/test-helpers/Cargo.toml +++ b/polkadot/primitives/test-helpers/Cargo.toml @@ -10,9 +10,9 @@ license.workspace = true workspace = true [dependencies] -sp-keyring = { path = "../../../substrate/primitives/keyring" } -sp-application-crypto = { package = "sp-application-crypto", path = "../../../substrate/primitives/application-crypto", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime" } -sp-core = { path = "../../../substrate/primitives/core", features = ["std"] } -polkadot-primitives = { path = ".." } -rand = "0.8.5" +sp-keyring = { workspace = true, default-features = true } +sp-application-crypto = { workspace = true } +sp-runtime = { workspace = true, default-features = true } +sp-core = { features = ["std"], workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +rand = { workspace = true, default-features = true } diff --git a/polkadot/rpc/Cargo.toml b/polkadot/rpc/Cargo.toml index cceb4dc5a93b3f9ccf643572e1ba32b38aa5a853..d01528d4dee07d2d1d5ae59f5dac6a61e60fb197 100644 --- a/polkadot/rpc/Cargo.toml +++ b/polkadot/rpc/Cargo.toml @@ -10,31 +10,31 @@ description = "Polkadot specific RPC functionality." workspace = true [dependencies] -jsonrpsee = { version = "0.22", features = ["server"] } -polkadot-primitives = { path = "../primitives" } -sc-client-api = { path = "../../substrate/client/api" } -sp-blockchain = { path = "../../substrate/primitives/blockchain" } -sp-keystore = { path = "../../substrate/primitives/keystore" } -sp-runtime = { path = "../../substrate/primitives/runtime" } -sp-api = { path = "../../substrate/primitives/api" } -sp-application-crypto = { path = "../../substrate/primitives/application-crypto" } -sp-consensus = { path = "../../substrate/primitives/consensus/common" } -sp-consensus-babe = { path = "../../substrate/primitives/consensus/babe" } -sp-consensus-beefy = { path = "../../substrate/primitives/consensus/beefy" } -sc-chain-spec = { path = "../../substrate/client/chain-spec" } -sc-rpc = { path = "../../substrate/client/rpc" } -sc-rpc-spec-v2 = { path = "../../substrate/client/rpc-spec-v2" } -sc-consensus-babe = { path = "../../substrate/client/consensus/babe" } -sc-consensus-babe-rpc = { path = "../../substrate/client/consensus/babe/rpc" } -sc-consensus-beefy = { path = "../../substrate/client/consensus/beefy" } -sc-consensus-beefy-rpc = { path = "../../substrate/client/consensus/beefy/rpc" } -sc-consensus-epochs = { path = "../../substrate/client/consensus/epochs" } -sc-consensus-grandpa = { path = "../../substrate/client/consensus/grandpa" } -sc-consensus-grandpa-rpc = { path = "../../substrate/client/consensus/grandpa/rpc" } -sc-sync-state-rpc = { path = "../../substrate/client/sync-state-rpc" } -sc-transaction-pool-api = { path = "../../substrate/client/transaction-pool/api" } -substrate-frame-rpc-system = { path = "../../substrate/utils/frame/rpc/system" } -mmr-rpc = { path = "../../substrate/client/merkle-mountain-range/rpc" } -pallet-transaction-payment-rpc = { path = "../../substrate/frame/transaction-payment/rpc" } -sp-block-builder = { path = "../../substrate/primitives/block-builder" } -substrate-state-trie-migration-rpc = { path = "../../substrate/utils/frame/rpc/state-trie-migration-rpc" } +jsonrpsee = { features = ["server"], workspace = true } +polkadot-primitives = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-application-crypto = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-consensus-babe = { workspace = true, default-features = true } +sp-consensus-beefy = { workspace = true, default-features = true } +sc-chain-spec = { workspace = true, default-features = true } +sc-rpc = { workspace = true, default-features = true } +sc-rpc-spec-v2 = { workspace = true, default-features = true } +sc-consensus-babe = { workspace = true, default-features = true } +sc-consensus-babe-rpc = { workspace = true, default-features = true } +sc-consensus-beefy = { workspace = true, default-features = true } +sc-consensus-beefy-rpc = { workspace = true, default-features = true } +sc-consensus-epochs = { workspace = true, default-features = true } +sc-consensus-grandpa = { workspace = true, default-features = true } +sc-consensus-grandpa-rpc = { workspace = true, default-features = true } +sc-sync-state-rpc = { workspace = true, default-features = true } +sc-transaction-pool-api = { workspace = true, default-features = true } +substrate-frame-rpc-system = { workspace = true, default-features = true } +mmr-rpc = { workspace = true, default-features = true } +pallet-transaction-payment-rpc = { workspace = true, default-features = true } +sp-block-builder = { workspace = true, default-features = true } +substrate-state-trie-migration-rpc = { workspace = true, default-features = true } diff --git a/polkadot/runtime/common/Cargo.toml b/polkadot/runtime/common/Cargo.toml index da89bd2251acff0d0c76b49908109a1ff662846c..718f8b8b070996fb5266ef857e7ba6295edfa676 100644 --- a/polkadot/runtime/common/Cargo.toml +++ b/polkadot/runtime/common/Cargo.toml @@ -10,66 +10,66 @@ license.workspace = true workspace = true [dependencies] -impl-trait-for-tuples = "0.2.2" -bitvec = { version = "1.0.0", default-features = false, features = ["alloc"] } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +impl-trait-for-tuples = { workspace = true } +bitvec = { features = ["alloc"], workspace = true } +codec = { features = ["derive"], workspace = true } log = { workspace = true } -rustc-hex = { version = "2.1.0", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +rustc-hex = { workspace = true } +scale-info = { features = ["derive"], workspace = true } serde = { features = ["alloc"], workspace = true } serde_derive = { workspace = true } -static_assertions = "1.1.0" +static_assertions = { workspace = true, default-features = true } -sp-api = { path = "../../../substrate/primitives/api", default-features = false } -sp-inherents = { path = "../../../substrate/primitives/inherents", default-features = false } -sp-std = { package = "sp-std", path = "../../../substrate/primitives/std", default-features = false } -sp-io = { path = "../../../substrate/primitives/io", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false, features = ["serde"] } -sp-session = { path = "../../../substrate/primitives/session", default-features = false } -sp-staking = { path = "../../../substrate/primitives/staking", default-features = false, features = ["serde"] } -sp-core = { path = "../../../substrate/primitives/core", default-features = false, features = ["serde"] } -sp-npos-elections = { path = "../../../substrate/primitives/npos-elections", default-features = false, features = ["serde"] } +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 } +sp-staking = { features = ["serde"], workspace = true } +sp-core = { features = ["serde"], workspace = true } +sp-npos-elections = { features = ["serde"], workspace = true } -pallet-authorship = { path = "../../../substrate/frame/authorship", default-features = false } -pallet-balances = { path = "../../../substrate/frame/balances", default-features = false } -pallet-broker = { path = "../../../substrate/frame/broker", default-features = false } -pallet-fast-unstake = { path = "../../../substrate/frame/fast-unstake", default-features = false } -pallet-identity = { path = "../../../substrate/frame/identity", default-features = false } -pallet-session = { path = "../../../substrate/frame/session", default-features = false } -frame-support = { path = "../../../substrate/frame/support", default-features = false } -pallet-staking = { path = "../../../substrate/frame/staking", default-features = false } -pallet-staking-reward-fn = { path = "../../../substrate/frame/staking/reward-fn", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -pallet-timestamp = { path = "../../../substrate/frame/timestamp", default-features = false } -pallet-vesting = { path = "../../../substrate/frame/vesting", default-features = false } -pallet-transaction-payment = { path = "../../../substrate/frame/transaction-payment", default-features = false } -pallet-treasury = { path = "../../../substrate/frame/treasury", default-features = false } -pallet-asset-rate = { path = "../../../substrate/frame/asset-rate", default-features = false, optional = true } -pallet-election-provider-multi-phase = { path = "../../../substrate/frame/election-provider-multi-phase", default-features = false } -frame-election-provider-support = { path = "../../../substrate/frame/election-provider-support", default-features = false } +pallet-authorship = { workspace = true } +pallet-balances = { workspace = true } +pallet-broker = { workspace = true } +pallet-fast-unstake = { workspace = true } +pallet-identity = { workspace = true } +pallet-session = { workspace = true } +frame-support = { workspace = true } +pallet-staking = { workspace = true } +pallet-staking-reward-fn = { workspace = true } +frame-system = { workspace = true } +pallet-timestamp = { workspace = true } +pallet-vesting = { workspace = true } +pallet-transaction-payment = { workspace = true } +pallet-treasury = { workspace = true } +pallet-asset-rate = { optional = true, workspace = true } +pallet-election-provider-multi-phase = { workspace = true } +frame-election-provider-support = { workspace = true } -frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-features = false, optional = true } -pallet-babe = { path = "../../../substrate/frame/babe", default-features = false, optional = true } +frame-benchmarking = { optional = true, workspace = true } +pallet-babe = { optional = true, workspace = true } -polkadot-primitives = { path = "../../primitives", default-features = false } -libsecp256k1 = { version = "0.7.0", default-features = false } -polkadot-runtime-parachains = { path = "../parachains", default-features = false } +polkadot-primitives = { workspace = true } +libsecp256k1 = { workspace = true } +polkadot-runtime-parachains = { workspace = true } -slot-range-helper = { path = "slot_range_helper", default-features = false } -xcm = { package = "staging-xcm", path = "../../xcm", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../xcm/xcm-executor", default-features = false, optional = true } -xcm-builder = { package = "staging-xcm-builder", path = "../../xcm/xcm-builder", default-features = false } +slot-range-helper = { workspace = true } +xcm = { workspace = true } +xcm-executor = { optional = true, workspace = true } +xcm-builder = { workspace = true } [dev-dependencies] -hex-literal = "0.4.1" -frame-support-test = { path = "../../../substrate/frame/support/test" } -pallet-babe = { path = "../../../substrate/frame/babe" } -pallet-treasury = { path = "../../../substrate/frame/treasury" } -sp-keystore = { path = "../../../substrate/primitives/keystore" } -sp-keyring = { path = "../../../substrate/primitives/keyring" } +hex-literal = { workspace = true, default-features = true } +frame-support-test = { workspace = true } +pallet-babe = { workspace = true, default-features = true } +pallet-treasury = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } -libsecp256k1 = "0.7.0" -polkadot-primitives-test-helpers = { path = "../../primitives/test-helpers" } +libsecp256k1 = { workspace = true, default-features = true } +polkadot-primitives-test-helpers = { workspace = true } [features] default = ["std"] diff --git a/polkadot/runtime/common/slot_range_helper/Cargo.toml b/polkadot/runtime/common/slot_range_helper/Cargo.toml index 47e8fea240025c02c2e6efa81ebbe54f7e3da115..6beca68f7678f3b575f68551b7283880aaf78915 100644 --- a/polkadot/runtime/common/slot_range_helper/Cargo.toml +++ b/polkadot/runtime/common/slot_range_helper/Cargo.toml @@ -10,11 +10,11 @@ description = "Helper crate for generating slot ranges for the Polkadot runtime. workspace = true [dependencies] -paste = "1.0" -enumn = "0.1.12" -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -sp-std = { package = "sp-std", path = "../../../../substrate/primitives/std", default-features = false } -sp-runtime = { path = "../../../../substrate/primitives/runtime", default-features = false } +paste = { workspace = true, default-features = true } +enumn = { workspace = true } +codec = { features = ["derive"], workspace = true } +sp-std = { workspace = true } +sp-runtime = { workspace = true } [features] default = ["std"] diff --git a/polkadot/runtime/common/src/assigned_slots/mod.rs b/polkadot/runtime/common/src/assigned_slots/mod.rs index 368708f256403d88d2f41cf105dd4dcc20892f28..d0a531b8b6ca5ad995803edc8cbc45daa88176c2 100644 --- a/polkadot/runtime/common/src/assigned_slots/mod.rs +++ b/polkadot/runtime/common/src/assigned_slots/mod.rs @@ -698,24 +698,9 @@ mod tests { type MaxConsumers = frame_support::traits::ConstU32<16>; } - parameter_types! { - pub const ExistentialDeposit: u64 = 1; - } - + #[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type Balance = u64; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type WeightInfo = (); - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeFreezeReason; - type FreezeIdentifier = (); - type MaxFreezes = ConstU32<1>; } impl parachains_configuration::Config for Test { diff --git a/polkadot/runtime/common/src/auctions.rs b/polkadot/runtime/common/src/auctions.rs index 199b18fba51dc4f1c0b2e49b1f6429d0526e3306..19d82ae85d0035aea89b5d07f0f042be237da42e 100644 --- a/polkadot/runtime/common/src/auctions.rs +++ b/polkadot/runtime/common/src/auctions.rs @@ -674,7 +674,7 @@ mod tests { use frame_support::{ assert_noop, assert_ok, assert_storage_noop, derive_impl, ord_parameter_types, parameter_types, - traits::{ConstU32, EitherOfDiverse, OnFinalize, OnInitialize}, + traits::{EitherOfDiverse, OnFinalize, OnInitialize}, }; use frame_system::{EnsureRoot, EnsureSignedBy}; use pallet_balances; @@ -725,25 +725,9 @@ mod tests { type MaxConsumers = frame_support::traits::ConstU32<16>; } - parameter_types! { - pub const ExistentialDeposit: u64 = 1; - pub const MaxReserves: u32 = 50; - } - + #[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type Balance = u64; - type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; - type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type WeightInfo = (); - type MaxLocks = (); - type MaxReserves = MaxReserves; - type ReserveIdentifier = [u8; 8]; - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeFreezeReason; - type FreezeIdentifier = (); - type MaxFreezes = ConstU32<1>; } #[derive(Eq, PartialEq, Ord, PartialOrd, Clone, Copy, Debug)] @@ -1426,7 +1410,8 @@ mod tests { #[test] fn initialize_winners_in_ending_period_works() { new_test_ext().execute_with(|| { - assert_eq!(::ExistentialDeposit::get(), 1); + let ed: u64 = ::ExistentialDeposit::get(); + assert_eq!(ed, 1); run_to_block(1); assert_ok!(Auctions::new_auction(RuntimeOrigin::signed(6), 9, 1)); let para_1 = ParaId::from(1_u32); @@ -1539,7 +1524,8 @@ mod tests { #[test] fn less_winning_samples_work() { new_test_ext().execute_with(|| { - assert_eq!(::ExistentialDeposit::get(), 1); + let ed: u64 = ::ExistentialDeposit::get(); + assert_eq!(ed, 1); EndingPeriod::set(30); SampleLength::set(10); diff --git a/polkadot/runtime/common/src/claims.rs b/polkadot/runtime/common/src/claims.rs index 54208e7fd1351202c0ee64bd9d0fc8adcab09b84..c12af215a04d7119c1052a09a6eb6bee7ac0acb3 100644 --- a/polkadot/runtime/common/src/claims.rs +++ b/polkadot/runtime/common/src/claims.rs @@ -708,7 +708,7 @@ mod tests { assert_err, assert_noop, assert_ok, derive_impl, dispatch::{GetDispatchInfo, Pays}, ord_parameter_types, parameter_types, - traits::{ConstU32, ExistenceRequirement, WithdrawReasons}, + traits::{ExistenceRequirement, WithdrawReasons}, }; use pallet_balances; use sp_runtime::{ @@ -738,24 +738,9 @@ mod tests { type MaxConsumers = frame_support::traits::ConstU32<16>; } - parameter_types! { - pub const ExistentialDeposit: u64 = 1; - } - + #[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type Balance = u64; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type WeightInfo = (); - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeFreezeReason; - type FreezeIdentifier = (); - type MaxFreezes = ConstU32<1>; } parameter_types! { diff --git a/polkadot/runtime/common/src/crowdloan/mod.rs b/polkadot/runtime/common/src/crowdloan/mod.rs index 1dbba363de5661481093f40288e68928c9747eb5..61d406aa681268d8ef0c66567faf7b74555a287d 100644 --- a/polkadot/runtime/common/src/crowdloan/mod.rs +++ b/polkadot/runtime/common/src/crowdloan/mod.rs @@ -860,7 +860,7 @@ mod tests { use frame_support::{ assert_noop, assert_ok, derive_impl, parameter_types, - traits::{ConstU32, OnFinalize, OnInitialize}, + traits::{OnFinalize, OnInitialize}, }; use polkadot_primitives::Id as ParaId; use sp_core::H256; @@ -918,24 +918,9 @@ mod tests { type MaxConsumers = frame_support::traits::ConstU32<16>; } - parameter_types! { - pub const ExistentialDeposit: u64 = 1; - } - + #[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type Balance = u64; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type WeightInfo = (); - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeFreezeReason; - type FreezeIdentifier = (); - type MaxFreezes = ConstU32<1>; } #[derive(Copy, Clone, Eq, PartialEq, Debug)] @@ -980,7 +965,7 @@ mod tests { let fund = Funds::::get(para).unwrap(); let account_id = Crowdloan::fund_account_id(fund.fund_index); if winner { - let ed = ::ExistentialDeposit::get(); + let ed: u64 = ::ExistentialDeposit::get(); let free_balance = Balances::free_balance(&account_id); Balances::reserve(&account_id, free_balance - ed) .expect("should be able to reserve free balance minus ED"); @@ -1815,7 +1800,8 @@ mod tests { #[test] fn withdraw_from_finished_works() { new_test_ext().execute_with(|| { - assert_eq!(::ExistentialDeposit::get(), 1); + let ed: u64 = ::ExistentialDeposit::get(); + assert_eq!(ed, 1); let para = new_para(); let index = NextFundIndex::::get(); let account_id = Crowdloan::fund_account_id(index); diff --git a/polkadot/runtime/common/src/impls.rs b/polkadot/runtime/common/src/impls.rs index 662a7ae9708450a63766e615f9ae53e93f570d53..b135e73a66f7b8f1d5695333ad35fcdaecfd11c5 100644 --- a/polkadot/runtime/common/src/impls.rs +++ b/polkadot/runtime/common/src/impls.rs @@ -273,7 +273,7 @@ mod tests { parameter_types, traits::{ tokens::{PayFromAccount, UnityAssetBalanceConversion}, - ConstU32, FindAuthor, + FindAuthor, }, weights::Weight, PalletId, @@ -339,20 +339,9 @@ mod tests { type MaxConsumers = frame_support::traits::ConstU32<16>; } + #[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type Balance = u64; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ConstU64<1>; type AccountStore = System; - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type WeightInfo = (); - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeFreezeReason; - type FreezeIdentifier = (); - type MaxFreezes = ConstU32<1>; } parameter_types! { @@ -363,13 +352,8 @@ mod tests { impl pallet_treasury::Config for Test { type Currency = pallet_balances::Pallet; - type ApproveOrigin = frame_system::EnsureRoot; type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; - type OnSlash = (); - type ProposalBond = (); - type ProposalBondMinimum = (); - type ProposalBondMaximum = (); type SpendPeriod = (); type Burn = (); type BurnDestination = (); diff --git a/polkadot/runtime/common/src/integration_tests.rs b/polkadot/runtime/common/src/integration_tests.rs index e77035b3f6b414fcf6af1fa1f93fa14428fe8ac1..052fb0389db40c086d2c13b3d30501e093ef5f90 100644 --- a/polkadot/runtime/common/src/integration_tests.rs +++ b/polkadot/runtime/common/src/integration_tests.rs @@ -173,23 +173,12 @@ impl pallet_timestamp::Config for Test { parameter_types! { pub static ExistentialDeposit: Balance = 1; - pub const MaxReserves: u32 = 50; } - +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxLocks = (); type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type WeightInfo = (); - type MaxReserves = MaxReserves; - type ReserveIdentifier = [u8; 8]; - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeFreezeReason; - type FreezeIdentifier = (); - type MaxFreezes = ConstU32<0>; } impl configuration::Config for Test { diff --git a/polkadot/runtime/common/src/paras_registrar/mod.rs b/polkadot/runtime/common/src/paras_registrar/mod.rs index 9bbb152f855f2a3e8f37925cd4006ccb4554ab92..6b9191f7c6f2db0f9e98b0a67ead596d4c3a9822 100644 --- a/polkadot/runtime/common/src/paras_registrar/mod.rs +++ b/polkadot/runtime/common/src/paras_registrar/mod.rs @@ -721,7 +721,7 @@ mod tests { assert_noop, assert_ok, derive_impl, error::BadOrigin, parameter_types, - traits::{ConstU32, OnFinalize, OnInitialize}, + traits::{OnFinalize, OnInitialize}, }; use frame_system::limits; use pallet_balances::Error as BalancesError; @@ -799,20 +799,11 @@ mod tests { pub const ExistentialDeposit: Balance = 1; } + #[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type Balance = u128; - type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; + type Balance = Balance; type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type WeightInfo = (); - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeFreezeReason; - type FreezeIdentifier = (); - type MaxFreezes = ConstU32<1>; } impl shared::Config for Test { diff --git a/polkadot/runtime/common/src/purchase.rs b/polkadot/runtime/common/src/purchase.rs index 5ae6b422618e09946750de2def845acc1bc0689f..eb480e4efe1f82f657daaa03cd33d883a01d9f7d 100644 --- a/polkadot/runtime/common/src/purchase.rs +++ b/polkadot/runtime/common/src/purchase.rs @@ -534,24 +534,9 @@ mod tests { type MaxConsumers = frame_support::traits::ConstU32<16>; } - parameter_types! { - pub const ExistentialDeposit: u64 = 1; - } - + #[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type Balance = u64; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type WeightInfo = (); - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeFreezeReason; - type FreezeIdentifier = (); - type MaxFreezes = ConstU32<1>; } parameter_types! { diff --git a/polkadot/runtime/common/src/slots/mod.rs b/polkadot/runtime/common/src/slots/mod.rs index 900e04eaff1882d5c1faeb3494dc7c87f1c112bf..747b7b5ca634ed0563061aea2d169624a2ed87ac 100644 --- a/polkadot/runtime/common/src/slots/mod.rs +++ b/polkadot/runtime/common/src/slots/mod.rs @@ -551,24 +551,9 @@ mod tests { type MaxConsumers = frame_support::traits::ConstU32<16>; } - parameter_types! { - pub const ExistentialDeposit: u64 = 1; - } - + #[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type Balance = u64; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type WeightInfo = (); - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeFreezeReason; - type FreezeIdentifier = (); - type MaxFreezes = ConstU32<1>; } parameter_types! { diff --git a/polkadot/runtime/common/src/traits.rs b/polkadot/runtime/common/src/traits.rs index 2ed1fb8af9beacda31b0134ebc72c95b24c2d8cd..eadeac74fcdb63cab542ca080cd372b5fbd4f4fd 100644 --- a/polkadot/runtime/common/src/traits.rs +++ b/polkadot/runtime/common/src/traits.rs @@ -56,7 +56,7 @@ pub trait Registrar { /// Remove any lock on the para registration. fn remove_lock(id: ParaId); - /// Register a Para ID under control of `who`. Registration may be be + /// Register a Para ID under control of `who`. Registration may be /// delayed by session rotation. fn register( who: Self::AccountId, diff --git a/polkadot/runtime/metrics/Cargo.toml b/polkadot/runtime/metrics/Cargo.toml index 342c5a885033884f025c34cadca03f37e1a7297e..54c685effc1165f7528029f01717ee1ad6f3a298 100644 --- a/polkadot/runtime/metrics/Cargo.toml +++ b/polkadot/runtime/metrics/Cargo.toml @@ -10,13 +10,13 @@ description = "Runtime metric interface for the Polkadot node" workspace = true [dependencies] -sp-std = { package = "sp-std", path = "../../../substrate/primitives/std", default-features = false } -sp-tracing = { path = "../../../substrate/primitives/tracing", default-features = false } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -polkadot-primitives = { path = "../../primitives", default-features = false } -frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-features = false, optional = true } +sp-std = { workspace = true } +sp-tracing = { workspace = true } +codec = { workspace = true } +polkadot-primitives = { workspace = true } +frame-benchmarking = { optional = true, workspace = true } -bs58 = { version = "0.5.0", default-features = false, features = ["alloc"] } +bs58 = { features = ["alloc"], workspace = true } [features] default = ["std"] diff --git a/polkadot/runtime/parachains/Cargo.toml b/polkadot/runtime/parachains/Cargo.toml index 250fee65beefe7af6e9762b8ebcca8020b6a556a..82ba22a70f37b0e8fb5049fbcd6ca60c1eb5c8a1 100644 --- a/polkadot/runtime/parachains/Cargo.toml +++ b/polkadot/runtime/parachains/Cargo.toml @@ -10,66 +10,65 @@ license.workspace = true workspace = true [dependencies] -impl-trait-for-tuples = "0.2.2" -bitvec = { version = "1.0.0", default-features = false, features = ["alloc"] } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive", "max-encoded-len"] } +impl-trait-for-tuples = { workspace = true } +bitvec = { features = ["alloc"], workspace = true } +codec = { features = ["derive", "max-encoded-len"], workspace = true } log = { workspace = true } -rustc-hex = { version = "2.1.0", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } serde = { features = ["alloc", "derive"], workspace = true } -derive_more = "0.99.17" -bitflags = "1.3.2" +derive_more = { workspace = true, default-features = true } +bitflags = { workspace = true } -sp-api = { path = "../../../substrate/primitives/api", default-features = false } -sp-inherents = { path = "../../../substrate/primitives/inherents", default-features = false } -sp-std = { package = "sp-std", path = "../../../substrate/primitives/std", default-features = false } -sp-io = { path = "../../../substrate/primitives/io", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false, features = ["serde"] } -sp-session = { path = "../../../substrate/primitives/session", default-features = false } -sp-staking = { path = "../../../substrate/primitives/staking", default-features = false, features = ["serde"] } -sp-core = { path = "../../../substrate/primitives/core", default-features = false, features = ["serde"] } -sp-keystore = { path = "../../../substrate/primitives/keystore", optional = true, default-features = false } -sp-application-crypto = { path = "../../../substrate/primitives/application-crypto", default-features = false, optional = true } -sp-tracing = { path = "../../../substrate/primitives/tracing", default-features = false, optional = true } -sp-arithmetic = { path = "../../../substrate/primitives/arithmetic", default-features = false } +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 } +sp-staking = { features = ["serde"], workspace = true } +sp-core = { features = ["serde"], workspace = true } +sp-keystore = { optional = true, workspace = true } +sp-application-crypto = { optional = true, workspace = true } +sp-tracing = { optional = true, workspace = true } +sp-arithmetic = { workspace = true } -pallet-authority-discovery = { path = "../../../substrate/frame/authority-discovery", default-features = false } -pallet-authorship = { path = "../../../substrate/frame/authorship", default-features = false } -pallet-balances = { path = "../../../substrate/frame/balances", default-features = false } -pallet-babe = { path = "../../../substrate/frame/babe", default-features = false } -pallet-broker = { path = "../../../substrate/frame/broker", default-features = false } -pallet-message-queue = { path = "../../../substrate/frame/message-queue", default-features = false } -pallet-session = { path = "../../../substrate/frame/session", default-features = false } -pallet-staking = { path = "../../../substrate/frame/staking", default-features = false } -pallet-timestamp = { path = "../../../substrate/frame/timestamp", default-features = false } -pallet-vesting = { path = "../../../substrate/frame/vesting", default-features = false } -frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-support = { path = "../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } +pallet-authority-discovery = { workspace = true } +pallet-authorship = { workspace = true } +pallet-balances = { workspace = true } +pallet-babe = { workspace = true } +pallet-broker = { workspace = true } +pallet-message-queue = { workspace = true } +pallet-session = { workspace = true } +pallet-staking = { workspace = true } +pallet-timestamp = { workspace = true } +pallet-vesting = { workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } -xcm = { package = "staging-xcm", path = "../../xcm", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../xcm/xcm-executor", default-features = false } -polkadot-primitives = { path = "../../primitives", default-features = false } +xcm = { workspace = true } +xcm-executor = { workspace = true } +polkadot-primitives = { workspace = true } -rand = { version = "0.8.5", default-features = false } -rand_chacha = { version = "0.3.1", default-features = false } -static_assertions = { version = "1.1.0", optional = true } -polkadot-parachain-primitives = { path = "../../parachain", default-features = false } -polkadot-runtime-metrics = { path = "../metrics", default-features = false } -polkadot-core-primitives = { path = "../../core-primitives", default-features = false } +rand = { workspace = true } +rand_chacha = { workspace = true } +static_assertions = { optional = true, workspace = true, default-features = true } +polkadot-parachain-primitives = { workspace = true } +polkadot-runtime-metrics = { workspace = true } +polkadot-core-primitives = { workspace = true } [dev-dependencies] -futures = "0.3.30" -hex-literal = "0.4.1" -sp-keyring = { path = "../../../substrate/primitives/keyring" } -frame-support-test = { path = "../../../substrate/frame/support/test" } -sc-keystore = { path = "../../../substrate/client/keystore" } -polkadot-primitives-test-helpers = { path = "../../primitives/test-helpers" } -sp-tracing = { path = "../../../substrate/primitives/tracing" } -sp-crypto-hashing = { path = "../../../substrate/primitives/crypto/hashing" } -thousands = "0.2.0" -assert_matches = "1" -rstest = "0.18.2" +futures = { workspace = true } +hex-literal = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +frame-support-test = { workspace = true } +sc-keystore = { workspace = true, default-features = true } +polkadot-primitives-test-helpers = { workspace = true } +sp-tracing = { workspace = true, default-features = true } +sp-crypto-hashing = { workspace = true, default-features = true } +thousands = { workspace = true } +assert_matches = { workspace = true } +rstest = { workspace = true } serde_json = { workspace = true, default-features = true } [features] @@ -98,7 +97,6 @@ std = [ "polkadot-runtime-metrics/std", "rand/std", "rand_chacha/std", - "rustc-hex/std", "scale-info/std", "serde/std", "sp-api/std", diff --git a/polkadot/runtime/parachains/src/mock.rs b/polkadot/runtime/parachains/src/mock.rs index 0a0be8432b2520201d52e6598058940794e8b53b..18722ff463cf2398a209bf5589d5acea3283ac84 100644 --- a/polkadot/runtime/parachains/src/mock.rs +++ b/polkadot/runtime/parachains/src/mock.rs @@ -139,20 +139,11 @@ parameter_types! { pub static ExistentialDeposit: u64 = 1; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type WeightInfo = (); - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeFreezeReason; - type FreezeIdentifier = (); - type MaxFreezes = ConstU32<0>; } parameter_types! { diff --git a/polkadot/runtime/parachains/src/runtime_api_impl/vstaging.rs b/polkadot/runtime/parachains/src/runtime_api_impl/vstaging.rs index 62e96e9fbb0511f5b188ff60a76a6d1620188d9b..f4e3db185fead7144e6cb0ae3455af98229d59f7 100644 --- a/polkadot/runtime/parachains/src/runtime_api_impl/vstaging.rs +++ b/polkadot/runtime/parachains/src/runtime_api_impl/vstaging.rs @@ -28,10 +28,10 @@ use sp_std::{ pub fn claim_queue() -> BTreeMap> { let now = >::block_number() + One::one(); - // This explicit update is only strictly required for session boundaries: - // - // At the end of a session we clear the claim queues: Without this update call, nothing would be - // scheduled to the client. + // This is needed so that the claim queue always has the right size (equal to + // scheduling_lookahead). Otherwise, if a candidate is backed in the same block where the + // previous candidate is included, the claim queue will have already pop()-ed the next item + // from the queue and the length would be `scheduling_lookahead - 1`. >::free_cores_and_fill_claim_queue(Vec::new(), now); let config = configuration::ActiveConfig::::get(); // Extra sanity, config should already never be smaller than 1: diff --git a/polkadot/runtime/parachains/src/scheduler.rs b/polkadot/runtime/parachains/src/scheduler.rs index 33b4d849c490f2bcbb3e931118dad8f5c5c3850b..d7fe5c06863c87413f988a972790c5d3482b513f 100644 --- a/polkadot/runtime/parachains/src/scheduler.rs +++ b/polkadot/runtime/parachains/src/scheduler.rs @@ -351,6 +351,9 @@ impl Pallet { } /// Note that the given cores have become occupied. Update the claim queue accordingly. + /// This will not push a new entry onto the claim queue, so the length after this call will be + /// the expected length - 1. The claim_queue runtime API will take care of adding another entry + /// here, to ensure the right lookahead. pub(crate) fn occupied( now_occupied: BTreeMap, ) -> BTreeMap { diff --git a/polkadot/runtime/rococo/Cargo.toml b/polkadot/runtime/rococo/Cargo.toml index d342926d3c5a08eb50e6317882a9b4521c3115d2..c4fbd461a631849010e4d3de7ab98a7b743432fb 100644 --- a/polkadot/runtime/rococo/Cargo.toml +++ b/polkadot/runtime/rococo/Cargo.toml @@ -11,117 +11,117 @@ license.workspace = true workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive", "max-encoded-len"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive", "max-encoded-len"], workspace = true } +scale-info = { features = ["derive"], workspace = true } log = { workspace = true } serde = { workspace = true } serde_derive = { optional = true, workspace = true } serde_json = { features = ["alloc"], workspace = true } -static_assertions = "1.1.0" -smallvec = "1.8.0" -bitvec = { version = "1.0.1", default-features = false, features = ["alloc"] } +static_assertions = { workspace = true, default-features = true } +smallvec = { workspace = true, default-features = true } +bitvec = { features = ["alloc"], workspace = true } -sp-authority-discovery = { path = "../../../substrate/primitives/authority-discovery", default-features = false } -sp-consensus-babe = { path = "../../../substrate/primitives/consensus/babe", default-features = false } -sp-consensus-beefy = { path = "../../../substrate/primitives/consensus/beefy", default-features = false } -sp-consensus-grandpa = { path = "../../../substrate/primitives/consensus/grandpa", default-features = false } -binary-merkle-tree = { path = "../../../substrate/utils/binary-merkle-tree", default-features = false } -rococo-runtime-constants = { package = "rococo-runtime-constants", path = "constants", default-features = false } -sp-api = { path = "../../../substrate/primitives/api", default-features = false } -sp-genesis-builder = { path = "../../../substrate/primitives/genesis-builder", default-features = false } -sp-inherents = { path = "../../../substrate/primitives/inherents", default-features = false } -sp-offchain = { path = "../../../substrate/primitives/offchain", default-features = false } -sp-arithmetic = { path = "../../../substrate/primitives/arithmetic", default-features = false } -sp-std = { package = "sp-std", path = "../../../substrate/primitives/std", default-features = false } -sp-io = { path = "../../../substrate/primitives/io", default-features = false } -sp-mmr-primitives = { path = "../../../substrate/primitives/merkle-mountain-range", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-staking = { path = "../../../substrate/primitives/staking", default-features = false } -sp-core = { path = "../../../substrate/primitives/core", default-features = false } -sp-session = { path = "../../../substrate/primitives/session", default-features = false } -sp-storage = { path = "../../../substrate/primitives/storage", default-features = false } -sp-version = { path = "../../../substrate/primitives/version", default-features = false } -sp-transaction-pool = { path = "../../../substrate/primitives/transaction-pool", default-features = false } -sp-block-builder = { path = "../../../substrate/primitives/block-builder", default-features = false } +sp-authority-discovery = { workspace = true } +sp-consensus-babe = { workspace = true } +sp-consensus-beefy = { workspace = true } +sp-consensus-grandpa = { workspace = true } +binary-merkle-tree = { workspace = true } +rococo-runtime-constants = { workspace = true } +sp-api = { workspace = true } +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 } +sp-staking = { workspace = true } +sp-core = { workspace = true } +sp-session = { workspace = true } +sp-storage = { workspace = true } +sp-version = { workspace = true } +sp-transaction-pool = { workspace = true } +sp-block-builder = { workspace = true } -pallet-authority-discovery = { path = "../../../substrate/frame/authority-discovery", default-features = false } -pallet-authorship = { path = "../../../substrate/frame/authorship", default-features = false } -pallet-babe = { path = "../../../substrate/frame/babe", default-features = false } -pallet-balances = { path = "../../../substrate/frame/balances", default-features = false } -pallet-beefy = { path = "../../../substrate/frame/beefy", default-features = false } -pallet-beefy-mmr = { path = "../../../substrate/frame/beefy-mmr", default-features = false } -pallet-bounties = { path = "../../../substrate/frame/bounties", default-features = false } -pallet-child-bounties = { path = "../../../substrate/frame/child-bounties", default-features = false } -pallet-state-trie-migration = { path = "../../../substrate/frame/state-trie-migration", default-features = false } -pallet-transaction-payment = { path = "../../../substrate/frame/transaction-payment", default-features = false } -pallet-transaction-payment-rpc-runtime-api = { path = "../../../substrate/frame/transaction-payment/rpc/runtime-api", default-features = false } -pallet-collective = { path = "../../../substrate/frame/collective", default-features = false } -pallet-conviction-voting = { path = "../../../substrate/frame/conviction-voting", default-features = false } -pallet-democracy = { path = "../../../substrate/frame/democracy", default-features = false } -pallet-elections-phragmen = { path = "../../../substrate/frame/elections-phragmen", default-features = false } -pallet-asset-rate = { path = "../../../substrate/frame/asset-rate", default-features = false } -frame-executive = { path = "../../../substrate/frame/executive", default-features = false } -pallet-grandpa = { path = "../../../substrate/frame/grandpa", default-features = false } -pallet-identity = { path = "../../../substrate/frame/identity", default-features = false } -pallet-indices = { path = "../../../substrate/frame/indices", default-features = false } -pallet-membership = { path = "../../../substrate/frame/membership", default-features = false } -pallet-message-queue = { path = "../../../substrate/frame/message-queue", default-features = false } -pallet-mmr = { path = "../../../substrate/frame/merkle-mountain-range", default-features = false } -pallet-multisig = { path = "../../../substrate/frame/multisig", default-features = false } -pallet-nis = { path = "../../../substrate/frame/nis", default-features = false } -pallet-offences = { path = "../../../substrate/frame/offences", default-features = false } -pallet-parameters = { path = "../../../substrate/frame/parameters", default-features = false } -pallet-preimage = { path = "../../../substrate/frame/preimage", default-features = false } -pallet-proxy = { path = "../../../substrate/frame/proxy", default-features = false } -pallet-ranked-collective = { path = "../../../substrate/frame/ranked-collective", default-features = false } -pallet-recovery = { path = "../../../substrate/frame/recovery", default-features = false } -pallet-referenda = { path = "../../../substrate/frame/referenda", default-features = false } -pallet-scheduler = { path = "../../../substrate/frame/scheduler", default-features = false } -pallet-session = { path = "../../../substrate/frame/session", default-features = false } -pallet-society = { path = "../../../substrate/frame/society", default-features = false } -pallet-sudo = { path = "../../../substrate/frame/sudo", default-features = false } -frame-support = { path = "../../../substrate/frame/support", default-features = false, features = ["tuples-96"] } -pallet-staking = { path = "../../../substrate/frame/staking", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -frame-system-rpc-runtime-api = { path = "../../../substrate/frame/system/rpc/runtime-api", default-features = false } -pallet-timestamp = { path = "../../../substrate/frame/timestamp", default-features = false } -pallet-tips = { path = "../../../substrate/frame/tips", default-features = false } -pallet-treasury = { path = "../../../substrate/frame/treasury", default-features = false } -pallet-utility = { path = "../../../substrate/frame/utility", default-features = false } -pallet-vesting = { path = "../../../substrate/frame/vesting", default-features = false } -pallet-whitelist = { path = "../../../substrate/frame/whitelist", default-features = false } -pallet-xcm = { path = "../../xcm/pallet-xcm", default-features = false } -pallet-xcm-benchmarks = { path = "../../xcm/pallet-xcm-benchmarks", default-features = false, optional = true } -pallet-root-testing = { path = "../../../substrate/frame/root-testing", default-features = false } +pallet-authority-discovery = { workspace = true } +pallet-authorship = { workspace = true } +pallet-babe = { workspace = true } +pallet-balances = { workspace = true } +pallet-beefy = { workspace = true } +pallet-beefy-mmr = { workspace = true } +pallet-bounties = { workspace = true } +pallet-child-bounties = { workspace = true } +pallet-state-trie-migration = { workspace = true } +pallet-transaction-payment = { workspace = true } +pallet-transaction-payment-rpc-runtime-api = { workspace = true } +pallet-collective = { workspace = true } +pallet-conviction-voting = { workspace = true } +pallet-democracy = { workspace = true } +pallet-elections-phragmen = { workspace = true } +pallet-asset-rate = { workspace = true } +frame-executive = { workspace = true } +pallet-grandpa = { workspace = true } +pallet-identity = { workspace = true } +pallet-indices = { workspace = true } +pallet-membership = { workspace = true } +pallet-message-queue = { workspace = true } +pallet-mmr = { workspace = true } +pallet-multisig = { workspace = true } +pallet-nis = { workspace = true } +pallet-offences = { workspace = true } +pallet-parameters = { workspace = true } +pallet-preimage = { workspace = true } +pallet-proxy = { workspace = true } +pallet-ranked-collective = { workspace = true } +pallet-recovery = { workspace = true } +pallet-referenda = { workspace = true } +pallet-scheduler = { workspace = true } +pallet-session = { workspace = true } +pallet-society = { workspace = true } +pallet-sudo = { workspace = true } +frame-support = { features = ["tuples-96"], workspace = true } +pallet-staking = { workspace = true } +frame-system = { workspace = true } +frame-system-rpc-runtime-api = { workspace = true } +pallet-timestamp = { workspace = true } +pallet-tips = { workspace = true } +pallet-treasury = { workspace = true } +pallet-utility = { workspace = true } +pallet-vesting = { workspace = true } +pallet-whitelist = { workspace = true } +pallet-xcm = { workspace = true } +pallet-xcm-benchmarks = { optional = true, workspace = true } +pallet-root-testing = { workspace = true } -frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-metadata-hash-extension = { path = "../../../substrate/frame/metadata-hash-extension", default-features = false } -frame-try-runtime = { path = "../../../substrate/frame/try-runtime", default-features = false, optional = true } -frame-system-benchmarking = { path = "../../../substrate/frame/system/benchmarking", default-features = false, optional = true } -hex-literal = { version = "0.4.1" } +frame-benchmarking = { optional = true, workspace = true } +frame-metadata-hash-extension = { workspace = true } +frame-try-runtime = { optional = true, workspace = true } +frame-system-benchmarking = { optional = true, workspace = true } +hex-literal = { workspace = true, default-features = true } -polkadot-runtime-common = { path = "../common", default-features = false } -polkadot-runtime-parachains = { path = "../parachains", default-features = false } -polkadot-primitives = { path = "../../primitives", default-features = false } -polkadot-parachain-primitives = { path = "../../parachain", default-features = false } +polkadot-runtime-common = { workspace = true } +polkadot-runtime-parachains = { workspace = true } +polkadot-primitives = { workspace = true } +polkadot-parachain-primitives = { workspace = true } -xcm = { package = "staging-xcm", path = "../../xcm", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../xcm/xcm-executor", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../xcm/xcm-builder", default-features = false } -xcm-fee-payment-runtime-api = { path = "../../xcm/xcm-fee-payment-runtime-api", default-features = false } +xcm = { workspace = true } +xcm-executor = { workspace = true } +xcm-builder = { workspace = true } +xcm-runtime-apis = { workspace = true } [dev-dependencies] -tiny-keccak = { version = "2.0.2", features = ["keccak"] } -sp-keyring = { path = "../../../substrate/primitives/keyring" } -remote-externalities = { package = "frame-remote-externalities", path = "../../../substrate/utils/frame/remote-externalities" } -sp-trie = { path = "../../../substrate/primitives/trie" } -separator = "0.4.1" +tiny-keccak = { features = ["keccak"], workspace = true } +sp-keyring = { workspace = true, default-features = true } +remote-externalities = { workspace = true, default-features = true } +sp-trie = { workspace = true, default-features = true } +separator = { workspace = true } serde_json = { workspace = true, default-features = true } -sp-tracing = { path = "../../../substrate/primitives/tracing", default-features = false } -tokio = { version = "1.24.2", features = ["macros"] } +sp-tracing = { workspace = true } +tokio = { features = ["macros"], workspace = true, default-features = true } [build-dependencies] -substrate-wasm-builder = { path = "../../../substrate/utils/wasm-builder", optional = true } +substrate-wasm-builder = { optional = true, workspace = true, default-features = true } [features] default = ["std"] @@ -217,7 +217,7 @@ std = [ "substrate-wasm-builder", "xcm-builder/std", "xcm-executor/std", - "xcm-fee-payment-runtime-api/std", + "xcm-runtime-apis/std", "xcm/std", ] runtime-benchmarks = [ @@ -270,7 +270,7 @@ runtime-benchmarks = [ "sp-staking/runtime-benchmarks", "xcm-builder/runtime-benchmarks", "xcm-executor/runtime-benchmarks", - "xcm-fee-payment-runtime-api/runtime-benchmarks", + "xcm-runtime-apis/runtime-benchmarks", ] try-runtime = [ "frame-executive/try-runtime", diff --git a/polkadot/runtime/rococo/constants/Cargo.toml b/polkadot/runtime/rococo/constants/Cargo.toml index 2c49488077e6f82b6a306c2b98d7d0f493c4681c..b67c36d71fd8721c583789a7a283868111afc037 100644 --- a/polkadot/runtime/rococo/constants/Cargo.toml +++ b/polkadot/runtime/rococo/constants/Cargo.toml @@ -10,17 +10,17 @@ license.workspace = true workspace = true [dependencies] -smallvec = "1.8.0" +smallvec = { workspace = true, default-features = true } -frame-support = { path = "../../../../substrate/frame/support", default-features = false } -polkadot-primitives = { path = "../../../primitives", default-features = false } -polkadot-runtime-common = { path = "../../common", default-features = false } -sp-runtime = { path = "../../../../substrate/primitives/runtime", default-features = false } -sp-weights = { path = "../../../../substrate/primitives/weights", default-features = false } -sp-core = { path = "../../../../substrate/primitives/core", default-features = false } +frame-support = { workspace = true } +polkadot-primitives = { workspace = true } +polkadot-runtime-common = { workspace = true } +sp-runtime = { workspace = true } +sp-weights = { workspace = true } +sp-core = { workspace = true } -xcm = { package = "staging-xcm", path = "../../../xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../xcm/xcm-builder", default-features = false } +xcm = { workspace = true } +xcm-builder = { workspace = true } [features] default = ["std"] diff --git a/polkadot/runtime/rococo/src/governance/fellowship.rs b/polkadot/runtime/rococo/src/governance/fellowship.rs index a589b768afde2c0757e74a6535509228f1613a82..27a58a0eebd183bc5d21efa655113cf3a0251cc0 100644 --- a/polkadot/runtime/rococo/src/governance/fellowship.rs +++ b/polkadot/runtime/rococo/src/governance/fellowship.rs @@ -356,6 +356,7 @@ impl pallet_ranked_collective::Config for Runtime type MinRankOfClass = sp_runtime::traits::Identity; type MemberSwappedHandler = (); type VoteWeight = pallet_ranked_collective::Geometric; + type MaxMemberCount = (); #[cfg(feature = "runtime-benchmarks")] type BenchmarkSetup = (); } diff --git a/polkadot/runtime/rococo/src/lib.rs b/polkadot/runtime/rococo/src/lib.rs index 91ca5eb5e31d1895fa4b795734e51f2a6da8c3d9..bbec754387e736fe93a5ac3e012224fa9f4f011e 100644 --- a/polkadot/runtime/rococo/src/lib.rs +++ b/polkadot/runtime/rococo/src/lib.rs @@ -131,7 +131,7 @@ use governance::{ pallet_custom_origins, AuctionAdmin, Fellows, GeneralAdmin, LeaseAdmin, Treasurer, TreasurySpender, }; -use xcm_fee_payment_runtime_api::{ +use xcm_runtime_apis::{ dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects}, fees::Error as XcmPaymentApiError, }; @@ -162,7 +162,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("rococo"), impl_name: create_runtime_str!("parity-rococo-v2.0"), authoring_version: 0, - spec_version: 1_012_000, + spec_version: 1_013_000, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 26, @@ -476,9 +476,6 @@ parameter_types! { } parameter_types! { - pub const ProposalBond: Permill = Permill::from_percent(5); - pub const ProposalBondMinimum: Balance = 2000 * CENTS; - pub const ProposalBondMaximum: Balance = 1 * GRAND; pub const SpendPeriod: BlockNumber = 6 * DAYS; pub const Burn: Permill = Permill::from_perthousand(2); pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry"); @@ -501,13 +498,8 @@ parameter_types! { impl pallet_treasury::Config for Runtime { type PalletId = TreasuryPalletId; type Currency = Balances; - type ApproveOrigin = EitherOfDiverse, Treasurer>; type RejectOrigin = EitherOfDiverse, Treasurer>; type RuntimeEvent = RuntimeEvent; - type OnSlash = Treasury; - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ProposalBondMinimum; - type ProposalBondMaximum = ProposalBondMaximum; type SpendPeriod = SpendPeriod; type Burn = Burn; type BurnDestination = Society; @@ -566,6 +558,7 @@ impl pallet_bounties::Config for Runtime { type RuntimeEvent = RuntimeEvent; type MaximumReasonLength = MaximumReasonLength; type WeightInfo = weights::pallet_bounties::WeightInfo; + type OnSlash = Treasury; } parameter_types! { @@ -1767,7 +1760,7 @@ sp_api::impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::fees::XcmPaymentApi for Runtime { + impl xcm_runtime_apis::fees::XcmPaymentApi for Runtime { fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result, XcmPaymentApiError> { let acceptable_assets = vec![AssetId(xcm_config::TokenLocation::get())]; XcmPallet::query_acceptable_payment_assets(xcm_version, acceptable_assets) @@ -1780,11 +1773,11 @@ sp_api::impl_runtime_apis! { Ok(WeightToFee::weight_to_fee(&weight)) }, Ok(asset_id) => { - log::trace!(target: "xcm::xcm_fee_payment_runtime_api", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); + log::trace!(target: "xcm::xcm_runtime_api", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); Err(XcmPaymentApiError::AssetNotFound) }, Err(_) => { - log::trace!(target: "xcm::xcm_fee_payment_runtime_api", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!"); + log::trace!(target: "xcm::xcm_runtime_api", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!"); Err(XcmPaymentApiError::VersionedConversionFailed) } } @@ -1799,7 +1792,7 @@ sp_api::impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::dry_run::DryRunApi for Runtime { + impl xcm_runtime_apis::dry_run::DryRunApi for Runtime { fn dry_run_call(origin: OriginCaller, call: RuntimeCall) -> Result, XcmDryRunApiError> { XcmPallet::dry_run_call::(origin, call) } @@ -1809,6 +1802,18 @@ sp_api::impl_runtime_apis! { } } + impl xcm_runtime_apis::conversions::LocationToAccountApi for Runtime { + fn convert_location(location: VersionedLocation) -> Result< + AccountId, + xcm_runtime_apis::conversions::Error + > { + xcm_runtime_apis::conversions::LocationToAccountHelper::< + AccountId, + xcm_config::LocationConverter, + >::convert_location(location) + } + } + impl sp_api::Metadata for Runtime { fn metadata() -> OpaqueMetadata { OpaqueMetadata::new(Runtime::metadata().into()) diff --git a/polkadot/runtime/rococo/src/weights/pallet_treasury.rs b/polkadot/runtime/rococo/src/weights/pallet_treasury.rs index 144e9d5b872382b7381e2d77c6fb08a8fbece4fa..06246ada72f16fb04623f3fc6534265cc1156b79 100644 --- a/polkadot/runtime/rococo/src/weights/pallet_treasury.rs +++ b/polkadot/runtime/rococo/src/weights/pallet_treasury.rs @@ -63,51 +63,6 @@ impl pallet_treasury::WeightInfo for WeightInfo { .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(3)) } - /// Storage: Treasury ProposalCount (r:1 w:1) - /// Proof: Treasury ProposalCount (max_values: Some(1), max_size: Some(4), added: 499, mode: MaxEncodedLen) - /// Storage: Treasury Proposals (r:0 w:1) - /// Proof: Treasury Proposals (max_values: None, max_size: Some(108), added: 2583, mode: MaxEncodedLen) - fn propose_spend() -> Weight { - // Proof Size summary in bytes: - // Measured: `143` - // Estimated: `1489` - // Minimum execution time: 354_000_000 picoseconds. - Weight::from_parts(376_000_000, 0) - .saturating_add(Weight::from_parts(0, 1489)) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: Treasury Proposals (r:1 w:1) - /// Proof: Treasury Proposals (max_values: None, max_size: Some(108), added: 2583, mode: MaxEncodedLen) - /// Storage: System Account (r:1 w:1) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) - fn reject_proposal() -> Weight { - // Proof Size summary in bytes: - // Measured: `301` - // Estimated: `3593` - // Minimum execution time: 547_000_000 picoseconds. - Weight::from_parts(550_000_000, 0) - .saturating_add(Weight::from_parts(0, 3593)) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: Treasury Proposals (r:1 w:0) - /// Proof: Treasury Proposals (max_values: None, max_size: Some(108), added: 2583, mode: MaxEncodedLen) - /// Storage: Treasury Approvals (r:1 w:1) - /// Proof: Treasury Approvals (max_values: Some(1), max_size: Some(402), added: 897, mode: MaxEncodedLen) - /// The range of component `p` is `[0, 99]`. - fn approve_proposal(p: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `470 + p * (8 ยฑ0)` - // Estimated: `3573` - // Minimum execution time: 104_000_000 picoseconds. - Weight::from_parts(121_184_402, 0) - .saturating_add(Weight::from_parts(0, 3573)) - // Standard Error: 42_854 - .saturating_add(Weight::from_parts(153_112, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(1)) - } /// Storage: Treasury Approvals (r:1 w:1) /// Proof: Treasury Approvals (max_values: Some(1), max_size: Some(402), added: 897, mode: MaxEncodedLen) fn remove_approval() -> Weight { diff --git a/polkadot/runtime/test-runtime/Cargo.toml b/polkadot/runtime/test-runtime/Cargo.toml index c4d78b1081a626effc136b3a3ee42acd4b514bdf..a66fceedae34158e70be869c1b4262fcde3d7a43 100644 --- a/polkadot/runtime/test-runtime/Cargo.toml +++ b/polkadot/runtime/test-runtime/Cargo.toml @@ -11,68 +11,68 @@ license.workspace = true workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } serde = { workspace = true } -sp-authority-discovery = { path = "../../../substrate/primitives/authority-discovery", default-features = false } -sp-consensus-babe = { path = "../../../substrate/primitives/consensus/babe", default-features = false } -sp-consensus-beefy = { path = "../../../substrate/primitives/consensus/beefy", default-features = false } -sp-api = { path = "../../../substrate/primitives/api", default-features = false } -sp-inherents = { path = "../../../substrate/primitives/inherents", default-features = false } -sp-offchain = { path = "../../../substrate/primitives/offchain", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } -sp-io = { path = "../../../substrate/primitives/io", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-staking = { path = "../../../substrate/primitives/staking", default-features = false } -sp-core = { path = "../../../substrate/primitives/core", default-features = false } -sp-genesis-builder = { path = "../../../substrate/primitives/genesis-builder", default-features = false } -sp-mmr-primitives = { path = "../../../substrate/primitives/merkle-mountain-range", default-features = false } -sp-session = { path = "../../../substrate/primitives/session", default-features = false } -sp-version = { path = "../../../substrate/primitives/version", default-features = false } -frame-election-provider-support = { path = "../../../substrate/frame/election-provider-support", default-features = false } -sp-transaction-pool = { path = "../../../substrate/primitives/transaction-pool", default-features = false } -sp-block-builder = { path = "../../../substrate/primitives/block-builder", default-features = false } +sp-authority-discovery = { workspace = true } +sp-consensus-babe = { workspace = true } +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 } +sp-core = { workspace = true } +sp-genesis-builder = { workspace = true } +sp-mmr-primitives = { workspace = true } +sp-session = { workspace = true } +sp-version = { workspace = true } +frame-election-provider-support = { workspace = true } +sp-transaction-pool = { workspace = true } +sp-block-builder = { workspace = true } -pallet-authority-discovery = { path = "../../../substrate/frame/authority-discovery", default-features = false } -pallet-authorship = { path = "../../../substrate/frame/authorship", default-features = false } -pallet-babe = { path = "../../../substrate/frame/babe", default-features = false } -pallet-balances = { path = "../../../substrate/frame/balances", default-features = false } -pallet-transaction-payment = { path = "../../../substrate/frame/transaction-payment", default-features = false } -pallet-transaction-payment-rpc-runtime-api = { path = "../../../substrate/frame/transaction-payment/rpc/runtime-api", default-features = false } -frame-executive = { path = "../../../substrate/frame/executive", default-features = false } -pallet-grandpa = { path = "../../../substrate/frame/grandpa", default-features = false } -pallet-indices = { path = "../../../substrate/frame/indices", default-features = false } -pallet-offences = { path = "../../../substrate/frame/offences", default-features = false } -pallet-session = { path = "../../../substrate/frame/session", default-features = false } -frame-support = { path = "../../../substrate/frame/support", default-features = false } -pallet-staking = { path = "../../../substrate/frame/staking", default-features = false } -pallet-staking-reward-curve = { path = "../../../substrate/frame/staking/reward-curve" } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -frame-system-rpc-runtime-api = { path = "../../../substrate/frame/system/rpc/runtime-api", default-features = false } -test-runtime-constants = { package = "test-runtime-constants", path = "constants", default-features = false } -pallet-timestamp = { path = "../../../substrate/frame/timestamp", default-features = false } -pallet-sudo = { path = "../../../substrate/frame/sudo", default-features = false } -pallet-vesting = { path = "../../../substrate/frame/vesting", default-features = false } +pallet-authority-discovery = { workspace = true } +pallet-authorship = { workspace = true } +pallet-babe = { workspace = true } +pallet-balances = { workspace = true } +pallet-transaction-payment = { workspace = true } +pallet-transaction-payment-rpc-runtime-api = { workspace = true } +frame-executive = { workspace = true } +pallet-grandpa = { workspace = true } +pallet-indices = { workspace = true } +pallet-offences = { workspace = true } +pallet-session = { workspace = true } +frame-support = { workspace = true } +pallet-staking = { workspace = true } +pallet-staking-reward-curve = { workspace = true, default-features = true } +frame-system = { workspace = true } +frame-system-rpc-runtime-api = { workspace = true } +test-runtime-constants = { workspace = true } +pallet-timestamp = { workspace = true } +pallet-sudo = { workspace = true } +pallet-vesting = { workspace = true } -polkadot-runtime-common = { path = "../common", default-features = false } -polkadot-primitives = { path = "../../primitives", default-features = false } -pallet-xcm = { path = "../../xcm/pallet-xcm", default-features = false } -polkadot-runtime-parachains = { path = "../parachains", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../xcm/xcm-builder", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../xcm/xcm-executor", default-features = false } -xcm = { package = "staging-xcm", path = "../../xcm", default-features = false } +polkadot-runtime-common = { workspace = true } +polkadot-primitives = { workspace = true } +pallet-xcm = { workspace = true } +polkadot-runtime-parachains = { workspace = true } +xcm-builder = { workspace = true } +xcm-executor = { workspace = true } +xcm = { workspace = true } [dev-dependencies] -hex-literal = "0.4.1" -tiny-keccak = { version = "2.0.2", features = ["keccak"] } -sp-keyring = { path = "../../../substrate/primitives/keyring" } -sp-trie = { path = "../../../substrate/primitives/trie" } +hex-literal = { workspace = true, default-features = true } +tiny-keccak = { features = ["keccak"], workspace = true } +sp-keyring = { workspace = true, default-features = true } +sp-trie = { workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } [build-dependencies] -substrate-wasm-builder = { path = "../../../substrate/utils/wasm-builder" } +substrate-wasm-builder = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/polkadot/runtime/test-runtime/constants/Cargo.toml b/polkadot/runtime/test-runtime/constants/Cargo.toml index ed10ece54f67c43a7b8aedfaebfb03452605cfe8..807774be7136961b5b2fa146cca50f4efc666fa7 100644 --- a/polkadot/runtime/test-runtime/constants/Cargo.toml +++ b/polkadot/runtime/test-runtime/constants/Cargo.toml @@ -10,11 +10,11 @@ license.workspace = true workspace = true [dependencies] -smallvec = "1.8.0" +smallvec = { workspace = true, default-features = true } -frame-support = { path = "../../../../substrate/frame/support", default-features = false } -polkadot-primitives = { path = "../../../primitives", default-features = false } -sp-runtime = { path = "../../../../substrate/primitives/runtime", default-features = false } +frame-support = { workspace = true } +polkadot-primitives = { workspace = true } +sp-runtime = { workspace = true } [features] default = ["std"] diff --git a/polkadot/runtime/test-runtime/src/lib.rs b/polkadot/runtime/test-runtime/src/lib.rs index 8178639946f8df0707ef39e2543a4f4dab8a2c0f..334c6eb733a1df5263d41042cfe0307152dcbdf3 100644 --- a/polkadot/runtime/test-runtime/src/lib.rs +++ b/polkadot/runtime/test-runtime/src/lib.rs @@ -53,6 +53,7 @@ use frame_support::{ }; use pallet_grandpa::{fg_primitives, AuthorityId as GrandpaId}; use pallet_session::historical as session_historical; +use pallet_timestamp::Now; use pallet_transaction_payment::{FeeDetails, RuntimeDispatchInfo}; use polkadot_primitives::{ slashing, AccountId, AccountIndex, Balance, BlockNumber, CandidateEvent, CandidateHash, @@ -1186,7 +1187,7 @@ sp_api::impl_runtime_apis! { impl crate::GetLastTimestamp for Runtime { fn get_last_timestamp() -> u64 { - Timestamp::now() + Now::::get() } } diff --git a/polkadot/runtime/westend/Cargo.toml b/polkadot/runtime/westend/Cargo.toml index ccb8a02b981cc36782c796eae7b13081e0c985de..5a7805c05161be49ae94986b60101594422d4d89 100644 --- a/polkadot/runtime/westend/Cargo.toml +++ b/polkadot/runtime/westend/Cargo.toml @@ -11,123 +11,122 @@ license.workspace = true workspace = true [dependencies] -bitvec = { version = "1.0.0", default-features = false, features = ["alloc"] } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive", "max-encoded-len"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +bitvec = { features = ["alloc"], workspace = true } +codec = { features = ["derive", "max-encoded-len"], workspace = true } +scale-info = { features = ["derive"], workspace = true } log = { workspace = true } -rustc-hex = { version = "2.1.0", default-features = false } serde = { workspace = true } serde_derive = { optional = true, workspace = true } -smallvec = "1.8.0" +smallvec = { workspace = true, default-features = true } -sp-authority-discovery = { path = "../../../substrate/primitives/authority-discovery", default-features = false } -sp-consensus-babe = { path = "../../../substrate/primitives/consensus/babe", default-features = false } -sp-consensus-beefy = { path = "../../../substrate/primitives/consensus/beefy", default-features = false } -binary-merkle-tree = { path = "../../../substrate/utils/binary-merkle-tree", default-features = false } -sp-inherents = { path = "../../../substrate/primitives/inherents", default-features = false } -sp-offchain = { path = "../../../substrate/primitives/offchain", default-features = false } -sp-api = { path = "../../../substrate/primitives/api", default-features = false } -sp-application-crypto = { path = "../../../substrate/primitives/application-crypto", default-features = false } -sp-arithmetic = { path = "../../../substrate/primitives/arithmetic", default-features = false } -sp-std = { package = "sp-std", path = "../../../substrate/primitives/std", default-features = false } -sp-genesis-builder = { path = "../../../substrate/primitives/genesis-builder", default-features = false } -sp-io = { path = "../../../substrate/primitives/io", default-features = false } -sp-mmr-primitives = { path = "../../../substrate/primitives/merkle-mountain-range", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-staking = { path = "../../../substrate/primitives/staking", default-features = false } -sp-core = { path = "../../../substrate/primitives/core", default-features = false } -sp-session = { path = "../../../substrate/primitives/session", default-features = false } -sp-storage = { path = "../../../substrate/primitives/storage", default-features = false } -sp-version = { path = "../../../substrate/primitives/version", default-features = false } -sp-transaction-pool = { path = "../../../substrate/primitives/transaction-pool", default-features = false } -sp-block-builder = { path = "../../../substrate/primitives/block-builder", default-features = false } -sp-npos-elections = { path = "../../../substrate/primitives/npos-elections", default-features = false } +sp-authority-discovery = { workspace = true } +sp-consensus-babe = { workspace = true } +sp-consensus-beefy = { workspace = true } +binary-merkle-tree = { workspace = true } +sp-inherents = { workspace = true } +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 } +sp-runtime = { workspace = true } +sp-staking = { workspace = true } +sp-core = { workspace = true } +sp-session = { workspace = true } +sp-storage = { workspace = true } +sp-version = { workspace = true } +sp-transaction-pool = { workspace = true } +sp-block-builder = { workspace = true } +sp-npos-elections = { workspace = true } -frame-election-provider-support = { path = "../../../substrate/frame/election-provider-support", default-features = false } -frame-executive = { path = "../../../substrate/frame/executive", default-features = false } -frame-metadata-hash-extension = { path = "../../../substrate/frame/metadata-hash-extension", default-features = false } -frame-support = { path = "../../../substrate/frame/support", default-features = false, features = ["experimental", "tuples-96"] } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -frame-system-rpc-runtime-api = { path = "../../../substrate/frame/system/rpc/runtime-api", default-features = false } -westend-runtime-constants = { package = "westend-runtime-constants", path = "constants", default-features = false } -pallet-asset-rate = { path = "../../../substrate/frame/asset-rate", default-features = false } -pallet-authority-discovery = { path = "../../../substrate/frame/authority-discovery", default-features = false } -pallet-authorship = { path = "../../../substrate/frame/authorship", default-features = false } -pallet-babe = { path = "../../../substrate/frame/babe", default-features = false } -pallet-bags-list = { path = "../../../substrate/frame/bags-list", default-features = false } -pallet-balances = { path = "../../../substrate/frame/balances", default-features = false } -pallet-beefy = { path = "../../../substrate/frame/beefy", default-features = false } -pallet-beefy-mmr = { path = "../../../substrate/frame/beefy-mmr", default-features = false } -pallet-collective = { path = "../../../substrate/frame/collective", default-features = false } -pallet-democracy = { path = "../../../substrate/frame/democracy", default-features = false } -pallet-elections-phragmen = { package = "pallet-elections-phragmen", path = "../../../substrate/frame/elections-phragmen", default-features = false } -pallet-election-provider-multi-phase = { path = "../../../substrate/frame/election-provider-multi-phase", default-features = false } -pallet-fast-unstake = { path = "../../../substrate/frame/fast-unstake", default-features = false } -pallet-grandpa = { path = "../../../substrate/frame/grandpa", default-features = false } -pallet-identity = { path = "../../../substrate/frame/identity", default-features = false } -pallet-indices = { path = "../../../substrate/frame/indices", default-features = false } -pallet-membership = { path = "../../../substrate/frame/membership", default-features = false } -pallet-message-queue = { path = "../../../substrate/frame/message-queue", default-features = false } -pallet-mmr = { path = "../../../substrate/frame/merkle-mountain-range", default-features = false } -pallet-multisig = { path = "../../../substrate/frame/multisig", default-features = false } -pallet-nomination-pools = { path = "../../../substrate/frame/nomination-pools", default-features = false } -pallet-conviction-voting = { path = "../../../substrate/frame/conviction-voting", default-features = false } -pallet-offences = { path = "../../../substrate/frame/offences", default-features = false } -pallet-preimage = { path = "../../../substrate/frame/preimage", default-features = false } -pallet-proxy = { path = "../../../substrate/frame/proxy", default-features = false } -pallet-recovery = { path = "../../../substrate/frame/recovery", default-features = false } -pallet-referenda = { path = "../../../substrate/frame/referenda", default-features = false } -pallet-scheduler = { path = "../../../substrate/frame/scheduler", default-features = false } -pallet-session = { path = "../../../substrate/frame/session", default-features = false } -pallet-society = { path = "../../../substrate/frame/society", default-features = false } -pallet-staking = { path = "../../../substrate/frame/staking", default-features = false } -pallet-staking-reward-curve = { package = "pallet-staking-reward-curve", path = "../../../substrate/frame/staking/reward-curve" } -pallet-staking-runtime-api = { path = "../../../substrate/frame/staking/runtime-api", default-features = false } -pallet-delegated-staking = { path = "../../../substrate/frame/delegated-staking", default-features = false } -pallet-state-trie-migration = { path = "../../../substrate/frame/state-trie-migration", default-features = false } -pallet-sudo = { path = "../../../substrate/frame/sudo", default-features = false } -pallet-timestamp = { path = "../../../substrate/frame/timestamp", default-features = false } -pallet-transaction-payment = { path = "../../../substrate/frame/transaction-payment", default-features = false } -pallet-transaction-payment-rpc-runtime-api = { path = "../../../substrate/frame/transaction-payment/rpc/runtime-api", default-features = false } -pallet-nomination-pools-runtime-api = { path = "../../../substrate/frame/nomination-pools/runtime-api", default-features = false } -pallet-treasury = { path = "../../../substrate/frame/treasury", default-features = false } -pallet-utility = { path = "../../../substrate/frame/utility", default-features = false } -pallet-vesting = { path = "../../../substrate/frame/vesting", default-features = false } -pallet-whitelist = { path = "../../../substrate/frame/whitelist", default-features = false } -pallet-xcm = { path = "../../xcm/pallet-xcm", default-features = false } -pallet-xcm-benchmarks = { path = "../../xcm/pallet-xcm-benchmarks", default-features = false, optional = true } -pallet-root-testing = { path = "../../../substrate/frame/root-testing", default-features = false } +frame-election-provider-support = { workspace = true } +frame-executive = { workspace = true } +frame-metadata-hash-extension = { workspace = true } +frame-support = { features = ["experimental", "tuples-96"], workspace = true } +frame-system = { workspace = true } +frame-system-rpc-runtime-api = { workspace = true } +westend-runtime-constants = { workspace = true } +pallet-asset-rate = { workspace = true } +pallet-authority-discovery = { workspace = true } +pallet-authorship = { workspace = true } +pallet-babe = { workspace = true } +pallet-bags-list = { workspace = true } +pallet-balances = { workspace = true } +pallet-beefy = { workspace = true } +pallet-beefy-mmr = { workspace = true } +pallet-collective = { workspace = true } +pallet-democracy = { workspace = true } +pallet-elections-phragmen = { workspace = true } +pallet-election-provider-multi-phase = { workspace = true } +pallet-fast-unstake = { workspace = true } +pallet-grandpa = { workspace = true } +pallet-identity = { workspace = true } +pallet-indices = { workspace = true } +pallet-membership = { workspace = true } +pallet-message-queue = { workspace = true } +pallet-mmr = { workspace = true } +pallet-multisig = { workspace = true } +pallet-nomination-pools = { workspace = true } +pallet-conviction-voting = { workspace = true } +pallet-offences = { workspace = true } +pallet-preimage = { workspace = true } +pallet-proxy = { workspace = true } +pallet-recovery = { workspace = true } +pallet-referenda = { workspace = true } +pallet-scheduler = { workspace = true } +pallet-session = { workspace = true } +pallet-society = { workspace = true } +pallet-staking = { workspace = true } +pallet-staking-reward-curve = { workspace = true, default-features = true } +pallet-staking-runtime-api = { workspace = true } +pallet-delegated-staking = { workspace = true } +pallet-state-trie-migration = { workspace = true } +pallet-sudo = { workspace = true } +pallet-timestamp = { workspace = true } +pallet-transaction-payment = { workspace = true } +pallet-transaction-payment-rpc-runtime-api = { workspace = true } +pallet-nomination-pools-runtime-api = { workspace = true } +pallet-treasury = { workspace = true } +pallet-utility = { workspace = true } +pallet-vesting = { workspace = true } +pallet-whitelist = { workspace = true } +pallet-xcm = { workspace = true } +pallet-xcm-benchmarks = { optional = true, workspace = true } +pallet-root-testing = { workspace = true } -frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-try-runtime = { path = "../../../substrate/frame/try-runtime", default-features = false, optional = true } -frame-system-benchmarking = { path = "../../../substrate/frame/system/benchmarking", default-features = false, optional = true } -pallet-election-provider-support-benchmarking = { path = "../../../substrate/frame/election-provider-support/benchmarking", default-features = false, optional = true } -pallet-nomination-pools-benchmarking = { path = "../../../substrate/frame/nomination-pools/benchmarking", default-features = false, optional = true } -pallet-offences-benchmarking = { path = "../../../substrate/frame/offences/benchmarking", default-features = false, optional = true } -pallet-session-benchmarking = { path = "../../../substrate/frame/session/benchmarking", default-features = false, optional = true } -hex-literal = { version = "0.4.1", optional = true } +frame-benchmarking = { optional = true, workspace = true } +frame-try-runtime = { optional = true, workspace = true } +frame-system-benchmarking = { optional = true, workspace = true } +pallet-election-provider-support-benchmarking = { optional = true, workspace = true } +pallet-nomination-pools-benchmarking = { optional = true, workspace = true } +pallet-offences-benchmarking = { optional = true, workspace = true } +pallet-session-benchmarking = { optional = true, workspace = true } +hex-literal = { optional = true, workspace = true, default-features = true } -polkadot-runtime-common = { path = "../common", default-features = false } -polkadot-primitives = { path = "../../primitives", default-features = false } -polkadot-parachain-primitives = { path = "../../parachain", default-features = false } -polkadot-runtime-parachains = { path = "../parachains", default-features = false } +polkadot-runtime-common = { workspace = true } +polkadot-primitives = { workspace = true } +polkadot-parachain-primitives = { workspace = true } +polkadot-runtime-parachains = { workspace = true } -xcm = { package = "staging-xcm", path = "../../xcm", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../xcm/xcm-executor", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../xcm/xcm-builder", default-features = false } -xcm-fee-payment-runtime-api = { path = "../../xcm/xcm-fee-payment-runtime-api", default-features = false } +xcm = { workspace = true } +xcm-executor = { workspace = true } +xcm-builder = { workspace = true } +xcm-runtime-apis = { workspace = true } [dev-dependencies] -hex-literal = "0.4.1" -tiny-keccak = { version = "2.0.2", features = ["keccak"] } -sp-keyring = { path = "../../../substrate/primitives/keyring" } +hex-literal = { workspace = true, default-features = true } +tiny-keccak = { features = ["keccak"], workspace = true } +sp-keyring = { workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } -remote-externalities = { package = "frame-remote-externalities", path = "../../../substrate/utils/frame/remote-externalities" } -tokio = { version = "1.24.2", features = ["macros"] } -sp-tracing = { path = "../../../substrate/primitives/tracing", default-features = false } +remote-externalities = { workspace = true, default-features = true } +tokio = { features = ["macros"], workspace = true, default-features = true } +sp-tracing = { workspace = true } [build-dependencies] -substrate-wasm-builder = { path = "../../../substrate/utils/wasm-builder" } +substrate-wasm-builder = { workspace = true, default-features = true } [features] default = ["std"] @@ -201,7 +200,6 @@ std = [ "polkadot-primitives/std", "polkadot-runtime-common/std", "polkadot-runtime-parachains/std", - "rustc-hex/std", "scale-info/std", "serde/std", "serde_derive", @@ -230,7 +228,7 @@ std = [ "westend-runtime-constants/std", "xcm-builder/std", "xcm-executor/std", - "xcm-fee-payment-runtime-api/std", + "xcm-runtime-apis/std", "xcm/std", ] runtime-benchmarks = [ @@ -288,7 +286,7 @@ runtime-benchmarks = [ "sp-staking/runtime-benchmarks", "xcm-builder/runtime-benchmarks", "xcm-executor/runtime-benchmarks", - "xcm-fee-payment-runtime-api/runtime-benchmarks", + "xcm-runtime-apis/runtime-benchmarks", ] try-runtime = [ "frame-election-provider-support/try-runtime", diff --git a/polkadot/runtime/westend/constants/Cargo.toml b/polkadot/runtime/westend/constants/Cargo.toml index d50b168fac52ee12709ece481375f73efdd878ac..b40846455bf55f234ee9bae2a9385f0e3ca9a74f 100644 --- a/polkadot/runtime/westend/constants/Cargo.toml +++ b/polkadot/runtime/westend/constants/Cargo.toml @@ -10,17 +10,17 @@ license.workspace = true workspace = true [dependencies] -smallvec = "1.8.0" +smallvec = { workspace = true, default-features = true } -frame-support = { path = "../../../../substrate/frame/support", default-features = false } -polkadot-primitives = { path = "../../../primitives", default-features = false } -polkadot-runtime-common = { path = "../../common", default-features = false } -sp-runtime = { path = "../../../../substrate/primitives/runtime", default-features = false } -sp-weights = { path = "../../../../substrate/primitives/weights", default-features = false } -sp-core = { path = "../../../../substrate/primitives/core", default-features = false } +frame-support = { workspace = true } +polkadot-primitives = { workspace = true } +polkadot-runtime-common = { workspace = true } +sp-runtime = { workspace = true } +sp-weights = { workspace = true } +sp-core = { workspace = true } -xcm = { package = "staging-xcm", path = "../../../xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../xcm/xcm-builder", default-features = false } +xcm = { workspace = true } +xcm-builder = { workspace = true } [features] default = ["std"] diff --git a/polkadot/runtime/westend/src/lib.rs b/polkadot/runtime/westend/src/lib.rs index 77262a98a94c858e7baa46b77fd47b0fc171f757..59789ed16cbb47707bb4f0867f40c782e48b2bcd 100644 --- a/polkadot/runtime/westend/src/lib.rs +++ b/polkadot/runtime/westend/src/lib.rs @@ -29,7 +29,7 @@ use frame_support::{ traits::{ fungible::HoldConsideration, tokens::UnityOrOuterConversion, ConstU32, Contains, EitherOf, EitherOfDiverse, EverythingBut, FromContains, InstanceFilter, KeyOwnerProofSystem, - LinearStoragePrice, ProcessMessage, ProcessMessageError, WithdrawReasons, + LinearStoragePrice, ProcessMessage, ProcessMessageError, VariantCountOf, WithdrawReasons, }, weights::{ConstantMultiplier, WeightMeter, WeightToFee as _}, PalletId, @@ -105,7 +105,7 @@ use sp_version::RuntimeVersion; use xcm::{latest::prelude::*, VersionedAssetId, VersionedAssets, VersionedLocation, VersionedXcm}; use xcm_builder::PayOverXcm; -use xcm_fee_payment_runtime_api::{ +use xcm_runtime_apis::{ dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects}, fees::Error as XcmPaymentApiError, }; @@ -154,7 +154,7 @@ pub const VERSION: RuntimeVersion = RuntimeVersion { spec_name: create_runtime_str!("westend"), impl_name: create_runtime_str!("parity-westend"), authoring_version: 2, - spec_version: 1_012_000, + spec_version: 1_013_000, impl_version: 0, apis: RUNTIME_API_VERSIONS, transaction_version: 26, @@ -310,7 +310,7 @@ impl pallet_balances::Config for Runtime { type RuntimeHoldReason = RuntimeHoldReason; type RuntimeFreezeReason = RuntimeFreezeReason; type FreezeIdentifier = RuntimeFreezeReason; - type MaxFreezes = ConstU32<1>; + type MaxFreezes = VariantCountOf; } parameter_types! { @@ -661,9 +661,6 @@ impl pallet_fast_unstake::Config for Runtime { } parameter_types! { - pub const ProposalBond: Permill = Permill::from_percent(5); - pub const ProposalBondMinimum: Balance = 2000 * CENTS; - pub const ProposalBondMaximum: Balance = 1 * GRAND; pub const SpendPeriod: BlockNumber = 6 * DAYS; pub const Burn: Permill = Permill::from_perthousand(2); pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry"); @@ -686,13 +683,8 @@ parameter_types! { impl pallet_treasury::Config for Runtime { type PalletId = TreasuryPalletId; type Currency = Balances; - type ApproveOrigin = EitherOfDiverse, Treasurer>; type RejectOrigin = EitherOfDiverse, Treasurer>; type RuntimeEvent = RuntimeEvent; - type OnSlash = Treasury; - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ProposalBondMinimum; - type ProposalBondMaximum = ProposalBondMaximum; type SpendPeriod = SpendPeriod; type Burn = Burn; type BurnDestination = (); @@ -2229,7 +2221,7 @@ sp_api::impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::fees::XcmPaymentApi for Runtime { + impl xcm_runtime_apis::fees::XcmPaymentApi for Runtime { fn query_acceptable_payment_assets(xcm_version: xcm::Version) -> Result, XcmPaymentApiError> { let acceptable_assets = vec![AssetId(xcm_config::TokenLocation::get())]; XcmPallet::query_acceptable_payment_assets(xcm_version, acceptable_assets) @@ -2242,11 +2234,11 @@ sp_api::impl_runtime_apis! { Ok(WeightToFee::weight_to_fee(&weight)) }, Ok(asset_id) => { - log::trace!(target: "xcm::xcm_fee_payment_runtime_api", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); + log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - unhandled asset_id: {asset_id:?}!"); Err(XcmPaymentApiError::AssetNotFound) }, Err(_) => { - log::trace!(target: "xcm::xcm_fee_payment_runtime_api", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!"); + log::trace!(target: "xcm::xcm_runtime_apis", "query_weight_to_asset_fee - failed to convert asset: {asset:?}!"); Err(XcmPaymentApiError::VersionedConversionFailed) } } @@ -2261,7 +2253,7 @@ sp_api::impl_runtime_apis! { } } - impl xcm_fee_payment_runtime_api::dry_run::DryRunApi for Runtime { + impl xcm_runtime_apis::dry_run::DryRunApi for Runtime { fn dry_run_call(origin: OriginCaller, call: RuntimeCall) -> Result, XcmDryRunApiError> { XcmPallet::dry_run_call::(origin, call) } @@ -2271,6 +2263,18 @@ sp_api::impl_runtime_apis! { } } + impl xcm_runtime_apis::conversions::LocationToAccountApi for Runtime { + fn convert_location(location: VersionedLocation) -> Result< + AccountId, + xcm_runtime_apis::conversions::Error + > { + xcm_runtime_apis::conversions::LocationToAccountHelper::< + AccountId, + xcm_config::LocationConverter, + >::convert_location(location) + } + } + impl pallet_nomination_pools_runtime_api::NominationPoolsApi< Block, AccountId, diff --git a/polkadot/runtime/westend/src/weights/pallet_treasury.rs b/polkadot/runtime/westend/src/weights/pallet_treasury.rs index 144e9d5b872382b7381e2d77c6fb08a8fbece4fa..06246ada72f16fb04623f3fc6534265cc1156b79 100644 --- a/polkadot/runtime/westend/src/weights/pallet_treasury.rs +++ b/polkadot/runtime/westend/src/weights/pallet_treasury.rs @@ -63,51 +63,6 @@ impl pallet_treasury::WeightInfo for WeightInfo { .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(3)) } - /// Storage: Treasury ProposalCount (r:1 w:1) - /// Proof: Treasury ProposalCount (max_values: Some(1), max_size: Some(4), added: 499, mode: MaxEncodedLen) - /// Storage: Treasury Proposals (r:0 w:1) - /// Proof: Treasury Proposals (max_values: None, max_size: Some(108), added: 2583, mode: MaxEncodedLen) - fn propose_spend() -> Weight { - // Proof Size summary in bytes: - // Measured: `143` - // Estimated: `1489` - // Minimum execution time: 354_000_000 picoseconds. - Weight::from_parts(376_000_000, 0) - .saturating_add(Weight::from_parts(0, 1489)) - .saturating_add(T::DbWeight::get().reads(1)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: Treasury Proposals (r:1 w:1) - /// Proof: Treasury Proposals (max_values: None, max_size: Some(108), added: 2583, mode: MaxEncodedLen) - /// Storage: System Account (r:1 w:1) - /// Proof: System Account (max_values: None, max_size: Some(128), added: 2603, mode: MaxEncodedLen) - fn reject_proposal() -> Weight { - // Proof Size summary in bytes: - // Measured: `301` - // Estimated: `3593` - // Minimum execution time: 547_000_000 picoseconds. - Weight::from_parts(550_000_000, 0) - .saturating_add(Weight::from_parts(0, 3593)) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(2)) - } - /// Storage: Treasury Proposals (r:1 w:0) - /// Proof: Treasury Proposals (max_values: None, max_size: Some(108), added: 2583, mode: MaxEncodedLen) - /// Storage: Treasury Approvals (r:1 w:1) - /// Proof: Treasury Approvals (max_values: Some(1), max_size: Some(402), added: 897, mode: MaxEncodedLen) - /// The range of component `p` is `[0, 99]`. - fn approve_proposal(p: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `470 + p * (8 ยฑ0)` - // Estimated: `3573` - // Minimum execution time: 104_000_000 picoseconds. - Weight::from_parts(121_184_402, 0) - .saturating_add(Weight::from_parts(0, 3573)) - // Standard Error: 42_854 - .saturating_add(Weight::from_parts(153_112, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(2)) - .saturating_add(T::DbWeight::get().writes(1)) - } /// Storage: Treasury Approvals (r:1 w:1) /// Proof: Treasury Approvals (max_values: Some(1), max_size: Some(402), added: 897, mode: MaxEncodedLen) fn remove_approval() -> Weight { diff --git a/polkadot/statement-table/Cargo.toml b/polkadot/statement-table/Cargo.toml index 7181afd9989ec9e0b00d1335bf35f2c5f2441836..53ea0b74463bc2466df2ff37f190f429d9b2973a 100644 --- a/polkadot/statement-table/Cargo.toml +++ b/polkadot/statement-table/Cargo.toml @@ -10,7 +10,7 @@ description = "Stores messages other authorities issue about candidates in Polka workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -sp-core = { path = "../../substrate/primitives/core" } -polkadot-primitives = { path = "../primitives" } -gum = { package = "tracing-gum", path = "../node/gum" } +codec = { features = ["derive"], workspace = true } +sp-core = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +gum = { workspace = true, default-features = true } diff --git a/polkadot/utils/generate-bags/Cargo.toml b/polkadot/utils/generate-bags/Cargo.toml index ad6d7259d2483e11e9df8c121bab75461a71c525..16205b0f51f57a62b923eff0952a45795c6cb3b6 100644 --- a/polkadot/utils/generate-bags/Cargo.toml +++ b/polkadot/utils/generate-bags/Cargo.toml @@ -10,9 +10,9 @@ description = "CLI to generate voter bags for Polkadot runtimes" workspace = true [dependencies] -clap = { version = "4.5.3", features = ["derive"] } +clap = { features = ["derive"], workspace = true } -generate-bags = { path = "../../../substrate/utils/frame/generate-bags" } -sp-io = { path = "../../../substrate/primitives/io" } +generate-bags = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } -westend-runtime = { path = "../../runtime/westend" } +westend-runtime = { workspace = true } diff --git a/polkadot/utils/remote-ext-tests/bags-list/Cargo.toml b/polkadot/utils/remote-ext-tests/bags-list/Cargo.toml index 20e4130f888bcb1f826dab81fb7e5a721a53a225..206ca8cf19a90df9bc2becd0c65039f35d714191 100644 --- a/polkadot/utils/remote-ext-tests/bags-list/Cargo.toml +++ b/polkadot/utils/remote-ext-tests/bags-list/Cargo.toml @@ -10,14 +10,14 @@ license.workspace = true workspace = true [dependencies] -westend-runtime = { path = "../../../runtime/westend" } -westend-runtime-constants = { path = "../../../runtime/westend/constants" } +westend-runtime = { workspace = true } +westend-runtime-constants = { workspace = true, default-features = true } -pallet-bags-list-remote-tests = { path = "../../../../substrate/frame/bags-list/remote-tests" } -sp-tracing = { path = "../../../../substrate/primitives/tracing" } -frame-system = { path = "../../../../substrate/frame/system" } -sp-core = { path = "../../../../substrate/primitives/core" } +pallet-bags-list-remote-tests = { workspace = true } +sp-tracing = { workspace = true, default-features = true } +frame-system = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } -clap = { version = "4.5.3", features = ["derive"] } +clap = { features = ["derive"], workspace = true } log = { workspace = true, default-features = true } -tokio = { version = "1.24.2", features = ["macros"] } +tokio = { features = ["macros"], workspace = true, default-features = true } diff --git a/polkadot/xcm/Cargo.toml b/polkadot/xcm/Cargo.toml index 5f8524b8ac627eea8cdd8a2e4500af9d2d8da758..29d055356312bf003bc3b09744177d2c19761839 100644 --- a/polkadot/xcm/Cargo.toml +++ b/polkadot/xcm/Cargo.toml @@ -10,23 +10,23 @@ license.workspace = true workspace = true [dependencies] -array-bytes = "6.2.2" -bounded-collections = { version = "0.2.0", default-features = false, features = ["serde"] } -derivative = { version = "2.2.0", default-features = false, features = ["use_core"] } -impl-trait-for-tuples = "0.2.2" +array-bytes = { workspace = true, default-features = true } +bounded-collections = { features = ["serde"], workspace = true } +derivative = { features = ["use_core"], workspace = true } +impl-trait-for-tuples = { workspace = true } log = { workspace = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive", "max-encoded-len"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive", "serde"] } -sp-weights = { path = "../../substrate/primitives/weights", default-features = false, features = ["serde"] } +codec = { features = ["derive", "max-encoded-len"], workspace = true } +scale-info = { features = ["derive", "serde"], workspace = true } +sp-weights = { features = ["serde"], workspace = true } serde = { features = ["alloc", "derive", "rc"], workspace = true } -schemars = { version = "0.8.13", default-features = true, optional = true } -xcm-procedural = { path = "procedural" } -environmental = { version = "1.1.4", default-features = false } +schemars = { default-features = true, optional = true, workspace = true } +xcm-procedural = { workspace = true, default-features = true } +environmental = { workspace = true } [dev-dependencies] -sp-io = { path = "../../substrate/primitives/io" } -hex = "0.4.3" -hex-literal = "0.4.1" +sp-io = { workspace = true, default-features = true } +hex = { workspace = true, default-features = true } +hex-literal = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/polkadot/xcm/docs/Cargo.toml b/polkadot/xcm/docs/Cargo.toml index 9820bd36dc0b1fb84fb6c4e43e4b1608308432a2..9d8f4c0a6430b71e2b2d1ba09719a8c397b4e4d5 100644 --- a/polkadot/xcm/docs/Cargo.toml +++ b/polkadot/xcm/docs/Cargo.toml @@ -10,30 +10,30 @@ publish = false [dependencies] # For XCM stuff -xcm = { path = "../../xcm", package = "staging-xcm" } -xcm-executor = { path = "../../xcm/xcm-executor", package = "staging-xcm-executor" } -xcm-builder = { path = "../../xcm/xcm-builder", package = "staging-xcm-builder" } -xcm-simulator = { path = "../../xcm/xcm-simulator" } -pallet-xcm = { path = "../../xcm/pallet-xcm" } +xcm = { workspace = true, default-features = true } +xcm-executor = { workspace = true, default-features = true } +xcm-builder = { workspace = true, default-features = true } +xcm-simulator = { workspace = true, default-features = true } +pallet-xcm = { workspace = true, default-features = true } # For building FRAME runtimes -frame = { package = "polkadot-sdk-frame", path = "../../../substrate/frame", features = ["experimental", "runtime"] } -codec = { package = "parity-scale-codec", version = "3.6.9" } -scale-info = { version = "2.6.0", default-features = false } -polkadot-parachain-primitives = { path = "../../../polkadot/parachain" } -polkadot-runtime-parachains = { path = "../../../polkadot/runtime/parachains" } -polkadot-primitives = { path = "../../../polkadot/primitives" } -sp-runtime = { path = "../../../substrate/primitives/runtime" } -sp-std = { path = "../../../substrate/primitives/std" } -sp-io = { path = "../../../substrate/primitives/io" } +frame = { features = ["experimental", "runtime"], workspace = true, default-features = true } +codec = { workspace = true, default-features = true } +scale-info = { workspace = true } +polkadot-parachain-primitives = { workspace = true, default-features = true } +polkadot-runtime-parachains = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-std = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } # Some pallets -pallet-message-queue = { path = "../../../substrate/frame/message-queue" } -pallet-balances = { path = "../../../substrate/frame/balances" } +pallet-message-queue = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } # For building docs simple-mermaid = { git = "https://github.com/kianenigma/simple-mermaid.git", branch = "main" } -docify = "0.2.6" +docify = { workspace = true } [dev-dependencies] -test-log = "0.2.14" +test-log = { workspace = true } 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 e3fdda2e733376ca3eb780acbc17256c12e6acac..e7d00ac71038b4f02d5172584a398f185864f46c 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 @@ -36,7 +36,7 @@ construct_runtime! { } } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +#[derive_impl(frame_system::config_preludes::TestDefaultConfig)] impl frame_system::Config for Runtime { type Block = Block; type AccountId = AccountId; @@ -49,8 +49,7 @@ impl mock_message_queue::Config for Runtime { type XcmExecutor = XcmExecutor; } -#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig as pallet_balances::DefaultConfig)] +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Runtime { - type Balance = Balance; type AccountStore = System; } diff --git a/polkadot/xcm/docs/src/cookbook/relay_token_transactor/relay_chain/mod.rs b/polkadot/xcm/docs/src/cookbook/relay_token_transactor/relay_chain/mod.rs index 25c35dd4aaa83c12b0176ea528d09f7d84bc87ce..686f86b37b73204e877ab3c935797ce92540816e 100644 --- a/polkadot/xcm/docs/src/cookbook/relay_token_transactor/relay_chain/mod.rs +++ b/polkadot/xcm/docs/src/cookbook/relay_token_transactor/relay_chain/mod.rs @@ -36,7 +36,7 @@ parameter_types! { pub const BlockHashCount: u64 = 250; } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +#[derive_impl(frame_system::config_preludes::TestDefaultConfig)] impl frame_system::Config for Runtime { type AccountId = AccountId; type Lookup = IdentityLookup; @@ -44,7 +44,7 @@ impl frame_system::Config for Runtime { type AccountData = pallet_balances::AccountData; } -#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig as pallet_balances::DefaultConfig)] +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Runtime { type AccountStore = System; } diff --git a/polkadot/xcm/pallet-xcm-benchmarks/Cargo.toml b/polkadot/xcm/pallet-xcm-benchmarks/Cargo.toml index 8bf3b9abf66349834b3c2b7d7cd367e4b0b835d8..1177d094c6c38a1a3efe4f7bd76bde715d1a2ffd 100644 --- a/polkadot/xcm/pallet-xcm-benchmarks/Cargo.toml +++ b/polkadot/xcm/pallet-xcm-benchmarks/Cargo.toml @@ -13,29 +13,29 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-support = { path = "../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } -sp-io = { path = "../../../substrate/primitives/io", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../xcm-executor", default-features = false } -frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-features = false } -xcm = { package = "staging-xcm", path = "..", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../xcm-builder", default-features = false } +codec = { workspace = true } +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 } +xcm = { workspace = true } +xcm-builder = { workspace = true } log = { workspace = true, default-features = true } [dev-dependencies] -pallet-balances = { path = "../../../substrate/frame/balances" } -pallet-assets = { path = "../../../substrate/frame/assets" } -sp-tracing = { path = "../../../substrate/primitives/tracing" } -xcm = { package = "staging-xcm", path = ".." } +pallet-balances = { workspace = true, default-features = true } +pallet-assets = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +xcm = { workspace = true, default-features = true } # temp -pallet-xcm = { path = "../pallet-xcm" } -polkadot-runtime-common = { path = "../../runtime/common" } +pallet-xcm = { workspace = true, default-features = true } +polkadot-runtime-common = { workspace = true, default-features = true } # westend-runtime = { path = "../../runtime/westend", features = ["runtime-benchmarks"] } -polkadot-primitives = { path = "../../primitives" } +polkadot-primitives = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/polkadot/xcm/pallet-xcm/Cargo.toml b/polkadot/xcm/pallet-xcm/Cargo.toml index 6f9b389ab6f12db50c27fab0f5f20961c7f171c6..0cce7a3449389875a7658f20e4012640e13cd394 100644 --- a/polkadot/xcm/pallet-xcm/Cargo.toml +++ b/polkadot/xcm/pallet-xcm/Cargo.toml @@ -10,32 +10,32 @@ license.workspace = true workspace = true [dependencies] -bounded-collections = { version = "0.2.0", default-features = false } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +bounded-collections = { workspace = true } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } serde = { optional = true, features = ["derive"], workspace = true, default-features = true } log = { workspace = true } -frame-support = { path = "../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -sp-core = { path = "../../../substrate/primitives/core", default-features = false } -sp-io = { path = "../../../substrate/primitives/io", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-core = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } -xcm = { package = "staging-xcm", path = "..", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../xcm-executor", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../xcm-builder", default-features = false } -xcm-fee-payment-runtime-api = { path = "../xcm-fee-payment-runtime-api", default-features = false } +xcm = { workspace = true } +xcm-executor = { workspace = true } +xcm-builder = { workspace = true } +xcm-runtime-apis = { workspace = true } # marked optional, used in benchmarking -frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-features = false, optional = true } -pallet-balances = { path = "../../../substrate/frame/balances", default-features = false, optional = true } +frame-benchmarking = { optional = true, workspace = true } +pallet-balances = { optional = true, workspace = true } [dev-dependencies] -pallet-assets = { path = "../../../substrate/frame/assets" } -polkadot-runtime-parachains = { path = "../../runtime/parachains" } -polkadot-parachain-primitives = { path = "../../parachain" } +pallet-assets = { workspace = true, default-features = true } +polkadot-runtime-parachains = { workspace = true, default-features = true } +polkadot-parachain-primitives = { workspace = true, default-features = true } [features] default = ["std"] @@ -55,7 +55,7 @@ std = [ "sp-std/std", "xcm-builder/std", "xcm-executor/std", - "xcm-fee-payment-runtime-api/std", + "xcm-runtime-apis/std", "xcm/std", ] runtime-benchmarks = [ @@ -69,7 +69,7 @@ runtime-benchmarks = [ "sp-runtime/runtime-benchmarks", "xcm-builder/runtime-benchmarks", "xcm-executor/runtime-benchmarks", - "xcm-fee-payment-runtime-api/runtime-benchmarks", + "xcm-runtime-apis/runtime-benchmarks", ] try-runtime = [ "frame-support/try-runtime", diff --git a/polkadot/xcm/pallet-xcm/src/lib.rs b/polkadot/xcm/pallet-xcm/src/lib.rs index 8f67e6e7d949693e25556af272ea73e443b620df..668f07c52ce35e8009d33abc3f1d021e07f85394 100644 --- a/polkadot/xcm/pallet-xcm/src/lib.rs +++ b/polkadot/xcm/pallet-xcm/src/lib.rs @@ -64,7 +64,7 @@ use xcm_executor::{ }, AssetsInHolding, }; -use xcm_fee_payment_runtime_api::{ +use xcm_runtime_apis::{ dry_run::{CallDryRunEffects, Error as XcmDryRunApiError, XcmDryRunEffects}, fees::Error as XcmPaymentApiError, }; @@ -1376,7 +1376,7 @@ pub mod pallet { /// - `assets`: The assets to be withdrawn. This should include the assets used to pay the /// fee on the `dest` (and possibly reserve) chains. /// - `assets_transfer_type`: The XCM `TransferType` used to transfer the `assets`. - /// - `remote_fees_id`: One of the included `assets` to be be used to pay fees. + /// - `remote_fees_id`: One of the included `assets` to be used to pay fees. /// - `fees_transfer_type`: The XCM `TransferType` used to transfer the `fees` assets. /// - `custom_xcm_on_dest`: The XCM to be executed on `dest` chain as the last step of the /// transfer, which also determines what happens to the assets on the destination chain. @@ -2442,7 +2442,7 @@ impl Pallet { /// /// Returns not only the call result and events, but also the local XCM, if any, /// and any XCMs forwarded to other locations. - /// Meant to be used in the `xcm_fee_payment_runtime_api::dry_run::DryRunApi` runtime API. + /// Meant to be used in the `xcm_runtime_apis::dry_run::DryRunApi` runtime API. pub fn dry_run_call( origin: OriginCaller, call: RuntimeCall, @@ -2474,7 +2474,7 @@ impl Pallet { /// Dry-runs `xcm` with the given `origin_location`. /// /// Returns execution result, events, and any forwarded XCMs to other locations. - /// Meant to be used in the `xcm_fee_payment_runtime_api::dry_run::DryRunApi` runtime API. + /// Meant to be used in the `xcm_runtime_apis::dry_run::DryRunApi` runtime API. pub fn dry_run_xcm( origin_location: VersionedLocation, xcm: VersionedXcm, diff --git a/polkadot/xcm/pallet-xcm/src/mock.rs b/polkadot/xcm/pallet-xcm/src/mock.rs index ead98e1d046005360743b921fe3d70cd93c06a1b..2be6f301f85621489ab6986aaf300251fd239fbc 100644 --- a/polkadot/xcm/pallet-xcm/src/mock.rs +++ b/polkadot/xcm/pallet-xcm/src/mock.rs @@ -266,24 +266,13 @@ impl frame_system::Config for Test { parameter_types! { pub ExistentialDeposit: Balance = 1; - pub const MaxLocks: u32 = 50; - pub const MaxReserves: u32 = 50; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxLocks = MaxLocks; type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type WeightInfo = (); - type MaxReserves = MaxReserves; - type ReserveIdentifier = [u8; 8]; - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeFreezeReason; - type FreezeIdentifier = (); - type MaxFreezes = ConstU32<0>; } #[cfg(feature = "runtime-benchmarks")] diff --git a/polkadot/xcm/procedural/Cargo.toml b/polkadot/xcm/procedural/Cargo.toml index ca9fb351bd3cad1f805106e405cfdcc496c9d8a8..a7db183bcdbf89b2b642f2eb8eea9f87019f086d 100644 --- a/polkadot/xcm/procedural/Cargo.toml +++ b/polkadot/xcm/procedural/Cargo.toml @@ -14,11 +14,11 @@ workspace = true proc-macro = true [dependencies] -proc-macro2 = "1.0.56" +proc-macro2 = { workspace = true } quote = { workspace = true } syn = { workspace = true } -Inflector = "0.11.4" +Inflector = { workspace = true } [dev-dependencies] -trybuild = { version = "1.0.88", features = ["diff"] } -xcm = { package = "staging-xcm", path = ".." } +trybuild = { features = ["diff"], workspace = true } +xcm = { workspace = true, default-features = true } diff --git a/polkadot/xcm/src/v2/mod.rs b/polkadot/xcm/src/v2/mod.rs index 38e55d0ea51e5844640b2e9613f830f7cd636e7f..fe7f05dd887cfa6745a02c32154247c6d0f75398 100644 --- a/polkadot/xcm/src/v2/mod.rs +++ b/polkadot/xcm/src/v2/mod.rs @@ -237,7 +237,7 @@ pub enum BodyPart { #[codec(compact)] denom: u32, }, - /// More than than the given proportion of members of the body. + /// More than the given proportion of members of the body. MoreThanProportion { #[codec(compact)] nom: u32, diff --git a/polkadot/xcm/src/v3/junction.rs b/polkadot/xcm/src/v3/junction.rs index 0920775ab8d584cf1bea995bf8bfd0edc82437b4..24e9c16bf699a9f2bdbc6221b55c33760ecf2282 100644 --- a/polkadot/xcm/src/v3/junction.rs +++ b/polkadot/xcm/src/v3/junction.rs @@ -187,7 +187,7 @@ pub enum BodyPart { #[codec(compact)] denom: u32, }, - /// More than than the given proportion of members of the body. + /// More than the given proportion of members of the body. MoreThanProportion { #[codec(compact)] nom: u32, diff --git a/polkadot/xcm/xcm-builder/Cargo.toml b/polkadot/xcm/xcm-builder/Cargo.toml index 79c601b98b4fd012202a8a4de00b2d254a7c8023..d43506aa651b4d719c42b8633649936036b04741 100644 --- a/polkadot/xcm/xcm-builder/Cargo.toml +++ b/polkadot/xcm/xcm-builder/Cargo.toml @@ -10,34 +10,34 @@ version = "7.0.0" workspace = true [dependencies] -impl-trait-for-tuples = "0.2.1" -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -xcm = { package = "staging-xcm", path = "..", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../xcm-executor", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } -sp-arithmetic = { path = "../../../substrate/primitives/arithmetic", default-features = false } -sp-io = { path = "../../../substrate/primitives/io", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-weights = { path = "../../../substrate/primitives/weights", default-features = false } -frame-support = { path = "../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -pallet-transaction-payment = { path = "../../../substrate/frame/transaction-payment", default-features = false } +impl-trait-for-tuples = { workspace = true } +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 } +sp-weights = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-transaction-payment = { workspace = true } log = { workspace = true } # Polkadot dependencies -polkadot-parachain-primitives = { path = "../../parachain", default-features = false } +polkadot-parachain-primitives = { workspace = true } [dev-dependencies] -primitive-types = "0.12.1" -pallet-balances = { path = "../../../substrate/frame/balances" } -pallet-xcm = { path = "../pallet-xcm" } -pallet-salary = { path = "../../../substrate/frame/salary" } -pallet-assets = { path = "../../../substrate/frame/assets" } -polkadot-primitives = { path = "../../primitives" } -polkadot-runtime-parachains = { path = "../../runtime/parachains" } -assert_matches = "1.5.0" -polkadot-test-runtime = { path = "../../runtime/test-runtime" } +primitive-types = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +pallet-xcm = { workspace = true, default-features = true } +pallet-salary = { workspace = true, default-features = true } +pallet-assets = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-runtime-parachains = { workspace = true, default-features = true } +assert_matches = { workspace = true } +polkadot-test-runtime = { workspace = true } [features] default = ["std"] diff --git a/polkadot/xcm/xcm-builder/tests/mock/mod.rs b/polkadot/xcm/xcm-builder/tests/mock/mod.rs index 62b448a9f430c106516dd4f134ae38d9fc5db47b..582d596b78f1092397dc821dd9152f4295a350fd 100644 --- a/polkadot/xcm/xcm-builder/tests/mock/mod.rs +++ b/polkadot/xcm/xcm-builder/tests/mock/mod.rs @@ -17,7 +17,7 @@ use codec::Encode; use frame_support::{ construct_runtime, derive_impl, parameter_types, - traits::{ConstU32, Everything, Nothing}, + traits::{Everything, Nothing}, weights::Weight, }; use frame_system::EnsureRoot; @@ -102,24 +102,14 @@ impl frame_system::Config for Runtime { parameter_types! { pub ExistentialDeposit: Balance = 1 * CENTS; - pub const MaxLocks: u32 = 50; - pub const MaxReserves: u32 = 50; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Runtime { - type MaxLocks = MaxLocks; type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type WeightInfo = (); - type MaxReserves = MaxReserves; type ReserveIdentifier = [u8; 8]; - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeFreezeReason; - type FreezeIdentifier = (); - type MaxFreezes = ConstU32<0>; } impl shared::Config for Runtime { diff --git a/polkadot/xcm/xcm-executor/Cargo.toml b/polkadot/xcm/xcm-executor/Cargo.toml index 3b30b4f13e2dd498945767a6e6d4c87a43333bc1..8f7b94612b597c239e15afee33f04b07e3a77dc0 100644 --- a/polkadot/xcm/xcm-executor/Cargo.toml +++ b/polkadot/xcm/xcm-executor/Cargo.toml @@ -10,20 +10,20 @@ version = "7.0.0" workspace = true [dependencies] -impl-trait-for-tuples = "0.2.2" -environmental = { version = "1.1.4", default-features = false } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive", "serde"] } -xcm = { package = "staging-xcm", path = "..", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } -sp-io = { path = "../../../substrate/primitives/io", default-features = false } -sp-arithmetic = { path = "../../../substrate/primitives/arithmetic", default-features = false } -sp-core = { path = "../../../substrate/primitives/core", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-weights = { path = "../../../substrate/primitives/weights", default-features = false } -frame-support = { path = "../../../substrate/frame/support", default-features = false } +impl-trait-for-tuples = { workspace = true } +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 } -frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-features = false, optional = true } +frame-benchmarking = { optional = true, workspace = true } [features] default = ["std"] diff --git a/polkadot/xcm/xcm-executor/integration-tests/Cargo.toml b/polkadot/xcm/xcm-executor/integration-tests/Cargo.toml index 37c2117e7b06fc62f33e71c3c57164caf26d4c9b..e669e5d2b2312fbba56a86a6b8518506ba350543 100644 --- a/polkadot/xcm/xcm-executor/integration-tests/Cargo.toml +++ b/polkadot/xcm/xcm-executor/integration-tests/Cargo.toml @@ -11,24 +11,24 @@ publish = false workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12" } -frame-support = { path = "../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../substrate/frame/system" } -futures = "0.3.30" -pallet-transaction-payment = { path = "../../../../substrate/frame/transaction-payment" } -pallet-xcm = { path = "../../pallet-xcm" } -polkadot-test-client = { path = "../../../node/test/client" } -polkadot-test-runtime = { path = "../../../runtime/test-runtime" } -polkadot-test-service = { path = "../../../node/test/service" } -polkadot-service = { path = "../../../node/service" } -sp-consensus = { path = "../../../../substrate/primitives/consensus/common" } -sp-keyring = { path = "../../../../substrate/primitives/keyring" } -sp-runtime = { path = "../../../../substrate/primitives/runtime", default-features = false } -sp-state-machine = { path = "../../../../substrate/primitives/state-machine" } -xcm = { package = "staging-xcm", path = "../..", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = ".." } -sp-tracing = { path = "../../../../substrate/primitives/tracing" } -sp-core = { path = "../../../../substrate/primitives/core" } +codec = { workspace = true, default-features = true } +frame-support = { workspace = true } +frame-system = { workspace = true, default-features = true } +futures = { workspace = true } +pallet-transaction-payment = { workspace = true, default-features = true } +pallet-xcm = { workspace = true, default-features = true } +polkadot-test-client = { workspace = true } +polkadot-test-runtime = { workspace = true } +polkadot-test-service = { workspace = true } +polkadot-service = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +sp-runtime = { workspace = true } +sp-state-machine = { workspace = true, default-features = true } +xcm = { workspace = true } +xcm-executor = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/polkadot/xcm/xcm-fee-payment-runtime-api/Cargo.toml b/polkadot/xcm/xcm-fee-payment-runtime-api/Cargo.toml deleted file mode 100644 index 6fa0236dfb41d5e2a4ec2749a402a8f73be60eb4..0000000000000000000000000000000000000000 --- a/polkadot/xcm/xcm-fee-payment-runtime-api/Cargo.toml +++ /dev/null @@ -1,71 +0,0 @@ -[package] -name = "xcm-fee-payment-runtime-api" -version = "0.1.0" -authors.workspace = true -edition.workspace = true -license = "Apache-2.0" -repository.workspace = true -description = "XCM fee payment runtime API" - -[package.metadata.docs.rs] -targets = ["x86_64-unknown-linux-gnu"] - -[dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ - "derive", -] } - -sp-api = { path = "../../../substrate/primitives/api", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = [ - "derive", - "serde", -] } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-weights = { path = "../../../substrate/primitives/weights", default-features = false } -xcm = { package = "staging-xcm", path = "../", default-features = false } -frame-support = { path = "../../../substrate/frame/support", default-features = false } - -[dev-dependencies] -frame-system = { path = "../../../substrate/frame/system", default-features = false } -pallet-xcm = { path = "../pallet-xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../xcm-builder", default-features = false } -sp-io = { path = "../../../substrate/primitives/io", default-features = false } -pallet-balances = { path = "../../../substrate/frame/balances", default-features = false } -pallet-assets = { path = "../../../substrate/frame/assets", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../xcm-executor", default-features = false } -frame-executive = { path = "../../../substrate/frame/executive", default-features = false } -log = { workspace = true } -env_logger = "0.9.0" - -[features] -default = ["std"] -std = [ - "codec/std", - "frame-executive/std", - "frame-support/std", - "frame-system/std", - "log/std", - "pallet-assets/std", - "pallet-balances/std", - "pallet-xcm/std", - "scale-info/std", - "sp-api/std", - "sp-io/std", - "sp-runtime/std", - "sp-std/std", - "sp-weights/std", - "xcm-builder/std", - "xcm-executor/std", - "xcm/std", -] -runtime-benchmarks = [ - "frame-support/runtime-benchmarks", - "frame-system/runtime-benchmarks", - "pallet-assets/runtime-benchmarks", - "pallet-balances/runtime-benchmarks", - "pallet-xcm/runtime-benchmarks", - "sp-runtime/runtime-benchmarks", - "xcm-builder/runtime-benchmarks", - "xcm-executor/runtime-benchmarks", -] diff --git a/polkadot/xcm/xcm-runtime-apis/Cargo.toml b/polkadot/xcm/xcm-runtime-apis/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..7d3f1a20b639a719db1fbc023dcc688eff6f2a52 --- /dev/null +++ b/polkadot/xcm/xcm-runtime-apis/Cargo.toml @@ -0,0 +1,65 @@ +[package] +name = "xcm-runtime-apis" +version = "0.1.0" +authors.workspace = true +edition.workspace = true +license = "Apache-2.0" +repository.workspace = true +description = "XCM runtime APIs" + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] + +[dependencies] +codec = { features = ["derive"], workspace = true } +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 } + +[dev-dependencies] +frame-system = { workspace = true } +sp-io = { workspace = true } +xcm-builder = { workspace = true } +hex-literal = { workspace = true } +pallet-xcm = { workspace = true } +pallet-balances = { workspace = true } +pallet-assets = { workspace = true } +xcm-executor = { workspace = true } +frame-executive = { workspace = true } +log = { workspace = true } +env_logger = { workspace = true } + +[features] +default = ["std"] +std = [ + "codec/std", + "frame-executive/std", + "frame-support/std", + "frame-system/std", + "log/std", + "pallet-assets/std", + "pallet-balances/std", + "pallet-xcm/std", + "scale-info/std", + "sp-api/std", + "sp-io/std", + "sp-std/std", + "sp-weights/std", + "xcm-builder/std", + "xcm-executor/std", + "xcm/std", +] +runtime-benchmarks = [ + "frame-support/runtime-benchmarks", + "frame-system/runtime-benchmarks", + "pallet-assets/runtime-benchmarks", + "pallet-balances/runtime-benchmarks", + "pallet-xcm/runtime-benchmarks", + "xcm-builder/runtime-benchmarks", + "xcm-executor/runtime-benchmarks", +] diff --git a/polkadot/xcm/xcm-runtime-apis/src/conversions.rs b/polkadot/xcm/xcm-runtime-apis/src/conversions.rs new file mode 100644 index 0000000000000000000000000000000000000000..d422664557e0eb94729a6876fc9001cf786d4b72 --- /dev/null +++ b/polkadot/xcm/xcm-runtime-apis/src/conversions.rs @@ -0,0 +1,56 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Substrate 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. + +// Substrate 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 . + +//! Contains runtime APIs for useful conversions, such as between XCM `Location` and `AccountId`. + +use codec::{Decode, Encode}; +use scale_info::TypeInfo; +use xcm::VersionedLocation; +use xcm_executor::traits::ConvertLocation; + +sp_api::decl_runtime_apis! { + /// API for useful conversions between XCM `Location` and `AccountId`. + pub trait LocationToAccountApi where AccountId: Decode { + /// Converts `Location` to `AccountId`. + fn convert_location(location: VersionedLocation) -> Result; + } +} + +#[derive(Copy, Clone, Encode, Decode, Eq, PartialEq, Debug, TypeInfo)] +pub enum Error { + /// Requested `Location` is not supported by the local conversion. + #[codec(index = 0)] + Unsupported, + + /// Converting a versioned data structure from one version to another failed. + #[codec(index = 1)] + VersionedConversionFailed, +} + +/// A helper implementation that can be used for `LocationToAccountApi` implementations. +/// It is useful when you already have a `ConvertLocation` implementation and a default +/// `Ss58Prefix`. +pub struct LocationToAccountHelper( + sp_std::marker::PhantomData<(AccountId, Conversion)>, +); +impl> + LocationToAccountHelper +{ + pub fn convert_location(location: VersionedLocation) -> Result { + let location = location.try_into().map_err(|_| Error::VersionedConversionFailed)?; + Conversion::convert_location(&location).ok_or(Error::Unsupported) + } +} diff --git a/polkadot/xcm/xcm-fee-payment-runtime-api/src/dry_run.rs b/polkadot/xcm/xcm-runtime-apis/src/dry_run.rs similarity index 100% rename from polkadot/xcm/xcm-fee-payment-runtime-api/src/dry_run.rs rename to polkadot/xcm/xcm-runtime-apis/src/dry_run.rs diff --git a/polkadot/xcm/xcm-fee-payment-runtime-api/src/fees.rs b/polkadot/xcm/xcm-runtime-apis/src/fees.rs similarity index 100% rename from polkadot/xcm/xcm-fee-payment-runtime-api/src/fees.rs rename to polkadot/xcm/xcm-runtime-apis/src/fees.rs diff --git a/polkadot/xcm/xcm-fee-payment-runtime-api/src/lib.rs b/polkadot/xcm/xcm-runtime-apis/src/lib.rs similarity index 74% rename from polkadot/xcm/xcm-fee-payment-runtime-api/src/lib.rs rename to polkadot/xcm/xcm-runtime-apis/src/lib.rs index 616ee4c2eccb0aeed1cdb5e2aa524855d8b2df82..7b3b86214b3a14d3886b8dec2928d564358e370f 100644 --- a/polkadot/xcm/xcm-fee-payment-runtime-api/src/lib.rs +++ b/polkadot/xcm/xcm-runtime-apis/src/lib.rs @@ -14,19 +14,17 @@ // You should have received a copy of the GNU General Public License // along with Polkadot. If not, see . -//! Runtime APIs for estimating xcm fee payment. -//! This crate offers two APIs, one for estimating fees, -//! which can be used for any type of message, and another one -//! for returning the specific messages used for transfers, a common -//! feature. -//! Users of these APIs should call the transfers API and pass the result to the -//! fees API. +//! Various runtime APIs to support XCM processing and manipulation. #![cfg_attr(not(feature = "std"), no_std)] +/// Exposes runtime APIs for various XCM-related conversions. +pub mod conversions; + /// Dry-run API. /// Given an extrinsic or an XCM program, it returns the outcome of its execution. pub mod dry_run; + /// Fee estimation API. /// Given an XCM program, it will return the fees needed to execute it properly or send it. pub mod fees; diff --git a/polkadot/xcm/xcm-runtime-apis/tests/conversions.rs b/polkadot/xcm/xcm-runtime-apis/tests/conversions.rs new file mode 100644 index 0000000000000000000000000000000000000000..7f0f0923b092116e0ad10f4b287dda8c93f5357f --- /dev/null +++ b/polkadot/xcm/xcm-runtime-apis/tests/conversions.rs @@ -0,0 +1,83 @@ +// Copyright (C) Parity Technologies (UK) Ltd. +// This file is part of Polkadot. + +// Substrate 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. + +// Substrate 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 . + +mod mock; + +use frame_support::{ + assert_err, assert_ok, + sp_runtime::{ + testing::H256, + traits::{IdentifyAccount, Verify}, + AccountId32, MultiSignature, + }, +}; +use mock::*; +use sp_api::ProvideRuntimeApi; +use xcm::prelude::*; +use xcm_runtime_apis::conversions::{ + Error as LocationToAccountApiError, LocationToAccountApi, LocationToAccountHelper, +}; + +#[test] +fn convert_location_to_account_works() { + sp_io::TestExternalities::default().execute_with(|| { + let client = TestClient {}; + let runtime_api = client.runtime_api(); + + // Test unknown conversion for `Here` location + assert_err!( + runtime_api + .convert_location(H256::zero(), VersionedLocation::from(Location::here())) + .unwrap(), + LocationToAccountApiError::Unsupported + ); + + // Test known conversion for sibling parachain location + assert_ok!( + runtime_api + .convert_location(H256::zero(), VersionedLocation::from((Parent, Parachain(1000)))) + .unwrap(), + 1000_u64 + ); + }) +} + +#[test] +fn location_to_account_helper_with_multi_signature_works() { + type Signature = MultiSignature; + type AccountIdForConversions = <::Signer as IdentifyAccount>::AccountId; + // We alias only `Location::parent()` + pub type LocationToAccountIdForConversions = + (xcm_builder::ParentIsPreset,); + + // Test unknown conversion for `Here` location + assert_err!( + LocationToAccountHelper::< + AccountIdForConversions, + LocationToAccountIdForConversions, + >::convert_location(Location::here().into_versioned()), + LocationToAccountApiError::Unsupported + ); + + // Test known conversion for `Parent` location + assert_ok!( + LocationToAccountHelper::< + AccountIdForConversions, + LocationToAccountIdForConversions, + >::convert_location(Location::parent().into_versioned()), + AccountId32::from(hex_literal::hex!("506172656e740000000000000000000000000000000000000000000000000000")) + ); +} diff --git a/polkadot/xcm/xcm-fee-payment-runtime-api/tests/fee_estimation.rs b/polkadot/xcm/xcm-runtime-apis/tests/fee_estimation.rs similarity index 99% rename from polkadot/xcm/xcm-fee-payment-runtime-api/tests/fee_estimation.rs rename to polkadot/xcm/xcm-runtime-apis/tests/fee_estimation.rs index 33611c8a471c03a34c125a921b24a51880dfbb3f..59ee17973805621ce360546afb0b1583abfbdc9a 100644 --- a/polkadot/xcm/xcm-fee-payment-runtime-api/tests/fee_estimation.rs +++ b/polkadot/xcm/xcm-runtime-apis/tests/fee_estimation.rs @@ -16,11 +16,11 @@ //! Tests for using both the XCM fee payment API and the dry-run API. +use frame_support::sp_runtime::testing::H256; use frame_system::RawOrigin; use sp_api::ProvideRuntimeApi; -use sp_runtime::testing::H256; use xcm::prelude::*; -use xcm_fee_payment_runtime_api::{dry_run::DryRunApi, fees::XcmPaymentApi}; +use xcm_runtime_apis::{dry_run::DryRunApi, fees::XcmPaymentApi}; mod mock; use mock::{ diff --git a/polkadot/xcm/xcm-fee-payment-runtime-api/tests/mock.rs b/polkadot/xcm/xcm-runtime-apis/tests/mock.rs similarity index 96% rename from polkadot/xcm/xcm-fee-payment-runtime-api/tests/mock.rs rename to polkadot/xcm/xcm-runtime-apis/tests/mock.rs index aa6c1422b608c955fc74934811f4f136212507cb..3b73070da45a9060a574be09af664bc0d22f91bc 100644 --- a/polkadot/xcm/xcm-fee-payment-runtime-api/tests/mock.rs +++ b/polkadot/xcm/xcm-runtime-apis/tests/mock.rs @@ -19,7 +19,11 @@ use codec::Encode; use frame_support::{ - construct_runtime, derive_impl, parameter_types, + construct_runtime, derive_impl, parameter_types, sp_runtime, + sp_runtime::{ + traits::{Dispatchable, Get, IdentityLookup, MaybeEquivalence, TryConvert}, + BuildStorage, SaturatedConversion, + }, traits::{ AsEnsureOriginWithArg, ConstU128, ConstU32, Contains, ContainsPair, Everything, Nothing, OriginTrait, @@ -28,10 +32,6 @@ use frame_support::{ }; use frame_system::{EnsureRoot, RawOrigin as SystemRawOrigin}; use pallet_xcm::TestWeightInfo; -use sp_runtime::{ - traits::{Dispatchable, Get, IdentityLookup, MaybeEquivalence, TryConvert}, - BuildStorage, SaturatedConversion, -}; use sp_std::{cell::RefCell, marker::PhantomData}; use xcm::{prelude::*, Version as XcmVersion}; use xcm_builder::{ @@ -44,7 +44,8 @@ use xcm_executor::{ XcmExecutor, }; -use xcm_fee_payment_runtime_api::{ +use xcm_runtime_apis::{ + conversions::{Error as LocationToAccountApiError, LocationToAccountApi}, dry_run::{CallDryRunEffects, DryRunApi, Error as XcmDryRunApiError, XcmDryRunEffects}, fees::{Error as XcmPaymentApiError, XcmPaymentApi}, }; @@ -352,6 +353,7 @@ impl pallet_xcm::Config for TestRuntime { type WeightInfo = TestWeightInfo; } +#[allow(dead_code)] pub fn new_test_ext_with_balances(balances: Vec<(AccountId, Balance)>) -> sp_io::TestExternalities { let mut t = frame_system::GenesisConfig::::default().build_storage().unwrap(); @@ -364,6 +366,7 @@ pub fn new_test_ext_with_balances(balances: Vec<(AccountId, Balance)>) -> sp_io: ext } +#[allow(dead_code)] pub fn new_test_ext_with_balances_and_assets( balances: Vec<(AccountId, Balance)>, assets: Vec<(AssetIdForAssetsPallet, AccountId, Balance)>, @@ -410,6 +413,14 @@ impl sp_api::ProvideRuntimeApi for TestClient { } sp_api::mock_impl_runtime_apis! { + impl LocationToAccountApi for RuntimeApi { + fn convert_location(location: VersionedLocation) -> Result { + let location = location.try_into().map_err(|_| LocationToAccountApiError::VersionedConversionFailed)?; + LocationToAccountId::convert_location(&location) + .ok_or(LocationToAccountApiError::Unsupported) + } + } + impl XcmPaymentApi for RuntimeApi { fn query_acceptable_payment_assets(xcm_version: XcmVersion) -> Result, XcmPaymentApiError> { Ok(vec![ diff --git a/polkadot/xcm/xcm-simulator/Cargo.toml b/polkadot/xcm/xcm-simulator/Cargo.toml index fc09b5e31861c0cb6470e7d7c121e8c94e1f60f8..c7caa49393ed5c7fa505b38d1a2eaac208d63465 100644 --- a/polkadot/xcm/xcm-simulator/Cargo.toml +++ b/polkadot/xcm/xcm-simulator/Cargo.toml @@ -10,20 +10,20 @@ license.workspace = true workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12" } -scale-info = { version = "2.6.0", default-features = false } -paste = "1.0.7" +codec = { workspace = true, default-features = true } +scale-info = { workspace = true } +paste = { workspace = true, default-features = true } -frame-support = { path = "../../../substrate/frame/support" } -frame-system = { path = "../../../substrate/frame/system" } -sp-io = { path = "../../../substrate/primitives/io" } -sp-std = { path = "../../../substrate/primitives/std" } -sp-runtime = { path = "../../../substrate/primitives/runtime" } +frame-support = { workspace = true, default-features = true } +frame-system = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-std = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } -xcm = { package = "staging-xcm", path = ".." } -xcm-executor = { package = "staging-xcm-executor", path = "../xcm-executor" } -xcm-builder = { package = "staging-xcm-builder", path = "../xcm-builder" } -polkadot-primitives = { path = "../../primitives" } -polkadot-core-primitives = { path = "../../core-primitives" } -polkadot-parachain-primitives = { path = "../../parachain" } -polkadot-runtime-parachains = { path = "../../runtime/parachains" } +xcm = { workspace = true, default-features = true } +xcm-executor = { workspace = true, default-features = true } +xcm-builder = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-core-primitives = { workspace = true, default-features = true } +polkadot-parachain-primitives = { workspace = true, default-features = true } +polkadot-runtime-parachains = { workspace = true, default-features = true } diff --git a/polkadot/xcm/xcm-simulator/example/Cargo.toml b/polkadot/xcm/xcm-simulator/example/Cargo.toml index 8b04170e3032f90adb6f4c3c5d3954729e009b20..e0aff9b7782a7e4fa8c73dc5cfaae51af2035533 100644 --- a/polkadot/xcm/xcm-simulator/example/Cargo.toml +++ b/polkadot/xcm/xcm-simulator/example/Cargo.toml @@ -10,29 +10,29 @@ version = "7.0.0" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12" } -scale-info = { version = "2.11.1", features = ["derive"] } +codec = { workspace = true, default-features = true } +scale-info = { features = ["derive"], workspace = true, default-features = true } log = { workspace = true } -frame-system = { path = "../../../../substrate/frame/system" } -frame-support = { path = "../../../../substrate/frame/support" } -pallet-balances = { path = "../../../../substrate/frame/balances" } -pallet-message-queue = { path = "../../../../substrate/frame/message-queue" } -pallet-uniques = { path = "../../../../substrate/frame/uniques" } -sp-std = { path = "../../../../substrate/primitives/std" } -sp-core = { path = "../../../../substrate/primitives/core" } -sp-runtime = { path = "../../../../substrate/primitives/runtime" } -sp-io = { path = "../../../../substrate/primitives/io" } -sp-tracing = { path = "../../../../substrate/primitives/tracing" } +frame-system = { workspace = true, default-features = true } +frame-support = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +pallet-message-queue = { workspace = true, default-features = true } +pallet-uniques = { workspace = true, default-features = true } +sp-std = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } -xcm = { package = "staging-xcm", path = "../.." } -xcm-simulator = { path = ".." } -xcm-executor = { package = "staging-xcm-executor", path = "../../xcm-executor" } -xcm-builder = { package = "staging-xcm-builder", path = "../../xcm-builder" } -pallet-xcm = { path = "../../pallet-xcm" } -polkadot-core-primitives = { path = "../../../core-primitives" } -polkadot-runtime-parachains = { path = "../../../runtime/parachains" } -polkadot-parachain-primitives = { path = "../../../parachain" } +xcm = { workspace = true, default-features = true } +xcm-simulator = { workspace = true, default-features = true } +xcm-executor = { workspace = true, default-features = true } +xcm-builder = { workspace = true, default-features = true } +pallet-xcm = { workspace = true, default-features = true } +polkadot-core-primitives = { workspace = true, default-features = true } +polkadot-runtime-parachains = { workspace = true, default-features = true } +polkadot-parachain-primitives = { workspace = true, default-features = true } [features] default = [] diff --git a/polkadot/xcm/xcm-simulator/fuzzer/Cargo.toml b/polkadot/xcm/xcm-simulator/fuzzer/Cargo.toml index 6b3b4018d9fbb30862eee8fa5ea1408c96b2f68e..04f8ba115173465b14127cb277bcc74776ea1a5b 100644 --- a/polkadot/xcm/xcm-simulator/fuzzer/Cargo.toml +++ b/polkadot/xcm/xcm-simulator/fuzzer/Cargo.toml @@ -11,30 +11,30 @@ publish = false workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12" } -honggfuzz = "0.5.55" -arbitrary = "1.3.2" -scale-info = { version = "2.11.1", features = ["derive"] } +codec = { workspace = true, default-features = true } +honggfuzz = { workspace = true } +arbitrary = { workspace = true } +scale-info = { features = ["derive"], workspace = true, default-features = true } -frame-system = { path = "../../../../substrate/frame/system" } -frame-support = { path = "../../../../substrate/frame/support" } -frame-executive = { path = "../../../../substrate/frame/executive" } -frame-try-runtime = { path = "../../../../substrate/frame/try-runtime" } -pallet-balances = { path = "../../../../substrate/frame/balances" } -pallet-message-queue = { path = "../../../../substrate/frame/message-queue" } -sp-std = { path = "../../../../substrate/primitives/std" } -sp-core = { path = "../../../../substrate/primitives/core" } -sp-runtime = { path = "../../../../substrate/primitives/runtime" } -sp-io = { path = "../../../../substrate/primitives/io" } +frame-system = { workspace = true, default-features = true } +frame-support = { workspace = true, default-features = true } +frame-executive = { workspace = true, default-features = true } +frame-try-runtime = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +pallet-message-queue = { workspace = true, default-features = true } +sp-std = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } -xcm = { package = "staging-xcm", path = "../.." } -xcm-simulator = { path = ".." } -xcm-executor = { package = "staging-xcm-executor", path = "../../xcm-executor" } -xcm-builder = { package = "staging-xcm-builder", path = "../../xcm-builder" } -pallet-xcm = { path = "../../pallet-xcm" } -polkadot-core-primitives = { path = "../../../core-primitives" } -polkadot-runtime-parachains = { path = "../../../runtime/parachains" } -polkadot-parachain-primitives = { path = "../../../parachain" } +xcm = { workspace = true, default-features = true } +xcm-simulator = { workspace = true, default-features = true } +xcm-executor = { workspace = true, default-features = true } +xcm-builder = { workspace = true, default-features = true } +pallet-xcm = { workspace = true, default-features = true } +polkadot-core-primitives = { workspace = true, default-features = true } +polkadot-runtime-parachains = { workspace = true, default-features = true } +polkadot-parachain-primitives = { workspace = true, default-features = true } [features] try-runtime = [ diff --git a/polkadot/xcm/xcm-simulator/fuzzer/src/parachain.rs b/polkadot/xcm/xcm-simulator/fuzzer/src/parachain.rs index 502bcca2d44270263a45eeaf305b924d8b37c509..11435868d4682ae4229b7939f2a8685316c7e296 100644 --- a/polkadot/xcm/xcm-simulator/fuzzer/src/parachain.rs +++ b/polkadot/xcm/xcm-simulator/fuzzer/src/parachain.rs @@ -24,7 +24,6 @@ use frame_support::{ }; use frame_system::EnsureRoot; -use sp_core::ConstU32; use sp_runtime::{ generic, traits::{AccountIdLookup, BlakeTwo256, Hash, IdentifyAccount, Verify}, @@ -73,24 +72,13 @@ impl frame_system::Config for Runtime { parameter_types! { pub ExistentialDeposit: Balance = 1; - pub const MaxLocks: u32 = 50; - pub const MaxReserves: u32 = 50; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Runtime { - type MaxLocks = MaxLocks; type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type WeightInfo = (); - type MaxReserves = MaxReserves; - type ReserveIdentifier = [u8; 8]; - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeFreezeReason; - type FreezeIdentifier = (); - type MaxFreezes = ConstU32<0>; } parameter_types! { diff --git a/polkadot/xcm/xcm-simulator/fuzzer/src/relay_chain.rs b/polkadot/xcm/xcm-simulator/fuzzer/src/relay_chain.rs index 4740aee83d870a0e260512ac15a982c515a1e803..459d2640b6d908b14e0964aa2e2a697f95c7dbd3 100644 --- a/polkadot/xcm/xcm-simulator/fuzzer/src/relay_chain.rs +++ b/polkadot/xcm/xcm-simulator/fuzzer/src/relay_chain.rs @@ -72,24 +72,13 @@ impl frame_system::Config for Runtime { parameter_types! { pub ExistentialDeposit: Balance = 1; - pub const MaxLocks: u32 = 50; - pub const MaxReserves: u32 = 50; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Runtime { - type MaxLocks = MaxLocks; type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type WeightInfo = (); - type MaxReserves = MaxReserves; - type ReserveIdentifier = [u8; 8]; - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeFreezeReason; - type FreezeIdentifier = (); - type MaxFreezes = ConstU32<0>; } impl shared::Config for Runtime { diff --git a/polkadot/zombienet_tests/assign-core.js b/polkadot/zombienet_tests/assign-core.js new file mode 100644 index 0000000000000000000000000000000000000000..5ddb86930f5a0a04380e1e4cbef5c96f81db4fe0 --- /dev/null +++ b/polkadot/zombienet_tests/assign-core.js @@ -0,0 +1,48 @@ +async function run(nodeName, networkInfo, args) { + const wsUri = networkInfo.nodesByName[nodeName].wsUri; + const api = await zombie.connect(wsUri); + + let core = Number(args[0]); + + let assignments = []; + + for (let i = 1; i < args.length; i += 2) { + let [para, parts] = [args[i], args[i + 1]]; + + console.log(`Assigning para ${para} to core ${core}`); + + assignments.push( + [{ task: para }, parts] + ); + } + await zombie.util.cryptoWaitReady(); + + // account to submit tx + const keyring = new zombie.Keyring({ type: "sr25519" }); + const alice = keyring.addFromUri("//Alice"); + + await new Promise(async (resolve, reject) => { + const unsub = await api.tx.sudo + .sudo(api.tx.coretime.assignCore(core, 0, assignments, null)) + .signAndSend(alice, ({ status, isError }) => { + if (status.isInBlock) { + console.log( + `Transaction included at blockhash ${status.asInBlock}`, + ); + } else if (status.isFinalized) { + console.log( + `Transaction finalized at blockHash ${status.asFinalized}`, + ); + unsub(); + return resolve(); + } else if (isError) { + console.log(`Transaction error`); + reject(`Transaction error`); + } + }); + }); + + return 0; +} + +module.exports = { run }; diff --git a/polkadot/zombienet_tests/elastic_scaling/0001-basic-3cores-6s-blocks.zndsl b/polkadot/zombienet_tests/elastic_scaling/0001-basic-3cores-6s-blocks.zndsl index d624cbaf9df6a62448db2cef637e6d29a0d419b5..d47ef8f415f7ac9ca94b825de23580ab6131f013 100644 --- a/polkadot/zombienet_tests/elastic_scaling/0001-basic-3cores-6s-blocks.zndsl +++ b/polkadot/zombienet_tests/elastic_scaling/0001-basic-3cores-6s-blocks.zndsl @@ -11,8 +11,8 @@ elastic-validator-4: reports node_roles is 4 # Register 2 extra cores to this some-parachain. -elastic-validator-0: js-script ./assign-core.js with "2000,0" return is 0 within 600 seconds -elastic-validator-0: js-script ./assign-core.js with "2000,1" return is 0 within 600 seconds +elastic-validator-0: js-script ./assign-core.js with "0,2000,57600" return is 0 within 600 seconds +elastic-validator-0: js-script ./assign-core.js with "1,2000,57600" return is 0 within 600 seconds # Wait for 20 relay chain blocks elastic-validator-0: reports substrate_block_height{status="best"} is at least 20 within 600 seconds diff --git a/polkadot/zombienet_tests/elastic_scaling/0002-elastic-scaling-doesnt-break-parachains.zndsl b/polkadot/zombienet_tests/elastic_scaling/0002-elastic-scaling-doesnt-break-parachains.zndsl index 900a3befbc6fc56f5200e9399f5fe5b21eb7af40..7ba896e1c90397642ff0736477f9c793bdb746ec 100644 --- a/polkadot/zombienet_tests/elastic_scaling/0002-elastic-scaling-doesnt-break-parachains.zndsl +++ b/polkadot/zombienet_tests/elastic_scaling/0002-elastic-scaling-doesnt-break-parachains.zndsl @@ -11,8 +11,8 @@ validator: reports substrate_block_height{status="finalized"} is at least 10 wit validator: parachain 2000 block height is at least 10 within 200 seconds # Register the second core assigned to this parachain. -alice: js-script ./assign-core.js with "2000,0" return is 0 within 600 seconds -alice: js-script ./assign-core.js with "2000,1" return is 0 within 600 seconds +alice: js-script ./assign-core.js with "0,2000,57600" return is 0 within 600 seconds +alice: js-script ./assign-core.js with "0,2000,57600" return is 0 within 600 seconds validator: reports substrate_block_height{status="finalized"} is at least 35 within 100 seconds diff --git a/polkadot/zombienet_tests/elastic_scaling/assign-core.js b/polkadot/zombienet_tests/elastic_scaling/assign-core.js deleted file mode 100644 index add63b6d30859d2c50a38a73e33ec75ed3669433..0000000000000000000000000000000000000000 --- a/polkadot/zombienet_tests/elastic_scaling/assign-core.js +++ /dev/null @@ -1,39 +0,0 @@ -async function run(nodeName, networkInfo, args) { - const wsUri = networkInfo.nodesByName[nodeName].wsUri; - const api = await zombie.connect(wsUri); - - let para = Number(args[0]); - let core = Number(args[1]); - console.log(`Assigning para ${para} to core ${core}`); - - await zombie.util.cryptoWaitReady(); - - // account to submit tx - const keyring = new zombie.Keyring({ type: "sr25519" }); - const alice = keyring.addFromUri("//Alice"); - - await new Promise(async (resolve, reject) => { - const unsub = await api.tx.sudo - .sudo(api.tx.coretime.assignCore(core, 0, [[{ task: para }, 57600]], null)) - .signAndSend(alice, ({ status, isError }) => { - if (status.isInBlock) { - console.log( - `Transaction included at blockhash ${status.asInBlock}`, - ); - } else if (status.isFinalized) { - console.log( - `Transaction finalized at blockHash ${status.asFinalized}`, - ); - unsub(); - return resolve(); - } else if (isError) { - console.log(`Transaction error`); - reject(`Transaction error`); - } - }); - }); - - return 0; -} - -module.exports = { run }; diff --git a/polkadot/zombienet_tests/elastic_scaling/assign-core.js b/polkadot/zombienet_tests/elastic_scaling/assign-core.js new file mode 120000 index 0000000000000000000000000000000000000000..eeb6402c06f5e52cedf150f924d6791beb1d9867 --- /dev/null +++ b/polkadot/zombienet_tests/elastic_scaling/assign-core.js @@ -0,0 +1 @@ +../assign-core.js \ No newline at end of file diff --git a/polkadot/zombienet_tests/functional/0015-coretime-shared-core.toml b/polkadot/zombienet_tests/functional/0015-coretime-shared-core.toml new file mode 100644 index 0000000000000000000000000000000000000000..fed30e0db05321631fdce66da858e1431ded64dd --- /dev/null +++ b/polkadot/zombienet_tests/functional/0015-coretime-shared-core.toml @@ -0,0 +1,44 @@ +[settings] +timeout = 1000 + +[relaychain.genesis.runtimeGenesis.patch.configuration.config.async_backing_params] + max_candidate_depth = 3 + allowed_ancestry_len = 2 + +[relaychain.genesis.runtimeGenesis.patch.configuration.config.scheduler_params] + max_validators_per_core = 1 + lookahead = 2 + num_cores = 4 + +[relaychain.genesis.runtimeGenesis.patch.configuration.config.approval_voting_params] + needed_approvals = 3 + +[relaychain] +default_image = "{{ZOMBIENET_INTEGRATION_TEST_IMAGE}}" +chain = "rococo-local" +command = "polkadot" + + [[relaychain.node_groups]] + name = "validator" + args = ["-lruntime=debug,parachain=debug,parachain::backing=trace,parachain::collator-protocol=trace,parachain::prospective-parachains=trace,runtime::parachains::scheduler=trace,runtime::inclusion-inherent=trace,runtime::inclusion=trace" ] + count = 4 + +{% for id in range(2000,2004) %} +[[parachains]] +id = {{id}} +register_para = false +onboard_as_parachain = false +add_to_genesis = false +chain = "glutton-westend-local-{{id}}" + [parachains.genesis.runtimeGenesis.patch.glutton] + compute = "50000000" + storage = "2500000000" + trashDataCount = 5120 + + [parachains.collator] + name = "collator-{{id}}" + image = "{{CUMULUS_IMAGE}}" + command = "polkadot-parachain" + args = ["-lparachain=debug"] + +{% endfor %} diff --git a/polkadot/zombienet_tests/functional/0015-coretime-shared-core.zndsl b/polkadot/zombienet_tests/functional/0015-coretime-shared-core.zndsl new file mode 100644 index 0000000000000000000000000000000000000000..b8b8887df85782268735f906eab771ddfcc22fcf --- /dev/null +++ b/polkadot/zombienet_tests/functional/0015-coretime-shared-core.zndsl @@ -0,0 +1,16 @@ +Description: CT shared core test +Network: ./0015-coretime-shared-core.toml +Creds: config + +validator: reports node_roles is 4 + +# register paras 2 by 2 to speed up the test. registering all at once will exceed the weight limit. +validator-0: js-script ./0015-force-register-paras.js with "2000,2001" return is 0 within 600 seconds +validator-0: js-script ./0015-force-register-paras.js with "2002,2003" return is 0 within 600 seconds +# assign core 0 to be shared by all paras. +validator-0: js-script ./assign-core.js with "0,2000,14400,2001,14400,2002,14400,2003,14400" return is 0 within 600 seconds + +collator-2000: reports block height is at least 6 within 200 seconds +collator-2001: reports block height is at least 6 within 50 seconds +collator-2002: reports block height is at least 6 within 50 seconds +collator-2003: reports block height is at least 6 within 50 seconds diff --git a/polkadot/zombienet_tests/functional/0015-force-register-paras.js b/polkadot/zombienet_tests/functional/0015-force-register-paras.js new file mode 100644 index 0000000000000000000000000000000000000000..f82163b01105a4b7bee09d6827860b685c38890e --- /dev/null +++ b/polkadot/zombienet_tests/functional/0015-force-register-paras.js @@ -0,0 +1,63 @@ +async function run(nodeName, networkInfo, args) { + const init = networkInfo.nodesByName[nodeName]; + let wsUri = init.wsUri; + let userDefinedTypes = init.userDefinedTypes; + const api = await zombie.connect(wsUri, userDefinedTypes); + + // account to submit tx + const keyring = new zombie.Keyring({ type: "sr25519" }); + const alice = keyring.addFromUri("//Alice"); + + let calls = []; + + for (let i = 0; i < args.length; i++) { + let para = args[i]; + const sec = networkInfo.nodesByName["collator-" + para]; + const api_collator = await zombie.connect(sec.wsUri, sec.userDefinedTypes); + + await zombie.util.cryptoWaitReady(); + + // Get the genesis header and the validation code of the parachain + const genesis_header = await api_collator.rpc.chain.getHeader(); + const validation_code = await api_collator.rpc.state.getStorage("0x3A636F6465"); + + calls.push( + api.tx.paras.addTrustedValidationCode(validation_code.toHex()) + ); + calls.push( + api.tx.registrar.forceRegister( + alice.address, + 0, + Number(para), + genesis_header.toHex(), + validation_code.toHex(), + ) + ); + } + + const sudo_batch = api.tx.sudo.sudo(api.tx.utility.batch(calls)); + + await new Promise(async (resolve, reject) => { + const unsub = await sudo_batch + .signAndSend(alice, ({ status, isError }) => { + if (status.isInBlock) { + console.log( + `Transaction included at blockhash ${status.asInBlock}`, + ); + } else if (status.isFinalized) { + console.log( + `Transaction finalized at blockHash ${status.asFinalized}`, + ); + unsub(); + return resolve(); + } else if (isError) { + console.log(`Transaction error`); + reject(`Transaction error`); + } + }); + }); + + return 0; +} + +module.exports = { run }; diff --git a/polkadot/zombienet_tests/functional/assign-core.js b/polkadot/zombienet_tests/functional/assign-core.js new file mode 120000 index 0000000000000000000000000000000000000000..eeb6402c06f5e52cedf150f924d6791beb1d9867 --- /dev/null +++ b/polkadot/zombienet_tests/functional/assign-core.js @@ -0,0 +1 @@ +../assign-core.js \ No newline at end of file diff --git a/prdoc/1.13.0/pr_1223.prdoc b/prdoc/1.13.0/pr_1223.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..08b18557b70c6b649c49bb1dd62acc9528a79a86 --- /dev/null +++ b/prdoc/1.13.0/pr_1223.prdoc @@ -0,0 +1,13 @@ +title: Optimize storage append operation + +doc: + - audience: [Node Dev, Runtime Dev] + description: | + This pull request optimizes the storage append operation in the `OverlayedChanges`. + Before the internal buffer was cloned every time a new transaction was created. Cloning + the internal buffer is now only done when there is no other possibility. This should + improve the performance in situations like when depositing events from batched calls. + +crates: + - name: sp-state-machine + bump: major diff --git a/prdoc/pr_1644.prdoc b/prdoc/1.13.0/pr_1644.prdoc similarity index 100% rename from prdoc/pr_1644.prdoc rename to prdoc/1.13.0/pr_1644.prdoc diff --git a/prdoc/pr_3393.prdoc b/prdoc/1.13.0/pr_3393.prdoc similarity index 100% rename from prdoc/pr_3393.prdoc rename to prdoc/1.13.0/pr_3393.prdoc diff --git a/prdoc/pr_3905.prdoc b/prdoc/1.13.0/pr_3905.prdoc similarity index 100% rename from prdoc/pr_3905.prdoc rename to prdoc/1.13.0/pr_3905.prdoc diff --git a/prdoc/pr_3935.prdoc b/prdoc/1.13.0/pr_3935.prdoc similarity index 100% rename from prdoc/pr_3935.prdoc rename to prdoc/1.13.0/pr_3935.prdoc diff --git a/prdoc/pr_3952.prdoc b/prdoc/1.13.0/pr_3952.prdoc similarity index 100% rename from prdoc/pr_3952.prdoc rename to prdoc/1.13.0/pr_3952.prdoc diff --git a/prdoc/pr_4131.prdoc b/prdoc/1.13.0/pr_4131.prdoc similarity index 100% rename from prdoc/pr_4131.prdoc rename to prdoc/1.13.0/pr_4131.prdoc diff --git a/prdoc/pr_4198.prdoc b/prdoc/1.13.0/pr_4198.prdoc similarity index 100% rename from prdoc/pr_4198.prdoc rename to prdoc/1.13.0/pr_4198.prdoc diff --git a/prdoc/pr_4233.prdoc b/prdoc/1.13.0/pr_4233.prdoc similarity index 100% rename from prdoc/pr_4233.prdoc rename to prdoc/1.13.0/pr_4233.prdoc diff --git a/prdoc/pr_4249.prdoc b/prdoc/1.13.0/pr_4249.prdoc similarity index 100% rename from prdoc/pr_4249.prdoc rename to prdoc/1.13.0/pr_4249.prdoc diff --git a/prdoc/pr_4274.prdoc b/prdoc/1.13.0/pr_4274.prdoc similarity index 100% rename from prdoc/pr_4274.prdoc rename to prdoc/1.13.0/pr_4274.prdoc diff --git a/prdoc/pr_4339.prdoc b/prdoc/1.13.0/pr_4339.prdoc similarity index 100% rename from prdoc/pr_4339.prdoc rename to prdoc/1.13.0/pr_4339.prdoc diff --git a/prdoc/pr_4380.prdoc b/prdoc/1.13.0/pr_4380.prdoc similarity index 100% rename from prdoc/pr_4380.prdoc rename to prdoc/1.13.0/pr_4380.prdoc diff --git a/prdoc/pr_4392.prdoc b/prdoc/1.13.0/pr_4392.prdoc similarity index 100% rename from prdoc/pr_4392.prdoc rename to prdoc/1.13.0/pr_4392.prdoc diff --git a/prdoc/pr_4410.prdoc b/prdoc/1.13.0/pr_4410.prdoc similarity index 100% rename from prdoc/pr_4410.prdoc rename to prdoc/1.13.0/pr_4410.prdoc diff --git a/prdoc/pr_4418.prdoc b/prdoc/1.13.0/pr_4418.prdoc similarity index 100% rename from prdoc/pr_4418.prdoc rename to prdoc/1.13.0/pr_4418.prdoc diff --git a/prdoc/pr_4431.prdoc b/prdoc/1.13.0/pr_4431.prdoc similarity index 100% rename from prdoc/pr_4431.prdoc rename to prdoc/1.13.0/pr_4431.prdoc diff --git a/prdoc/pr_4444.prdoc b/prdoc/1.13.0/pr_4444.prdoc similarity index 100% rename from prdoc/pr_4444.prdoc rename to prdoc/1.13.0/pr_4444.prdoc diff --git a/prdoc/pr_4465.prdoc b/prdoc/1.13.0/pr_4465.prdoc similarity index 100% rename from prdoc/pr_4465.prdoc rename to prdoc/1.13.0/pr_4465.prdoc diff --git a/prdoc/pr_4471.prdoc b/prdoc/1.13.0/pr_4471.prdoc similarity index 100% rename from prdoc/pr_4471.prdoc rename to prdoc/1.13.0/pr_4471.prdoc diff --git a/prdoc/pr_4472.prdoc b/prdoc/1.13.0/pr_4472.prdoc similarity index 100% rename from prdoc/pr_4472.prdoc rename to prdoc/1.13.0/pr_4472.prdoc diff --git a/prdoc/pr_4475.prdoc b/prdoc/1.13.0/pr_4475.prdoc similarity index 100% rename from prdoc/pr_4475.prdoc rename to prdoc/1.13.0/pr_4475.prdoc diff --git a/prdoc/pr_4478.prdoc b/prdoc/1.13.0/pr_4478.prdoc similarity index 100% rename from prdoc/pr_4478.prdoc rename to prdoc/1.13.0/pr_4478.prdoc diff --git a/prdoc/pr_4503.prdoc b/prdoc/1.13.0/pr_4503.prdoc similarity index 100% rename from prdoc/pr_4503.prdoc rename to prdoc/1.13.0/pr_4503.prdoc diff --git a/prdoc/pr_4510.prdoc b/prdoc/1.13.0/pr_4510.prdoc similarity index 100% rename from prdoc/pr_4510.prdoc rename to prdoc/1.13.0/pr_4510.prdoc diff --git a/prdoc/pr_4514.prdoc b/prdoc/1.13.0/pr_4514.prdoc similarity index 100% rename from prdoc/pr_4514.prdoc rename to prdoc/1.13.0/pr_4514.prdoc diff --git a/prdoc/pr_4521.prdoc b/prdoc/1.13.0/pr_4521.prdoc similarity index 100% rename from prdoc/pr_4521.prdoc rename to prdoc/1.13.0/pr_4521.prdoc diff --git a/prdoc/pr_4533.prdoc b/prdoc/1.13.0/pr_4533.prdoc similarity index 100% rename from prdoc/pr_4533.prdoc rename to prdoc/1.13.0/pr_4533.prdoc diff --git a/prdoc/pr_4534.prdoc b/prdoc/1.13.0/pr_4534.prdoc similarity index 100% rename from prdoc/pr_4534.prdoc rename to prdoc/1.13.0/pr_4534.prdoc diff --git a/prdoc/pr_4537.prdoc b/prdoc/1.13.0/pr_4537.prdoc similarity index 100% rename from prdoc/pr_4537.prdoc rename to prdoc/1.13.0/pr_4537.prdoc diff --git a/prdoc/pr_4541.prdoc b/prdoc/1.13.0/pr_4541.prdoc similarity index 100% rename from prdoc/pr_4541.prdoc rename to prdoc/1.13.0/pr_4541.prdoc diff --git a/prdoc/pr_4542.prdoc b/prdoc/1.13.0/pr_4542.prdoc similarity index 100% rename from prdoc/pr_4542.prdoc rename to prdoc/1.13.0/pr_4542.prdoc diff --git a/prdoc/pr_4555.prdoc b/prdoc/1.13.0/pr_4555.prdoc similarity index 100% rename from prdoc/pr_4555.prdoc rename to prdoc/1.13.0/pr_4555.prdoc diff --git a/prdoc/pr_4571.prdoc b/prdoc/1.13.0/pr_4571.prdoc similarity index 100% rename from prdoc/pr_4571.prdoc rename to prdoc/1.13.0/pr_4571.prdoc diff --git a/prdoc/pr_4595.prdoc b/prdoc/1.13.0/pr_4595.prdoc similarity index 100% rename from prdoc/pr_4595.prdoc rename to prdoc/1.13.0/pr_4595.prdoc diff --git a/prdoc/pr_4621.prdoc b/prdoc/1.13.0/pr_4621.prdoc similarity index 100% rename from prdoc/pr_4621.prdoc rename to prdoc/1.13.0/pr_4621.prdoc diff --git a/prdoc/pr_4633.prdoc b/prdoc/1.13.0/pr_4633.prdoc similarity index 100% rename from prdoc/pr_4633.prdoc rename to prdoc/1.13.0/pr_4633.prdoc diff --git a/prdoc/pr_4634.prdoc b/prdoc/1.13.0/pr_4634.prdoc similarity index 100% rename from prdoc/pr_4634.prdoc rename to prdoc/1.13.0/pr_4634.prdoc diff --git a/prdoc/pr_4645.prdoc b/prdoc/1.13.0/pr_4645.prdoc similarity index 100% rename from prdoc/pr_4645.prdoc rename to prdoc/1.13.0/pr_4645.prdoc diff --git a/prdoc/pr_4646.prdoc b/prdoc/1.13.0/pr_4646.prdoc similarity index 100% rename from prdoc/pr_4646.prdoc rename to prdoc/1.13.0/pr_4646.prdoc diff --git a/prdoc/1.13.0/pr_4721.prdoc b/prdoc/1.13.0/pr_4721.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..730ac4d8308692001c20f30a89276af26a1b14ce --- /dev/null +++ b/prdoc/1.13.0/pr_4721.prdoc @@ -0,0 +1,19 @@ +# 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: Skip tree route calculation if no forks present + +doc: + - audience: Node Operator + description: | + Fixes an issue with synchronisation on parachains. Once they reached the tip of the chain, + nodes would show `Preparing 0.0 bps`. This is shown because the node is blocked on calculating + the tree route from genesis to the tip of the chain many times. This PR solves that by skipping + tree route calculation if there is only one leave. In addition, further optimizations have been + done to alleviate long finalization distances. + +crates: + - name: sp-blockchain + bump: minor + - name: sc-client-db + bump: none diff --git a/prdoc/pr_1631.prdoc b/prdoc/pr_1631.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..f73d00968552a4b0c589a68079971d0dcac503bc --- /dev/null +++ b/prdoc/pr_1631.prdoc @@ -0,0 +1,39 @@ +# 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: Upgrade libp2p to 0.52.4 + +doc: + - audience: [Node Dev, Node Operator] + description: | + Upgrade libp2p from 0.51.4 to 0.52.4 + +crates: + - name: sc-authority-discovery + bump: minor + - name: sc-cli + bump: minor + - name: sc-mixnet + bump: minor + - name: sc-network + bump: minor + - name: sc-network-gossip + bump: minor + - name: sc-network-common + bump: minor + - name: sc-network-light + bump: minor + - name: sc-network-statement + bump: minor + - name: sc-network-sync + bump: minor + - name: sc-network-test + bump: minor + - name: sc-network-transactions + bump: minor + - name: sc-network-types + bump: minor + - name: sc-offchain + bump: major + - name: sc-telemetry + bump: major diff --git a/prdoc/pr_3374.prdoc b/prdoc/pr_3374.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..76744f778db0a5bf5ba259ec2978d4b7e8d4e9b6 --- /dev/null +++ b/prdoc/pr_3374.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: removed `pallet::getter` from `pallet-timestamp` + +doc: + - audience: Runtime Dev + description: | + This PR removes all the `pallet::getter` usages from `pallet-timestamp`, and updates depdendant runtimes accordingly. + The syntax `StorageItem::::get()` should be used instead. + +crates: + - name: pallet-timestamp \ No newline at end of file diff --git a/prdoc/pr_3820.prdoc b/prdoc/pr_3820.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..33e8129df92a3c045f88531f40ee2d1793e591ab --- /dev/null +++ b/prdoc/pr_3820.prdoc @@ -0,0 +1,32 @@ +# 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 deprecated calls from treasury pallet + +doc: + - audience: Runtime User + description: | + This PR remove deprecated calls, relevant tests from `pallet-treasury`. + - Remove deprecated calls `propose_spend`, `reject_proposal`, `approve_proposal`. + - Replace the code flow of `propose_spend` then `approve_proposal` with `spend_local` + - Remove deprecated calls' related weight functions and test cases. + - Remove deprecated parameter types: ProposalBond, ProposalBondMaximum, ProposalBondMinimum + - Remove pallet treasury's relevant deprecated code in pallet-tips, pallet-bounties and pallet-child-bounties + +crates: + - name: pallet-treasury + bump: major + - name: pallet-tips + bump: patch + - name: pallet-child-bounties + bump: patch + - name: pallet-bounties + bump: patch + - name: polkadot-runtime-common + bump: patch + - name: rococo-runtime + bump: patch + - name: westend-runtime + bump: patch + - name: collectives-westend-runtime + bump: patch diff --git a/prdoc/pr_3828.prdoc b/prdoc/pr_3828.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..426625d5f23effb3fe889cacb767650d56921044 --- /dev/null +++ b/prdoc/pr_3828.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: "[FRAME] Remove storage migration type" + +doc: + - audience: Runtime Dev + description: | + Introduce migration type to remove data associated with a specific storage of a pallet. + +crates: + - name: frame-support + bump: minor diff --git a/prdoc/pr_3843.prdoc b/prdoc/pr_3843.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..e01900dcc25b998124a2929f14171d049c2fa698 --- /dev/null +++ b/prdoc/pr_3843.prdoc @@ -0,0 +1,17 @@ +# 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: Introduce a new dispatchable function `set_partial_params` in `pallet-core-fellowship` + +doc: + - audience: Runtime Dev + description: | + This PR adds a new dispatchable function `set_partial_params` + to update config with multiple arguments without duplicating the + fields that does not need to update. + +crates: + - name: pallet-core-fellowship + bump: major + - name: collectives-westend-runtime + bump: patch diff --git a/prdoc/pr_3951.prdoc b/prdoc/pr_3951.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..3a8096e6f448748e090cf0732a7b453fafcb6239 --- /dev/null +++ b/prdoc/pr_3951.prdoc @@ -0,0 +1,30 @@ +# 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 Assets Freezer + +doc: + - audience: Runtime Dev + description: | + This pallet is an extension of `pallet-assets`, supporting + freezes similar to `pallet-balances`. + To use this pallet, set `Freezer` of `pallet-assets` Config to the according instance of + `pallet-assets-freezer`. + - audience: Runtime User + description: | + The storage of this pallet contains a Vecs of account freezes. Applications UIs and Developer + Tools might benefit from observing it. + +crates: + - name: frame-support + bump: minor + - name: pallet-assets-freezer + bump: major + - name: pallet-assets + bump: patch + - name: pallet-balances + bump: patch + - name: asset-hub-rococo-runtime + bump: minor + - name: asset-hub-westend-runtime + bump: minor diff --git a/prdoc/pr_4513.prdoc b/prdoc/pr_4513.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..e7363d211c1700a9ec3a4b38799ad73da0b13038 --- /dev/null +++ b/prdoc/pr_4513.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: Removed `pallet::getter` usage from pallet-elections-phragmen + +doc: + - audience: Runtime Dev + description: | + This PR removed the `pallet::getter`s from `pallet-elections-phragmen`. + The syntax `StorageItem::::get()` should be used instead. + +crates: + - name: pallet-elections-phragmen + bump: major diff --git a/prdoc/pr_4596.prdoc b/prdoc/pr_4596.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..d47aa3aedfb85abcae3bd76f0d0abe31d544816b --- /dev/null +++ b/prdoc/pr_4596.prdoc @@ -0,0 +1,18 @@ +title: "Frame: `Consideration` trait generic over `Footprint` and handles zero cost" + +doc: + - audience: Runtime Dev + description: | + `Consideration` trait generic over `Footprint` and can handle zero cost for a give footprint. + + `Consideration` trait is generic over `Footprint` (currently defined over the type with the same name). This makes it possible to setup a custom footprint (e.g. current number of proposals in the storage). + + `Consideration::new` and `Consideration::update` return an `Option` instead `Self`, this make it possible to define no cost for a specific footprint (e.g. current number of proposals in the storage < max_proposal_count / 2). + +crates: + - name: frame-support + bump: major + - name: pallet-preimage + bump: major + - name: pallet-balances + bump: patch diff --git a/prdoc/pr_4618.prdoc b/prdoc/pr_4618.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..3dd0fce81eeee54a411aef89442c233da204af68 --- /dev/null +++ b/prdoc/pr_4618.prdoc @@ -0,0 +1,20 @@ +title: Unify logic for fetching the `:code` of a block + +doc: + - audience: Node Operator + description: | + Fixes an issue on parachains when running with a custom `substitute` of the on chain wasm code + and having replaced the wasm code on the relay chain. The relay chain was rejecting blocks + build this way, because the collator was reporting the actual on chain wasm code hash + to the relay chain. However, the relay chain was expecting the code hash of the wasm code substitute + that was also registered on the relay chain. + - audience: Node Dev + description: | + `Client::code_at` will now use the same `substitute` to determine the code for a given block as it is + done when executing any runtime call. + +crates: + - name: cumulus-client-consensus-aura + bump: minor + - name: sc-service + bump: minor diff --git a/prdoc/pr_4684.prdoc b/prdoc/pr_4684.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..b1c429c57822494cd11f75beea93c4dabf2764cb --- /dev/null +++ b/prdoc/pr_4684.prdoc @@ -0,0 +1,13 @@ +title: "Refactor of the parachain template" + +doc: + - audience: Runtime Dev + description: | + Introduce the construct runtime V2 to the parachain template runtime. In addition, url links in the parachain pallet + template now direct to the polkadot sdk docs. + +crates: + - name: pallet-parachain-template + bump: none + - name: parachain-template-runtime + bump: none diff --git a/prdoc/pr_4685.prdoc b/prdoc/pr_4685.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..e212919ba2e5bcfede725c1afbdd27115dc5e229 --- /dev/null +++ b/prdoc/pr_4685.prdoc @@ -0,0 +1,16 @@ +# 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: Chain-spec-builder supports `codeSubstitutes`. + +doc: + - audience: Node Operator + description: | + A new subcommand `add-code-substitute` is available for the `chain-spec-builder` binary. It allows users to provide a runtime that should be used from a given + block onwards. The `codeSubstitutes` field in the chain spec is used to force usage of a given runtime at a given block until the next runtime upgrade. It can be + used to progress chains that are stalled due to runtime bugs that prevent block-building. However, parachain usage is only possible in combination with an updated + validation function on the relay chain. + +crates: + - name: staging-chain-spec-builder + bump: minor diff --git a/prdoc/pr_4710.prdoc b/prdoc/pr_4710.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..d7d31d817208a44402c53d2941750108c250f683 --- /dev/null +++ b/prdoc/pr_4710.prdoc @@ -0,0 +1,11 @@ +title: "Dont partially modify HRMP pages" + +doc: + - audience: Runtime Dev + description: | + The xcmp-queue pallet now does not partially modify a page anymore when the next message does + not fully fit into it but instead cleanly creates a new one. + +crates: + - name: cumulus-pallet-xcmp-queue + bump: patch diff --git a/prdoc/pr_4724.prdoc b/prdoc/pr_4724.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..3723c2a70246ad40ad139c4da6e770fd386996f4 --- /dev/null +++ b/prdoc/pr_4724.prdoc @@ -0,0 +1,24 @@ +title: Fix core sharing and make use of scheduling_lookahead during backing + +doc: + - audience: Node Dev + description: | + Core sharing (two or more parachains scheduled on the same core with interlaced assignments) was not working correctly. + Adds the neccessary fixes to the backing subsystems. Moreover, adds support for backing collations which are built + and advertised ahead of time (with up to `scheduling_lookahead` relay chain blocks in advance). + +crates: + - name: polkadot-node-core-backing + bump: patch + - name: polkadot-node-core-prospective-parachains + bump: patch + - name: polkadot-collator-protocol + bump: patch + - name: polkadot-statement-distribution + bump: patch + - name: polkadot-node-subsystem-util + bump: minor + - name: polkadot-runtime-parachains + bump: none + - name: polkadot + bump: none diff --git a/prdoc/pr_4728.prdoc b/prdoc/pr_4728.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..1494fbdbb2b9fb2a534e3fa47d13ee46996b180d --- /dev/null +++ b/prdoc/pr_4728.prdoc @@ -0,0 +1,17 @@ +# 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: "Glutton - add support for bloating the parachain block length" + +doc: + - audience: [Runtime Dev, Runtime User] + description: | + Introduce a new configuration parameter `block_length` which can be configured via a call to + `set_block_length`. This sets the ration of the block length that is to be filled with trash. + This is implemented by an inherent that takes trash data as a parameter filling the block length. + +crates: + - name: pallet-glutton + bump: major + - name: glutton-westend-runtime + bump: major diff --git a/prdoc/pr_4730.prdoc b/prdoc/pr_4730.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..9af14534bcbd28a600c1bb838ae6ff7f8512f563 --- /dev/null +++ b/prdoc/pr_4730.prdoc @@ -0,0 +1,25 @@ +# 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: rpc upgrade jsonrpsee to v0.23.1 + +doc: + - audience: Node Dev + description: | + Upgrade the rpc library jsonrpsee to v0.23.1 to utilize: + + - Add Extensions which we now is using to get the connection id (used by the rpc spec v2) + - Update hyper to v1.0, http v1.0, soketto and related crates (hyper::service::make_service_fn is removed) + - The subscription API for the client is modified to know why a subscription was closed. + +crates: + - name: sc-rpc-spec-v2 + bump: patch + - name: sc-rpc + bump: patch + - name: sc-rpc-server + bump: patch + - name: cumulus-relay-chain-rpc-interface + bump: patch + - name: frame-remote-externalities + bump: patch diff --git a/prdoc/pr_4733.prdoc b/prdoc/pr_4733.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..e633248398526c43fc0da478779c4fea86524e7a --- /dev/null +++ b/prdoc/pr_4733.prdoc @@ -0,0 +1,27 @@ +title: Add pov-recovery unit tests and support for elastic scaling + +doc: + - audience: Node Dev + description: | + Adds unit tests for cumulus pov-recovery and support for elastic scaling (recovering multiple candidates in a single relay chain block). + +crates: + - name: cumulus-client-network + bump: patch + - name: cumulus-client-pov-recovery + bump: patch + - name: cumulus-relay-chain-interface + bump: major + validate: false + - name: cumulus-relay-chain-inprocess-interface + bump: minor + - name: cumulus-relay-chain-rpc-interface + bump: minor + - name: cumulus-client-consensus-common + bump: none + - name: sc-client-api + bump: minor + - name: sp-blockchain + bump: minor + - name: sp-consensus + bump: minor diff --git a/prdoc/pr_4756.prdoc b/prdoc/pr_4756.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..064a79fb06648a39c6983c92a80028fff093355d --- /dev/null +++ b/prdoc/pr_4756.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: Do not make pallet-nfts benchmarks signature-dependent + +doc: + - audience: Runtime Dev + description: | + - Adds extra functionality to pallet-nfts's BenchmarkHelper to provide signers and sign message. + - Abstracts away the explicit link with Sr25519 schema in the benchmarks, allowing parachains with a different one to be able to run them and calculate the weights. + - Adds a default implementation for the empty tuple that leaves the code equivalent. + +crates: + - name: pallet-nfts + bump: minor diff --git a/prdoc/pr_4765.prdoc b/prdoc/pr_4765.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..f64b2fdc51ab12c59aac8a247bf69026dffb9bf1 --- /dev/null +++ b/prdoc/pr_4765.prdoc @@ -0,0 +1,18 @@ +title: CheckWeight - account for extrinsic len as proof size + +doc: + - audience: Runtime Dev + description: | + This changes how CheckWeight extension works. It will now account for the extrinsic length + as proof size. When `on_idle` is called, the remaining weight parameter reflects this. + +crates: + - name: frame-system + bump: patch + - name: frame-executive + bump: none + - name: cumulus-primitives-storage-weight-reclaim + bump: none + + + diff --git a/prdoc/pr_4769.prdoc b/prdoc/pr_4769.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..e9691ba6f89744f073f8b0e794706e755aa59f0a --- /dev/null +++ b/prdoc/pr_4769.prdoc @@ -0,0 +1,20 @@ +title: Use real rust type for pallet alias in `runtime` macro + +doc: + - audience: Runtime Dev + description: | + This PR adds the ability to use a real rust type for pallet alias in the new `runtime` macro: + ```rust + #[runtime::pallet_index(0)] + pub type System = frame_system::Pallet; + ``` + + Please note that the current syntax still continues to be supported. + +crates: + - name: frame-support-procedural + bump: patch + - name: frame-support + bump: patch + - name: minimal-template-runtime + bump: patch diff --git a/prdoc/pr_4802.prdoc b/prdoc/pr_4802.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..5757c4cbae184444d4eb78b620bcef50a3b0e133 --- /dev/null +++ b/prdoc/pr_4802.prdoc @@ -0,0 +1,16 @@ +# 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 `health/readiness endpoint` to the rpc server + +doc: + - audience: Node Operator + description: | + Add `/health/readiness endpoint` to the rpc server which returns HTTP status code 200 if the chain is synced + and can connect to the rest of the network otherwise status code 500 is returned. + The endpoint can be reached by performing a HTTP GET request to the + endpoint such as `$ curl /health/readiness` + +crates: + - name: sc-rpc-server + bump: patch diff --git a/prdoc/pr_4807.prdoc b/prdoc/pr_4807.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..b60bfb524510a17f50df19fbbb985dc0d263a9d6 --- /dev/null +++ b/prdoc/pr_4807.prdoc @@ -0,0 +1,11 @@ +title: "pallet ranked collective: max member count per rank" + +doc: + - audience: Runtime Dev + description: | + Configuration for the maximum member count per rank, with the option for no limit. + +crates: + - name: pallet-ranked-collective + bump: major + diff --git a/prdoc/pr_4823.prdoc b/prdoc/pr_4823.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..a498b33f7bfa949078ca23ac196116b7f5b2f1f9 --- /dev/null +++ b/prdoc/pr_4823.prdoc @@ -0,0 +1,11 @@ +title: "`pallet-referenda`: Ensure to schedule referendas earliest at the next block" + +doc: + - audience: Runtime User + description: | + Ensure that referendas are scheduled earliest at the next block when they are enacted. + Otherwise the scheduling may fails and thus, the enactment of the referenda. + +crates: + - name: pallet-referenda + bump: patch diff --git a/prdoc/pr_4831.prdoc b/prdoc/pr_4831.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..8629ead6e81d80306bb69cf57ed14cea49313010 --- /dev/null +++ b/prdoc/pr_4831.prdoc @@ -0,0 +1,25 @@ +title: "treasury pallet: - remove unused config parameters" + +doc: + - audience: Runtime Dev + description: | + Remove unused config parameters `ApproveOrigin` and `OnSlash` from the treasury pallet. + Add `OnSlash` config parameter to the bounties and tips pallets. + +crates: + - name: pallet-treasury + bump: major + - name: pallet-bounties + bump: major + - name: pallet-tips + bump: major + - name: collectives-westend-runtime + bump: patch + - name: polkadot-runtime-common + bump: patch + - name: rococo-runtime + bump: patch + - name: westend-runtime + bump: patch + - name: kitchensink-runtime + bump: patch diff --git a/prdoc/pr_4833.prdoc b/prdoc/pr_4833.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..a5cf853696eee38fc2659a3357eb7be7fe5f860a --- /dev/null +++ b/prdoc/pr_4833.prdoc @@ -0,0 +1,12 @@ +title: "Reinitialize should allow to override existing config in collationGeneration" + +doc: + - audience: Node Dev + description: | + The Reinitialize collationGeneration subsystem message currently fails if no other config is already set. + As it is difficult to query the collationGeneration subsystem to check when to call Initialize or Reinitialize, this PR + proposes that Reinitialize overrides the configuration regardless if there was one already set. + +crates: + - name: polkadot-node-collation-generation + bump: minor diff --git a/prdoc/pr_4844.prdoc b/prdoc/pr_4844.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..999e63c84ed9a0491c6b4683a5ed3d5b25efa8c2 --- /dev/null +++ b/prdoc/pr_4844.prdoc @@ -0,0 +1,34 @@ +title: Make `Verifier::verify` and `BlockImport::check_block` use `&self` instead of `&mut self` + +doc: + - audience: Node Dev + description: | + `Verifier::verify` and `BlockImport::check_block` were refactored to use `&self` instead of `&mut self` + because there is no fundamental requirement for those operations to be exclusive in nature. + +crates: +- name: sc-consensus + bump: major + validate: false +- name: sc-consensus-aura + bump: major +- name: sc-consensus-babe + bump: major +- name: sc-consensus-beefy + bump: major +- name: sc-consensus-grandpa + bump: major +- name: sc-consensus-manual-seal + bump: major +- name: sc-consensus-pow + bump: major +- name: sc-service + bump: major +- name: cumulus-client-consensus-common + bump: major +- name: cumulus-client-consensus-aura + bump: major +- name: cumulus-client-consensus-relay-chain + bump: major +- name: polkadot-parachain-bin + validate: false diff --git a/prdoc/pr_4857.prdoc b/prdoc/pr_4857.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..d515e4257622e046c42b4de2638541397463374a --- /dev/null +++ b/prdoc/pr_4857.prdoc @@ -0,0 +1,50 @@ +# 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: "[xcm] runtime api for LocationToAccount conversions" + +doc: + - audience: Runtime Dev + description: | + Introduces a new runtime API to help with conversions of XCM `Location` to the runtime's `AccountId`, + showing an Ss58 formatted address for easier verification. + + Besides that, the `xcm-fee-payment-runtime-api` module was merged into the new `xcm-runtime-apis`. + If you are using the `xcm-fee-payment-runtime-api` dependency, you just need to change it to `xcm-runtime-apis` + and update the imports from `use xcm_fee_payment_runtime_api::*` to `use xcm_runtime_apis::*`. + +crates: + - name: xcm-runtime-apis + bump: none + - name: polkadot-sdk + bump: patch + - name: pallet-xcm + bump: patch + - name: polkadot-service + bump: patch + - name: rococo-runtime + bump: patch + - name: westend-runtime + bump: patch + - name: asset-hub-rococo-runtime + bump: patch + - name: asset-hub-westend-runtime + bump: patch + - name: bridge-hub-rococo-runtime + bump: patch + - name: bridge-hub-westend-runtime + bump: patch + - name: collectives-westend-runtime + bump: patch + - name: people-rococo-runtime + bump: patch + - name: people-westend-runtime + bump: patch + - name: penpal-runtime + bump: patch + - name: contracts-rococo-runtime + bump: patch + - name: coretime-rococo-runtime + bump: patch + - name: coretime-westend-runtime + bump: none diff --git a/prdoc/pr_4865.prdoc b/prdoc/pr_4865.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..48ffd04219cf5ab48bb45bae7449a0176d28ec7e --- /dev/null +++ b/prdoc/pr_4865.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: Implement trait `ContainsLengthBound` for pallet-membership + +doc: + - audience: Runtime Dev + description: | + Implement trait ContainsLengthBound for pallet membership otherwise we can't use it with pallet-tips without wrapper + +crates: + - name: pallet-membership + bump: minor diff --git a/prdoc/pr_4877.prdoc b/prdoc/pr_4877.prdoc new file mode 100644 index 0000000000000000000000000000000000000000..ede536aee450257aaff732870f01d1dfa9106e49 --- /dev/null +++ b/prdoc/pr_4877.prdoc @@ -0,0 +1,13 @@ +title: "Core-Fellowship: new promote_fast call" + +doc: + - audience: Runtime User + description: | + Adds the ability to quickly promote someone within a collective by bypassing the promotion + cooldown. This can help in special situations and comes with a new origin: `FastPromoteOrigin`. + +crates: + - name: pallet-core-fellowship + bump: major + - name: collectives-westend-runtime + bump: major diff --git a/scripts/bench-all.sh b/scripts/bench-all.sh new file mode 100755 index 0000000000000000000000000000000000000000..e5512e26bbad75248f2983a2e3a653e3d1328435 --- /dev/null +++ b/scripts/bench-all.sh @@ -0,0 +1,16 @@ +#!/usr/bin/env bash + +set -eu -o pipefail +shopt -s inherit_errexit +shopt -s globstar + +. "$(realpath "$(dirname "${BASH_SOURCE[0]}")/command-utils.sh")" + +get_arg optional --pallet "$@" +PALLET="${out:-""}" + +if [[ ! -z "$PALLET" ]]; then + . "$(dirname "${BASH_SOURCE[0]}")/lib/bench-all-pallet.sh" "$@" +else + . "$(dirname "${BASH_SOURCE[0]}")/bench.sh" --subcommand=all "$@" +fi diff --git a/scripts/bench.sh b/scripts/bench.sh new file mode 100755 index 0000000000000000000000000000000000000000..2f4ef7ec6a14118630964a835d181d9631a0c605 --- /dev/null +++ b/scripts/bench.sh @@ -0,0 +1,117 @@ +#!/bin/bash +# Initially based on https://github.com/paritytech/bench-bot/blob/cd3b2943d911ae29e41fe6204788ef99c19412c3/bench.js + +# Most external variables used in this script, such as $GH_CONTRIBUTOR, are +# related to https://github.com/paritytech/try-runtime-bot + +# This script relies on $GITHUB_TOKEN which is probably a protected GitLab CI +# variable; if this assumption holds true, it is implied that this script should +# be ran only on protected pipelines + +set -eu -o pipefail +shopt -s inherit_errexit + +# realpath allows to reuse the current +BENCH_ROOT_DIR=$(realpath "$(dirname "${BASH_SOURCE[0]}")") + +. "$(realpath "$(dirname "${BASH_SOURCE[0]}")/command-utils.sh")" + +repository_name="$(basename "$PWD")" + +get_arg optional --target_dir "$@" +target_dir="${out:-""}" + +get_arg optional --noexit "$@" +noexit="${out:-""}" + +output_path="." + +profile="production" + +if [[ "$repository_name" == "polkadot-sdk" ]]; then + output_path="./$target_dir" +fi + +cargo_run_benchmarks="cargo run --quiet --profile=${profile}" + +echo "Repository: $repository_name" +echo "Target Dir: $target_dir" +echo "Output Path: $output_path" + +cargo_run() { + echo "Running $cargo_run_benchmarks" "${args[@]}" + + # if not patched with PATCH_something=123 then use --locked + if [[ -z "${BENCH_PATCHED:-}" ]]; then + cargo_run_benchmarks+=" --locked" + fi + + $cargo_run_benchmarks "${args[@]}" +} + + +main() { + + # Remove the "github" remote since the same repository might be reused by a + # GitLab runner, therefore the remote might already exist from a previous run + # in case it was not cleaned up properly for some reason + &>/dev/null git remote remove github || : + + tmp_dirs=() + cleanup() { + exit_code=$? + # Clean up the "github" remote at the end since it contains the + # $GITHUB_TOKEN secret, which is only available for protected pipelines on + # GitLab + &>/dev/null git remote remove github || : + rm -rf "${tmp_dirs[@]}" + echo "Done, exit: $exit_code" + exit $exit_code + } + + # avoid exit if --noexit is passed + if [ -z "$noexit" ]; then + trap cleanup EXIT + fi + + # set -x + + get_arg required --subcommand "$@" + local subcommand="${out:-""}" + + case "$subcommand" in + runtime|pallet|xcm) + echo 'Running bench_pallet' + . "$BENCH_ROOT_DIR/lib/bench-pallet.sh" "$@" + ;; + overhead) + echo 'Running bench_overhead' + . "$BENCH_ROOT_DIR/lib/bench-overhead.sh" "$@" + ;; + all) + echo "Running all-$target_dir" + . "$BENCH_ROOT_DIR/lib/bench-all-${target_dir}.sh" "$@" + ;; + *) + die "Invalid subcommand $subcommand to process_args" + ;; + esac + + # set +x + + # in case we used diener to patch some dependency during benchmark execution, + # revert the patches so that they're not included in the diff + git checkout --quiet HEAD Cargo.toml + + # Save the generated weights to GitLab artifacts in case commit+push fails + echo "Showing weights diff for command" + git diff -P | tee -a "${ARTIFACTS_DIR}/weights.patch" + echo "Wrote weights patch to \"${ARTIFACTS_DIR}/weights.patch\"" + + + # instead of using `cargo run --locked`, we allow the Cargo files to be updated + # but avoid committing them. It is so `cmd_runner_apply_patches` can work + git restore --staged Cargo.* +} + +main "$@" diff --git a/scripts/command-utils.sh b/scripts/command-utils.sh new file mode 100644 index 0000000000000000000000000000000000000000..252e4c86480e6b259af8a46038e1b9e0658e70fb --- /dev/null +++ b/scripts/command-utils.sh @@ -0,0 +1,80 @@ +#!/usr/bin/env bash + +if [ "${LOADED_UTILS_SH:-}" ]; then + return +else + export LOADED_UTILS_SH=true +fi + +export ARTIFACTS_DIR="$PWD/.git/.artifacts" + +die() { + if [ "${1:-}" ]; then + >&2 echo "$1" + fi + exit 1 +} + +get_arg() { + local arg_type="$1" + shift + + local is_required + case "$arg_type" in + required|required-many) + is_required=true + ;; + optional|optional-many) ;; + *) + die "Invalid is_required argument \"$2\" in get_arg" + ;; + esac + + local has_many_values + if [ "${arg_type: -6}" == "-many" ]; then + has_many_values=true + fi + + local option_arg="$1" + shift + + local args=("$@") + + unset out + out=() + + local get_next_arg + for arg in "${args[@]}"; do + if [ "${get_next_arg:-}" ]; then + out+=("$arg") + unset get_next_arg + if [ ! "${has_many_values:-}" ]; then + break + fi + # --foo=bar (get the value after '=') + elif [ "${arg:0:$(( ${#option_arg} + 1 ))}" == "$option_arg=" ]; then + out+=("${arg:$(( ${#option_arg} + 1 ))}") + if [ ! "${has_many_values:-}" ]; then + break + fi + # --foo bar (get the next argument) + elif [ "$arg" == "$option_arg" ]; then + get_next_arg=true + fi + done + + # arg list ended with --something but no argument was provided next + if [ "${get_next_arg:-}" ]; then + die "Expected argument after \"${args[-1]}"\" + fi + + if [ "${out[0]:-}" ]; then + if [ ! "${has_many_values:-}" ]; then + out="${out[0]}" + fi + elif [ "${is_required:-}" ]; then + die "Argument $option_arg is required, but was not found" + else + unset out + fi +} diff --git a/scripts/lib/bench-all-cumulus.sh b/scripts/lib/bench-all-cumulus.sh new file mode 100755 index 0000000000000000000000000000000000000000..f4c2a35c6b6b7ed8d30fa058666453f5c321b8e1 --- /dev/null +++ b/scripts/lib/bench-all-cumulus.sh @@ -0,0 +1,139 @@ +#!/usr/bin/env bash +# originally moved from https://github.com/paritytech/cumulus/blob/445f9277ab55b4d930ced4fbbb38d27c617c6658/scripts/benchmarks-ci.sh + +# default RUST_LOG is warn, but could be overridden +export RUST_LOG="${RUST_LOG:-error}" + +THIS_DIR=$(dirname "${BASH_SOURCE[0]}") +. "$THIS_DIR/../command-utils.sh" + +POLKADOT_PARACHAIN="./target/$profile/polkadot-parachain" + +run_cumulus_bench() { + local artifactsDir="$ARTIFACTS_DIR" + local category=$1 + local runtimeName=$2 + local paraId=${3:-} + + local benchmarkOutput="$output_path/parachains/runtimes/$category/$runtimeName/src/weights" + local benchmarkRuntimeChain + if [[ ! -z "$paraId" ]]; then + benchmarkRuntimeChain="${runtimeName}-dev-$paraId" + else + benchmarkRuntimeChain="$runtimeName-dev" + fi + + local benchmarkMetadataOutputDir="$artifactsDir/$runtimeName" + mkdir -p "$benchmarkMetadataOutputDir" + + # Load all pallet names in an array. + echo "[+] Listing pallets for runtime $runtimeName for chain: $benchmarkRuntimeChain ..." + local pallets=($( + $POLKADOT_PARACHAIN benchmark pallet --list --chain="${benchmarkRuntimeChain}" |\ + tail -n+2 |\ + cut -d',' -f1 |\ + sort |\ + uniq + )) + + if [ ${#pallets[@]} -ne 0 ]; then + echo "[+] Benchmarking ${#pallets[@]} pallets for runtime $runtimeName for chain: $benchmarkRuntimeChain, pallets:" + for pallet in "${pallets[@]}"; do + echo " [+] $pallet" + done + else + echo "$runtimeName pallet list not found in benchmarks-ci.sh" + exit 1 + fi + + for pallet in "${pallets[@]}"; do + # (by default) do not choose output_file, like `pallet_assets.rs` because it does not work for multiple instances + # `benchmark pallet` command will decide the output_file name if there are multiple instances + local output_file="" + local extra_args="" + # a little hack for pallet_xcm_benchmarks - we want to force custom implementation for XcmWeightInfo + if [[ "$pallet" == "pallet_xcm_benchmarks::generic" ]] || [[ "$pallet" == "pallet_xcm_benchmarks::fungible" ]]; then + output_file="xcm/${pallet//::/_}.rs" + extra_args="--template=$output_path/templates/xcm-bench-template.hbs" + fi + $POLKADOT_PARACHAIN benchmark pallet \ + $extra_args \ + --chain="${benchmarkRuntimeChain}" \ + --wasm-execution=compiled \ + --pallet="$pallet" \ + --no-storage-info \ + --no-median-slopes \ + --no-min-squares \ + --extrinsic='*' \ + --steps=50 \ + --repeat=20 \ + --json \ + --header="$output_path/file_header.txt" \ + --output="${benchmarkOutput}/${output_file}" >> "$benchmarkMetadataOutputDir/${pallet//::/_}_benchmark.json" + done +} + + +echo "[+] Compiling benchmarks..." +cargo build --profile $profile --locked --features=runtime-benchmarks -p polkadot-parachain-bin + +# Run benchmarks for all pallets of a given runtime if runtime argument provided +get_arg optional --runtime "$@" +runtime="${out:-""}" + +if [[ $runtime ]]; then + paraId="" + case "$runtime" in + asset-*) + category="assets" + ;; + collectives-*) + category="collectives" + ;; + coretime-*) + category="coretime" + ;; + bridge-*) + category="bridge-hubs" + ;; + contracts-*) + category="contracts" + ;; + people-*) + category="people" + ;; + glutton-*) + category="glutton" + paraId="1300" + ;; + *) + echo "Unknown runtime: $runtime" + exit 1 + ;; + esac + + run_cumulus_bench $category $runtime $paraId + +else # run all + # Assets + run_cumulus_bench assets asset-hub-rococo + run_cumulus_bench assets asset-hub-westend + + # Collectives + run_cumulus_bench collectives collectives-westend + + # Coretime + run_cumulus_bench coretime coretime-rococo + run_cumulus_bench coretime coretime-westend + + # People + run_cumulus_bench people people-rococo + run_cumulus_bench people people-westend + + # Bridge Hubs + run_cumulus_bench bridge-hubs bridge-hub-rococo + run_cumulus_bench bridge-hubs bridge-hub-westend + + # Glutton + run_cumulus_bench glutton glutton-westend 1300 +fi diff --git a/scripts/lib/bench-all-pallet.sh b/scripts/lib/bench-all-pallet.sh new file mode 100644 index 0000000000000000000000000000000000000000..e6908045ddbd7f34ba7cad0e4c102e4606dff7aa --- /dev/null +++ b/scripts/lib/bench-all-pallet.sh @@ -0,0 +1,96 @@ +#!/usr/bin/env bash + +set -eu -o pipefail +shopt -s inherit_errexit +shopt -s globstar + +. "$(dirname "${BASH_SOURCE[0]}")/../command-utils.sh" + +get_arg required --pallet "$@" +PALLET="${out:-""}" + +REPO_NAME="$(basename "$PWD")" +BASE_COMMAND="$(dirname "${BASH_SOURCE[0]}")/../../bench/bench.sh --noexit=true --subcommand=pallet" + +WEIGHT_FILE_PATHS=( $(find . -type f -name "${PALLET}.rs" -path "**/weights/*" | sed 's|^\./||g') ) + +# convert pallet_ranked_collective to ranked-collective +CLEAN_PALLET=$(echo $PALLET | sed 's/pallet_//g' | sed 's/_/-/g') + +# add substrate pallet weights to a list +SUBSTRATE_PALLET_PATH=$(ls substrate/frame/$CLEAN_PALLET/src/weights.rs || :) +if [ ! -z "${SUBSTRATE_PALLET_PATH}" ]; then + WEIGHT_FILE_PATHS+=("$SUBSTRATE_PALLET_PATH") +fi + +# add trappist pallet weights to a list +TRAPPIST_PALLET_PATH=$(ls pallet/$CLEAN_PALLET/src/weights.rs || :) +if [ ! -z "${TRAPPIST_PALLET_PATH}" ]; then + WEIGHT_FILE_PATHS+=("$TRAPPIST_PALLET_PATH") +fi + +COMMANDS=() + +if [ "${#WEIGHT_FILE_PATHS[@]}" -eq 0 ]; then + echo "No weights files found for pallet: $PALLET" + exit 1 +else + echo "Found weights files for pallet: $PALLET" +fi + +for f in ${WEIGHT_FILE_PATHS[@]}; do + echo "- $f" + # f examples: + # cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/pallet_balances.rs + # polkadot/runtime/rococo/src/weights/pallet_balances.rs + # runtime/trappist/src/weights/pallet_assets.rs + TARGET_DIR=$(echo $f | cut -d'/' -f 1) + + if [ "$REPO_NAME" == "polkadot-sdk" ]; then + case $TARGET_DIR in + cumulus) + TYPE=$(echo $f | cut -d'/' -f 2) + # Example: cumulus/parachains/runtimes/assets/asset-hub-rococo/src/weights/pallet_balances.rs + if [ "$TYPE" == "parachains" ]; then + RUNTIME=$(echo $f | cut -d'/' -f 5) + RUNTIME_DIR=$(echo $f | cut -d'/' -f 4) + COMMANDS+=("$BASE_COMMAND --runtime=$RUNTIME --runtime_dir=$RUNTIME_DIR --target_dir=$TARGET_DIR --pallet=$PALLET") + fi + ;; + polkadot) + # Example: polkadot/runtime/rococo/src/weights/pallet_balances.rs + RUNTIME=$(echo $f | cut -d'/' -f 3) + COMMANDS+=("$BASE_COMMAND --runtime=$RUNTIME --target_dir=$TARGET_DIR --pallet=$PALLET") + ;; + substrate) + # Example: substrate/frame/contracts/src/weights.rs + COMMANDS+=("$BASE_COMMAND --target_dir=$TARGET_DIR --runtime=dev --pallet=$PALLET") + ;; + *) + echo "Unknown dir: $TARGET_DIR" + exit 1 + ;; + esac + fi + + if [ "$REPO_NAME" == "trappist" ]; then + case $TARGET_DIR in + runtime) + TYPE=$(echo $f | cut -d'/' -f 2) + if [ "$TYPE" == "trappist" || "$TYPE" == "stout" ]; then + # Example: runtime/trappist/src/weights/pallet_assets.rs + COMMANDS+=("$BASE_COMMAND --target_dir=trappist --runtime=$TYPE --pallet=$PALLET") + fi + ;; + *) + echo "Unknown dir: $TARGET_DIR" + exit 1 + ;; + esac + fi +done + +for cmd in "${COMMANDS[@]}"; do + echo "Running command: $cmd" + . $cmd +done diff --git a/scripts/lib/bench-all-polkadot.sh b/scripts/lib/bench-all-polkadot.sh new file mode 100644 index 0000000000000000000000000000000000000000..ac52e00140e38de76fe082aa3fd0aaf670b465bb --- /dev/null +++ b/scripts/lib/bench-all-polkadot.sh @@ -0,0 +1,88 @@ +#!/bin/bash + +# Runs all benchmarks for all pallets, for a given runtime, provided by $1 +# Should be run on a reference machine to gain accurate benchmarks +# current reference machine: https://github.com/paritytech/polkadot/pull/6508/files +# original source: https://github.com/paritytech/polkadot/blob/b9842c4b52f6791fef6c11ecd020b22fe614f041/scripts/run_all_benches.sh + +get_arg required --runtime "$@" +runtime="${out:-""}" + +# default RUST_LOG is error, but could be overridden +export RUST_LOG="${RUST_LOG:-error}" + +echo "[+] Compiling benchmarks..." +cargo build --profile $profile --locked --features=runtime-benchmarks -p polkadot + +POLKADOT_BIN="./target/$profile/polkadot" + +# Update the block and extrinsic overhead weights. +echo "[+] Benchmarking block and extrinsic overheads..." +OUTPUT=$( + $POLKADOT_BIN benchmark overhead \ + --chain="${runtime}-dev" \ + --wasm-execution=compiled \ + --weight-path="$output_path/runtime/${runtime}/constants/src/weights/" \ + --warmup=10 \ + --repeat=100 \ + --header="$output_path/file_header.txt" +) +if [ $? -ne 0 ]; then + echo "$OUTPUT" >> "$ERR_FILE" + echo "[-] Failed to benchmark the block and extrinsic overheads. Error written to $ERR_FILE; continuing..." +fi + + +# Load all pallet names in an array. +PALLETS=($( + $POLKADOT_BIN benchmark pallet --list --chain="${runtime}-dev" |\ + tail -n+2 |\ + cut -d',' -f1 |\ + sort |\ + uniq +)) + +echo "[+] Benchmarking ${#PALLETS[@]} pallets for runtime $runtime" + +# Define the error file. +ERR_FILE="${ARTIFACTS_DIR}/benchmarking_errors.txt" +# Delete the error file before each run. +rm -f $ERR_FILE + +# Benchmark each pallet. +for PALLET in "${PALLETS[@]}"; do + echo "[+] Benchmarking $PALLET for $runtime"; + + output_file="" + if [[ $PALLET == *"::"* ]]; then + # translates e.g. "pallet_foo::bar" to "pallet_foo_bar" + output_file="${PALLET//::/_}.rs" + fi + + OUTPUT=$( + $POLKADOT_BIN benchmark pallet \ + --chain="${runtime}-dev" \ + --steps=50 \ + --repeat=20 \ + --no-storage-info \ + --no-median-slopes \ + --no-min-squares \ + --pallet="$PALLET" \ + --extrinsic="*" \ + --execution=wasm \ + --wasm-execution=compiled \ + --header="$output_path/file_header.txt" \ + --output="$output_path/runtime/${runtime}/src/weights/${output_file}" 2>&1 + ) + if [ $? -ne 0 ]; then + echo "$OUTPUT" >> "$ERR_FILE" + echo "[-] Failed to benchmark $PALLET. Error written to $ERR_FILE; continuing..." + fi +done + +# Check if the error file exists. +if [ -f "$ERR_FILE" ]; then + echo "[-] Some benchmarks failed. See: $ERR_FILE" +else + echo "[+] All benchmarks passed." +fi diff --git a/scripts/lib/bench-all-substrate.sh b/scripts/lib/bench-all-substrate.sh new file mode 100644 index 0000000000000000000000000000000000000000..eeb18cdd8bbb31ee58daa93b35e45cf2a1f33e86 --- /dev/null +++ b/scripts/lib/bench-all-substrate.sh @@ -0,0 +1,148 @@ +#!/usr/bin/env bash + +# This file is part of Substrate. +# Copyright (C) 2022 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 script has three parts which all use the Substrate runtime: +# - Pallet benchmarking to update the pallet weights +# - Overhead benchmarking for the Extrinsic and Block weights +# - Machine benchmarking +# +# Should be run on a reference machine to gain accurate benchmarks +# current reference machine: https://github.com/paritytech/substrate/pull/5848 + +# Original source: https://github.com/paritytech/substrate/blob/ff9921a260a67e3a71f25c8b402cd5c7da787a96/scripts/run_all_benchmarks.sh +# Fail if any sub-command in a pipe fails, not just the last one. +set -o pipefail +# Fail on undeclared variables. +set -u +# Fail if any sub-command fails. +set -e +# Fail on traps. +# set -E + +# default RUST_LOG is warn, but could be overridden +export RUST_LOG="${RUST_LOG:-error}" + +echo "[+] Compiling Substrate benchmarks..." +cargo build --profile=$profile --locked --features=runtime-benchmarks -p staging-node-cli + +# The executable to use. +SUBSTRATE="./target/$profile/substrate-node" + +# Manually exclude some pallets. +EXCLUDED_PALLETS=( + # Helper pallets + "pallet_election_provider_support_benchmarking" + # Pallets without automatic benchmarking + "pallet_babe" + "pallet_grandpa" + "pallet_mmr" + "pallet_offences" + # Only used for testing, does not need real weights. + "frame_benchmarking_pallet_pov" + "pallet_example_tasks" + "pallet_example_basic" + "pallet_example_split" + "pallet_example_kitchensink" + "pallet_example_mbm" + "tasks_example" +) + +# Load all pallet names in an array. +ALL_PALLETS=($( + $SUBSTRATE benchmark pallet --list --chain=dev |\ + tail -n+2 |\ + cut -d',' -f1 |\ + sort |\ + uniq +)) + +# Define the error file. +ERR_FILE="${ARTIFACTS_DIR}/benchmarking_errors.txt" + +# Delete the error file before each run. +rm -f "$ERR_FILE" + +mkdir -p "$(dirname "$ERR_FILE")" + +# Update the block and extrinsic overhead weights. +echo "[+] Benchmarking block and extrinsic overheads..." +OUTPUT=$( + $SUBSTRATE benchmark overhead \ + --chain=dev \ + --wasm-execution=compiled \ + --weight-path="$output_path/frame/support/src/weights/" \ + --header="$output_path/HEADER-APACHE2" \ + --warmup=10 \ + --repeat=100 2>&1 +) +if [ $? -ne 0 ]; then + echo "$OUTPUT" >> "$ERR_FILE" + echo "[-] Failed to benchmark the block and extrinsic overheads. Error written to $ERR_FILE; continuing..." +fi + +echo "[+] Benchmarking ${#ALL_PALLETS[@]} Substrate pallets and excluding ${#EXCLUDED_PALLETS[@]}." + +echo "[+] Excluded pallets ${EXCLUDED_PALLETS[@]}" +echo "[+] ------ " +echo "[+] Whole list pallets ${ALL_PALLETS[@]}" + +# Benchmark each pallet. +for PALLET in "${ALL_PALLETS[@]}"; do + FOLDER="$(echo "${PALLET#*_}" | tr '_' '-')"; + WEIGHT_FILE="$output_path/frame/${FOLDER}/src/weights.rs" + + # Skip the pallet if it is in the excluded list. + + if [[ " ${EXCLUDED_PALLETS[@]} " =~ " ${PALLET} " ]]; then + echo "[+] Skipping $PALLET as it is in the excluded list." + continue + fi + + echo "[+] Benchmarking $PALLET with weight file $WEIGHT_FILE"; + + set +e # Disable exit on error for the benchmarking of the pallets + OUTPUT=$( + $SUBSTRATE benchmark pallet \ + --chain=dev \ + --steps=50 \ + --repeat=20 \ + --pallet="$PALLET" \ + --no-storage-info \ + --no-median-slopes \ + --no-min-squares \ + --extrinsic="*" \ + --wasm-execution=compiled \ + --heap-pages=4096 \ + --output="$WEIGHT_FILE" \ + --header="$output_path/HEADER-APACHE2" \ + --template="$output_path/.maintain/frame-weight-template.hbs" 2>&1 + ) + if [ $? -ne 0 ]; then + echo -e "$PALLET: $OUTPUT\n" >> "$ERR_FILE" + echo "[-] Failed to benchmark $PALLET. Error written to $ERR_FILE; continuing..." + fi + set -e # Re-enable exit on error +done + + +# Check if the error file exists. +if [ -s "$ERR_FILE" ]; then + echo "[-] Some benchmarks failed. See: $ERR_FILE" + exit 1 +else + echo "[+] All benchmarks passed." +fi diff --git a/scripts/lib/bench-overhead.sh b/scripts/lib/bench-overhead.sh new file mode 100644 index 0000000000000000000000000000000000000000..c4cca8b4c128ca201adebb1e353ac11ad30b0825 --- /dev/null +++ b/scripts/lib/bench-overhead.sh @@ -0,0 +1,66 @@ +#!/bin/bash + +THIS_DIR=$(dirname "${BASH_SOURCE[0]}") +. "$THIS_DIR/../command-utils.sh" + +bench_overhead_common_args=( + -- + benchmark + overhead + --wasm-execution=compiled + --warmup=10 + --repeat=100 +) +bench_overhead() { + local args + case "$target_dir" in + substrate) + args=( + --bin=substrate + "${bench_overhead_common_args[@]}" + --header="$output_path/HEADER-APACHE2" + --weight-path="$output_path/frame/support/src/weights" + --chain="dev" + ) + ;; + polkadot) + get_arg required --runtime "$@" + local runtime="${out:-""}" + args=( + --bin=polkadot + "${bench_overhead_common_args[@]}" + --header="$output_path/file_header.txt" + --weight-path="$output_path/runtime/$runtime/constants/src/weights" + --chain="$runtime-dev" + ) + ;; + cumulus) + get_arg required --runtime "$@" + local runtime="${out:-""}" + args=( + -p=polkadot-parachain-bin + "${bench_overhead_common_args[@]}" + --header="$output_path/file_header.txt" + --weight-path="$output_path/parachains/runtimes/assets/$runtime/src/weights" + --chain="$runtime" + ) + ;; + trappist) + get_arg required --runtime "$@" + local runtime="${out:-""}" + args=( + "${bench_overhead_common_args[@]}" + --header="$output_path/templates/file_header.txt" + --weight-path="$output_path/runtime/$runtime/src/weights" + --chain="$runtime-dev" + ) + ;; + *) + die "Target Dir \"$target_dir\" is not supported in bench_overhead" + ;; + esac + + cargo_run "${args[@]}" +} + +bench_overhead "$@" diff --git a/scripts/lib/bench-pallet.sh b/scripts/lib/bench-pallet.sh new file mode 100644 index 0000000000000000000000000000000000000000..15eac31e3a45cbb3c4f7c2dde3a1006164259f3a --- /dev/null +++ b/scripts/lib/bench-pallet.sh @@ -0,0 +1,178 @@ +#!/bin/bash + +THIS_DIR=$(dirname "${BASH_SOURCE[0]}") +. "$THIS_DIR/../command-utils.sh" + +bench_pallet_common_args=( + -- + benchmark + pallet + --steps=50 + --repeat=20 + --extrinsic="*" + --wasm-execution=compiled + --heap-pages=4096 + --json-file="${ARTIFACTS_DIR}/bench.json" +) +bench_pallet() { + get_arg required --subcommand "$@" + local subcommand="${out:-""}" + + get_arg required --runtime "$@" + local runtime="${out:-""}" + + get_arg required --pallet "$@" + local pallet="${out:-""}" + + local args + case "$target_dir" in + substrate) + args=( + --features=runtime-benchmarks + --manifest-path="$output_path/bin/node/cli/Cargo.toml" + "${bench_pallet_common_args[@]}" + --pallet="$pallet" + --chain="$runtime" + ) + + case "$subcommand" in + pallet) + # Translates e.g. "pallet_foo::bar" to "pallet_foo_bar" + local output_dir="${pallet//::/_}" + + # Substrate benchmarks are output to the "frame" directory but they aren't + # named exactly after the $pallet argument. For example: + # - When $pallet == pallet_balances, the output folder is frame/balances + # - When $pallet == frame_benchmarking, the output folder is frame/benchmarking + # The common pattern we infer from those examples is that we should remove + # the prefix + if [[ "$output_dir" =~ ^[A-Za-z]*[^A-Za-z](.*)$ ]]; then + output_dir="${BASH_REMATCH[1]}" + fi + + # We also need to translate '_' to '-' due to the folders' naming + # conventions + output_dir="${output_dir//_/-}" + + args+=( + --header="$output_path/HEADER-APACHE2" + --output="$output_path/frame/$output_dir/src/weights.rs" + --template="$output_path/.maintain/frame-weight-template.hbs" + ) + ;; + *) + die "Subcommand $subcommand is not supported for $target_dir in bench_pallet" + ;; + esac + ;; + polkadot) + # For backward compatibility: replace "-dev" with "" + runtime=${runtime/-dev/} + + local weights_dir="$output_path/runtime/${runtime}/src/weights" + + args=( + --bin=polkadot + --features=runtime-benchmarks + "${bench_pallet_common_args[@]}" + --pallet="$pallet" + --chain="${runtime}-dev" + ) + + case "$subcommand" in + pallet) + args+=( + --header="$output_path/file_header.txt" + --output="${weights_dir}/" + ) + ;; + xcm) + args+=( + --header="$output_path/file_header.txt" + --template="$output_path/xcm/pallet-xcm-benchmarks/template.hbs" + --output="${weights_dir}/xcm/" + ) + ;; + *) + die "Subcommand $subcommand is not supported for $target_dir in bench_pallet" + ;; + esac + ;; + cumulus) + get_arg required --runtime_dir "$@" + local runtime_dir="${out:-""}" + local chain="$runtime" + + # to support specifying parachain id from runtime name (e.g. ["glutton-westend", "glutton-westend-dev-1300"]) + # If runtime ends with "-dev" or "-dev-\d+", leave as it is, otherwise concat "-dev" at the end of $chain + if [[ ! "$runtime" =~ -dev(-[0-9]+)?$ ]]; then + chain="${runtime}-dev" + fi + + # replace "-dev" or "-dev-\d+" with "" for runtime + runtime=$(echo "$runtime" | sed 's/-dev.*//g') + + args=( + -p=polkadot-parachain-bin + --features=runtime-benchmarks + "${bench_pallet_common_args[@]}" + --pallet="$pallet" + --chain="${chain}" + --header="$output_path/file_header.txt" + ) + + case "$subcommand" in + pallet) + args+=( + --output="$output_path/parachains/runtimes/$runtime_dir/$runtime/src/weights/" + ) + ;; + xcm) + mkdir -p "$output_path/parachains/runtimes/$runtime_dir/$runtime/src/weights/xcm" + args+=( + --template="$output_path/templates/xcm-bench-template.hbs" + --output="$output_path/parachains/runtimes/$runtime_dir/$runtime/src/weights/xcm/" + ) + ;; + *) + die "Subcommand $subcommand is not supported for $target_dir in bench_pallet" + ;; + esac + ;; + trappist) + local weights_dir="$output_path/runtime/$runtime/src/weights" + + args=( + --features=runtime-benchmarks + "${bench_pallet_common_args[@]}" + --pallet="$pallet" + --chain="${runtime}-dev" + --header="$output_path/templates/file_header.txt" + ) + + case "$subcommand" in + pallet) + args+=( + --output="${weights_dir}/" + ) + ;; + xcm) + args+=( + --template="$output_path/templates/xcm-bench-template.hbs" + --output="${weights_dir}/xcm/" + ) + ;; + *) + die "Subcommand $subcommand is not supported for $target_dir in bench_pallet" + ;; + esac + ;; + *) + die "Repository $target_dir is not supported in bench_pallet" + ;; + esac + + cargo_run "${args[@]}" +} + +bench_pallet "$@" diff --git a/scripts/sync.sh b/scripts/sync.sh new file mode 100755 index 0000000000000000000000000000000000000000..b5d8a521993717d23469ddce4e1399bdd265220f --- /dev/null +++ b/scripts/sync.sh @@ -0,0 +1,74 @@ +#!/usr/bin/env bash + +set -eu -o pipefail + +. "$(realpath "$(dirname "${BASH_SOURCE[0]}")/command-utils.sh")" + + +# Function to check syncing status +check_syncing() { + # Send the system_health request and parse the isSyncing field + RESPONSE=$(curl -sSX POST http://127.0.0.1:9944 \ + --header 'Content-Type: application/json' \ + --data-raw '{"jsonrpc": "2.0", "method": "system_health", "params": [], "id": "1"}') + + # Check for errors in the curl command + if [ $? -ne 0 ]; then + echo "Error: Unable to send request to Polkadot node" + fi + + IS_SYNCING=$(echo $RESPONSE | jq -r '.result.isSyncing') + + # Check for errors in the jq command or missing field in the response + if [ $? -ne 0 ] || [ "$IS_SYNCING" == "null" ]; then + echo "Error: Unable to parse sync status from response" + fi + + # Return the isSyncing value + echo $IS_SYNCING +} + +main() { + get_arg required --chain "$@" + local chain="${out:-""}" + + get_arg required --type "$@" + local type="${out:-""}" + + export RUST_LOG="${RUST_LOG:-remote-ext=debug,runtime=trace}" + + cargo build --release + + cp "./target/release/polkadot" ./polkadot-bin + + # Start sync. + # "&" runs the process in the background + # "> /dev/tty" redirects the output of the process to the terminal + ./polkadot-bin --sync="$type" --chain="$chain" > "$ARTIFACTS_DIR/sync.log" 2>&1 & + + # Get the PID of process + POLKADOT_SYNC_PID=$! + + sleep 10 + + # Poll the node every 100 seconds until syncing is complete + while :; do + SYNC_STATUS="$(check_syncing)" + if [ "$SYNC_STATUS" == "true" ]; then + echo "Node is still syncing..." + sleep 100 + elif [ "$SYNC_STATUS" == "false" ]; then + echo "Node sync is complete!" + kill "$POLKADOT_SYNC_PID" # Stop the Polkadot node process once syncing is complete + exit 0 # Success + elif [[ "$SYNC_STATUS" = Error:* ]]; then + echo "$SYNC_STATUS" + exit 1 # Error + else + echo "Unknown error: $SYNC_STATUS" + exit 1 # Unknown error + fi + done +} + +main "$@" diff --git a/substrate/bin/node/bench/Cargo.toml b/substrate/bin/node/bench/Cargo.toml index b756f3504655bf44f0b5e51699026dcd82afaca3..6b061955184ea3ef982352011733616a9bb0520a 100644 --- a/substrate/bin/node/bench/Cargo.toml +++ b/substrate/bin/node/bench/Cargo.toml @@ -15,33 +15,33 @@ workspace = true # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -array-bytes = "6.2.2" -clap = { version = "4.5.3", features = ["derive"] } +array-bytes = { workspace = true, default-features = true } +clap = { features = ["derive"], workspace = true } log = { workspace = true, default-features = true } -node-primitives = { path = "../primitives" } -node-testing = { path = "../testing" } -kitchensink-runtime = { path = "../runtime" } -sc-client-api = { path = "../../../client/api" } -sp-runtime = { path = "../../../primitives/runtime" } -sp-state-machine = { path = "../../../primitives/state-machine" } +node-primitives = { workspace = true, default-features = true } +node-testing = { workspace = true } +kitchensink-runtime = { workspace = true } +sc-client-api = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-state-machine = { workspace = true, default-features = true } serde = { workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } -derive_more = { version = "0.99.17", default-features = false, features = ["display"] } -kvdb = "0.13.0" -kvdb-rocksdb = "0.19.0" -sp-trie = { path = "../../../primitives/trie" } -sp-core = { path = "../../../primitives/core" } -sp-consensus = { path = "../../../primitives/consensus/common" } -sc-basic-authorship = { path = "../../../client/basic-authorship" } -sp-inherents = { path = "../../../primitives/inherents" } -sp-timestamp = { path = "../../../primitives/timestamp", default-features = false } -sp-tracing = { path = "../../../primitives/tracing" } -hash-db = "0.16.0" -tempfile = "3.1.0" -fs_extra = "1" -rand = { version = "0.8.5", features = ["small_rng"] } -lazy_static = "1.4.0" -parity-db = "0.4.12" -sc-transaction-pool = { path = "../../../client/transaction-pool" } -sc-transaction-pool-api = { path = "../../../client/transaction-pool/api" } -futures = { version = "0.3.30", features = ["thread-pool"] } +derive_more = { features = ["display"], workspace = true } +kvdb = { workspace = true } +kvdb-rocksdb = { workspace = true } +sp-trie = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sc-basic-authorship = { workspace = true, default-features = true } +sp-inherents = { workspace = true, default-features = true } +sp-timestamp = { workspace = true } +sp-tracing = { workspace = true, default-features = true } +hash-db = { workspace = true, default-features = true } +tempfile = { workspace = true } +fs_extra = { workspace = true } +rand = { features = ["small_rng"], workspace = true, default-features = true } +lazy_static = { workspace = true } +parity-db = { workspace = true } +sc-transaction-pool = { workspace = true, default-features = true } +sc-transaction-pool-api = { workspace = true, default-features = true } +futures = { features = ["thread-pool"], workspace = true } diff --git a/substrate/bin/node/bench/src/import.rs b/substrate/bin/node/bench/src/import.rs index 78b280076e0bd625f2c6fa76beb76a9439a7187a..e340869dea0281092b41c94d107e65e4831c7e95 100644 --- a/substrate/bin/node/bench/src/import.rs +++ b/substrate/bin/node/bench/src/import.rs @@ -122,7 +122,8 @@ impl core::Benchmark for ImportBenchmark { match self.block_type { BlockType::RandomTransfersKeepAlive => { // should be 8 per signed extrinsic + 1 per unsigned - // we have 1 unsigned and the rest are signed in the block + // we have 2 unsigned (timestamp and glutton bloat) while the rest are + // signed in the block. // those 8 events per signed are: // - transaction paid for the transaction payment // - withdraw (Balances::Withdraw) for charging the transaction fee @@ -135,18 +136,18 @@ impl core::Benchmark for ImportBenchmark { // - extrinsic success assert_eq!( kitchensink_runtime::System::events().len(), - (self.block.extrinsics.len() - 1) * 8 + 1, + (self.block.extrinsics.len() - 2) * 8 + 2, ); }, BlockType::Noop => { assert_eq!( kitchensink_runtime::System::events().len(), // should be 2 per signed extrinsic + 1 per unsigned - // we have 1 unsigned and the rest are signed in the block + // we have 2 unsigned and the rest are signed in the block // those 2 events per signed are: // - deposit event for charging transaction fee // - extrinsic success - (self.block.extrinsics.len() - 1) * 2 + 1, + (self.block.extrinsics.len() - 2) * 2 + 2, ); }, _ => {}, diff --git a/substrate/bin/node/cli/Cargo.toml b/substrate/bin/node/cli/Cargo.toml index 929cd6a29e3889dbd93d6e31277406cf61176114..ab665f0792a46814343bb39f7497ae925bbe8e68 100644 --- a/substrate/bin/node/cli/Cargo.toml +++ b/substrate/bin/node/cli/Cargo.toml @@ -37,53 +37,53 @@ crate-type = ["cdylib", "rlib"] [dependencies] # third-party dependencies -array-bytes = "6.1" -clap = { version = "4.5.3", features = ["derive"], optional = true } -codec = { package = "parity-scale-codec", version = "3.6.12" } +array-bytes = { workspace = true, default-features = true } +clap = { features = ["derive"], optional = true, workspace = true } +codec = { workspace = true, default-features = true } serde = { features = ["derive"], workspace = true, default-features = true } -jsonrpsee = { version = "0.22", features = ["server"] } -futures = "0.3.30" +jsonrpsee = { features = ["server"], workspace = true } +futures = { workspace = true } log = { workspace = true, default-features = true } -rand = "0.8" +rand = { workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } # The Polkadot-SDK: -polkadot-sdk = { path = "../../../../umbrella", features = ["node"] } +polkadot-sdk = { features = ["node"], workspace = true, default-features = true } # Shared code between the staging node and kitchensink runtime: -kitchensink-runtime = { path = "../runtime" } -node-rpc = { path = "../rpc" } -node-primitives = { path = "../primitives" } -node-inspect = { package = "staging-node-inspect", path = "../inspect", optional = true } +kitchensink-runtime = { workspace = true } +node-rpc = { workspace = true } +node-primitives = { workspace = true, default-features = true } +node-inspect = { optional = true, workspace = true, default-features = true } [dev-dependencies] -futures = "0.3.30" -tempfile = "3.1.0" -assert_cmd = "2.0.2" -nix = { version = "0.28.0", features = ["signal"] } -regex = "1.6.0" -platforms = "3.0" -soketto = "0.7.1" -criterion = { version = "0.5.1", features = ["async_tokio"] } -tokio = { version = "1.22.0", features = ["macros", "parking_lot", "time"] } -tokio-util = { version = "0.7.4", features = ["compat"] } -wait-timeout = "0.2" -wat = "1.0" +futures = { workspace = true } +tempfile = { workspace = true } +assert_cmd = { workspace = true } +nix = { features = ["signal"], workspace = true } +regex = { workspace = true } +platforms = { workspace = true } +soketto = { workspace = true } +criterion = { features = ["async_tokio"], workspace = true, default-features = true } +tokio = { features = ["macros", "parking_lot", "time"], workspace = true, default-features = true } +tokio-util = { features = ["compat"], workspace = true } +wait-timeout = { workspace = true } +wat = { workspace = true } serde_json = { workspace = true, default-features = true } -scale-info = { version = "2.11.1", features = ["derive", "serde"] } +scale-info = { features = ["derive", "serde"], workspace = true, default-features = true } # These testing-only dependencies are not exported by the Polkadot-SDK crate: -node-testing = { path = "../testing" } -substrate-cli-test-utils = { path = "../../../test-utils/cli" } -sc-service-test = { path = "../../../client/service/test" } +node-testing = { workspace = true } +substrate-cli-test-utils = { workspace = true } +sc-service-test = { workspace = true } [build-dependencies] -clap = { version = "4.5.3", optional = true } -clap_complete = { version = "4.0.2", optional = true } +clap = { optional = true, workspace = true } +clap_complete = { optional = true, workspace = true } -node-inspect = { package = "staging-node-inspect", path = "../inspect", optional = true } +node-inspect = { optional = true, workspace = true, default-features = true } -polkadot-sdk = { path = "../../../../umbrella", features = ["frame-benchmarking-cli", "sc-cli", "sc-storage-monitor", "substrate-build-script-utils"], optional = true } +polkadot-sdk = { features = ["frame-benchmarking-cli", "sc-cli", "sc-storage-monitor", "substrate-build-script-utils"], optional = true, workspace = true, default-features = true } [features] default = ["cli"] diff --git a/substrate/bin/node/cli/tests/res/default_genesis_config.json b/substrate/bin/node/cli/tests/res/default_genesis_config.json index e21fbb47da8c4619e0923c85bf3470828cd80b23..d8713764ab21d516851fddff04734f37e03c9bfe 100644 --- a/substrate/bin/node/cli/tests/res/default_genesis_config.json +++ b/substrate/bin/node/cli/tests/res/default_genesis_config.json @@ -74,6 +74,7 @@ "glutton": { "compute": "0", "storage": "0", + "blockLength": "0", "trashDataCount": 0 }, "assets": { diff --git a/substrate/bin/node/inspect/Cargo.toml b/substrate/bin/node/inspect/Cargo.toml index 5e4488903bf45fa32dd1f219bf9cf5766522e5bd..68769ffb4fa44794d98bfd56657d8cb7219f8a7c 100644 --- a/substrate/bin/node/inspect/Cargo.toml +++ b/substrate/bin/node/inspect/Cargo.toml @@ -15,17 +15,17 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -clap = { version = "4.5.3", features = ["derive"] } -codec = { package = "parity-scale-codec", version = "3.6.12" } +clap = { features = ["derive"], workspace = true } +codec = { workspace = true, default-features = true } thiserror = { workspace = true } -sc-cli = { path = "../../../client/cli" } -sc-client-api = { path = "../../../client/api" } -sc-service = { path = "../../../client/service", default-features = false } -sp-blockchain = { path = "../../../primitives/blockchain" } -sp-core = { path = "../../../primitives/core" } -sp-io = { path = "../../../primitives/io" } -sp-runtime = { path = "../../../primitives/runtime" } -sp-statement-store = { path = "../../../primitives/statement-store" } +sc-cli = { workspace = true } +sc-client-api = { workspace = true, default-features = true } +sc-service = { workspace = true } +sp-blockchain = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-statement-store = { workspace = true, default-features = true } [features] runtime-benchmarks = [ diff --git a/substrate/bin/node/primitives/Cargo.toml b/substrate/bin/node/primitives/Cargo.toml index 24279ad09c3d9f4576a212d7c67ac24be27b8e22..de295fd59d45a73fee8736259ed91038dd2d40aa 100644 --- a/substrate/bin/node/primitives/Cargo.toml +++ b/substrate/bin/node/primitives/Cargo.toml @@ -16,8 +16,8 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-core = { path = "../../../primitives/core", default-features = false } -sp-runtime = { path = "../../../primitives/runtime", default-features = false } +sp-core = { workspace = true } +sp-runtime = { workspace = true } [features] default = ["std"] diff --git a/substrate/bin/node/rpc/Cargo.toml b/substrate/bin/node/rpc/Cargo.toml index 6ae80eb578596490753d903d253c01af2660ef4f..fa1e96e67e98250a1c3da6b6298307f00cb85acb 100644 --- a/substrate/bin/node/rpc/Cargo.toml +++ b/substrate/bin/node/rpc/Cargo.toml @@ -16,33 +16,33 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -jsonrpsee = { version = "0.22", features = ["server"] } -node-primitives = { path = "../primitives" } -pallet-transaction-payment-rpc = { path = "../../../frame/transaction-payment/rpc" } -mmr-rpc = { path = "../../../client/merkle-mountain-range/rpc" } -sc-chain-spec = { path = "../../../client/chain-spec" } -sc-client-api = { path = "../../../client/api" } -sc-consensus-babe = { path = "../../../client/consensus/babe" } -sc-consensus-babe-rpc = { path = "../../../client/consensus/babe/rpc" } -sc-consensus-beefy = { path = "../../../client/consensus/beefy" } -sc-consensus-beefy-rpc = { path = "../../../client/consensus/beefy/rpc" } -sp-consensus-beefy = { path = "../../../primitives/consensus/beefy" } -sc-consensus-grandpa = { path = "../../../client/consensus/grandpa" } -sc-consensus-grandpa-rpc = { path = "../../../client/consensus/grandpa/rpc" } -sc-mixnet = { path = "../../../client/mixnet" } -sc-rpc = { path = "../../../client/rpc" } -sc-rpc-api = { path = "../../../client/rpc-api" } -sc-rpc-spec-v2 = { path = "../../../client/rpc-spec-v2" } -sc-sync-state-rpc = { path = "../../../client/sync-state-rpc" } -sc-transaction-pool-api = { path = "../../../client/transaction-pool/api" } -sp-api = { path = "../../../primitives/api" } -sp-block-builder = { path = "../../../primitives/block-builder" } -sp-blockchain = { path = "../../../primitives/blockchain" } -sp-consensus = { path = "../../../primitives/consensus/common" } -sp-consensus-babe = { path = "../../../primitives/consensus/babe" } -sp-keystore = { path = "../../../primitives/keystore" } -sp-runtime = { path = "../../../primitives/runtime" } -sp-application-crypto = { path = "../../../primitives/application-crypto" } -sp-statement-store = { path = "../../../primitives/statement-store" } -substrate-frame-rpc-system = { path = "../../../utils/frame/rpc/system" } -substrate-state-trie-migration-rpc = { path = "../../../utils/frame/rpc/state-trie-migration-rpc" } +jsonrpsee = { features = ["server"], workspace = true } +node-primitives = { workspace = true, default-features = true } +pallet-transaction-payment-rpc = { workspace = true, default-features = true } +mmr-rpc = { workspace = true, default-features = true } +sc-chain-spec = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-consensus-babe = { workspace = true, default-features = true } +sc-consensus-babe-rpc = { workspace = true, default-features = true } +sc-consensus-beefy = { workspace = true, default-features = true } +sc-consensus-beefy-rpc = { workspace = true, default-features = true } +sp-consensus-beefy = { workspace = true, default-features = true } +sc-consensus-grandpa = { workspace = true, default-features = true } +sc-consensus-grandpa-rpc = { workspace = true, default-features = true } +sc-mixnet = { workspace = true, default-features = true } +sc-rpc = { workspace = true, default-features = true } +sc-rpc-api = { workspace = true, default-features = true } +sc-rpc-spec-v2 = { workspace = true, default-features = true } +sc-sync-state-rpc = { workspace = true, default-features = true } +sc-transaction-pool-api = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-block-builder = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-consensus-babe = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-application-crypto = { workspace = true, default-features = true } +sp-statement-store = { workspace = true, default-features = true } +substrate-frame-rpc-system = { workspace = true, default-features = true } +substrate-state-trie-migration-rpc = { workspace = true, default-features = true } diff --git a/substrate/bin/node/runtime/Cargo.toml b/substrate/bin/node/runtime/Cargo.toml index e8cc7b3482b66ef8e850871670430b23f2923396..c1c470f1dcd6dfc7bf755d25609c68d6cb18fa03 100644 --- a/substrate/bin/node/runtime/Cargo.toml +++ b/substrate/bin/node/runtime/Cargo.toml @@ -19,29 +19,29 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] # third-party dependencies -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", "max-encoded-len", -] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive", "serde"] } -static_assertions = "1.1.0" +], workspace = true } +scale-info = { features = ["derive", "serde"], workspace = true } +static_assertions = { workspace = true, default-features = true } log = { workspace = true } serde_json = { features = ["alloc", "arbitrary_precision"], workspace = true } # pallet-asset-conversion: turn on "num-traits" feature -primitive-types = { version = "0.12.0", default-features = false, features = ["codec", "num-traits", "scale-info"] } +primitive-types = { features = ["codec", "num-traits", "scale-info"], workspace = true } -polkadot-sdk = { path = "../../../../umbrella", features = ["runtime", "tuples-96"], default-features = false } +polkadot-sdk = { features = ["runtime", "tuples-96"], workspace = true } # shared code between runtime and node -node-primitives = { path = "../primitives", default-features = false } +node-primitives = { workspace = true } # Example pallets that are not published: -pallet-example-mbm = { path = "../../../frame/examples/multi-block-migrations", default-features = false } -pallet-example-tasks = { path = "../../../frame/examples/tasks", default-features = false } +pallet-example-mbm = { workspace = true } +pallet-example-tasks = { workspace = true } [build-dependencies] -substrate-wasm-builder = { path = "../../../utils/wasm-builder", optional = true } +substrate-wasm-builder = { optional = true, workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/bin/node/runtime/src/lib.rs b/substrate/bin/node/runtime/src/lib.rs index 8fb59a9d8474c02bcc3cf0f43865528f236b7129..a3dc7decd1076f47f0d95609a95aab4ea1c6ee2c 100644 --- a/substrate/bin/node/runtime/src/lib.rs +++ b/substrate/bin/node/runtime/src/lib.rs @@ -49,7 +49,7 @@ use frame_support::{ AsEnsureOriginWithArg, ConstBool, ConstU128, ConstU16, ConstU32, Contains, Currency, EitherOfDiverse, EnsureOriginWithArg, EqualPrivilegeOnly, Imbalance, InsideBoth, InstanceFilter, KeyOwnerProofSystem, LinearStoragePrice, LockIdentifier, Nothing, - OnUnbalanced, WithdrawReasons, + OnUnbalanced, VariantCountOf, WithdrawReasons, }, weights::{ constants::{ @@ -542,7 +542,7 @@ impl pallet_balances::Config for Runtime { type AccountStore = frame_system::Pallet; type WeightInfo = pallet_balances::weights::SubstrateWeight; type FreezeIdentifier = RuntimeFreezeReason; - type MaxFreezes = ConstU32<1>; + type MaxFreezes = VariantCountOf; } parameter_types! { @@ -1038,6 +1038,7 @@ impl pallet_ranked_collective::Config for Runtime { type MinRankOfClass = traits::Identity; type VoteWeight = pallet_ranked_collective::Geometric; type MemberSwappedHandler = (CoreFellowship, Salary); + type MaxMemberCount = (); #[cfg(feature = "runtime-benchmarks")] type BenchmarkSetup = (CoreFellowship, Salary); } @@ -1212,8 +1213,6 @@ impl pallet_membership::Config for Runtime { } parameter_types! { - pub const ProposalBond: Permill = Permill::from_percent(5); - pub const ProposalBondMinimum: Balance = 1 * DOLLARS; pub const SpendPeriod: BlockNumber = 1 * DAYS; pub const Burn: Permill = Permill::from_percent(50); pub const TipCountdown: BlockNumber = 1 * DAYS; @@ -1230,19 +1229,11 @@ parameter_types! { impl pallet_treasury::Config for Runtime { type PalletId = TreasuryPalletId; type Currency = Balances; - type ApproveOrigin = EitherOfDiverse< - EnsureRoot, - pallet_collective::EnsureProportionAtLeast, - >; type RejectOrigin = EitherOfDiverse< EnsureRoot, pallet_collective::EnsureProportionMoreThan, >; type RuntimeEvent = RuntimeEvent; - type OnSlash = (); - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ProposalBondMinimum; - type ProposalBondMaximum = (); type SpendPeriod = SpendPeriod; type Burn = Burn; type BurnDestination = (); @@ -1296,6 +1287,7 @@ impl pallet_bounties::Config for Runtime { type MaximumReasonLength = MaximumReasonLength; type WeightInfo = pallet_bounties::weights::SubstrateWeight; type ChildBountyManager = ChildBounties; + type OnSlash = Treasury; } parameter_types! { @@ -1340,6 +1332,7 @@ impl pallet_tips::Config for Runtime { type TipReportDepositBase = TipReportDepositBase; type MaxTipAmount = ConstU128<{ 500 * DOLLARS }>; type WeightInfo = pallet_tips::weights::SubstrateWeight; + type OnSlash = Treasury; } parameter_types! { @@ -1874,6 +1867,7 @@ impl pallet_core_fellowship::Config for Runtime { type InductOrigin = pallet_core_fellowship::EnsureInducted; type ApproveOrigin = EnsureRootWithSuccess>; type PromoteOrigin = EnsureRootWithSuccess>; + type FastPromoteOrigin = Self::PromoteOrigin; type EvidenceSize = ConstU32<16_384>; type MaxRank = ConstU32<9>; } @@ -2248,248 +2242,248 @@ mod runtime { pub struct Runtime; #[runtime::pallet_index(0)] - pub type System = frame_system; + pub type System = frame_system::Pallet; #[runtime::pallet_index(1)] - pub type Utility = pallet_utility; + pub type Utility = pallet_utility::Pallet; #[runtime::pallet_index(2)] - pub type Babe = pallet_babe; + pub type Babe = pallet_babe::Pallet; #[runtime::pallet_index(3)] - pub type Timestamp = pallet_timestamp; + pub type Timestamp = pallet_timestamp::Pallet; // Authorship must be before session in order to note author in the correct session and era // for im-online and staking. #[runtime::pallet_index(4)] - pub type Authorship = pallet_authorship; + pub type Authorship = pallet_authorship::Pallet; #[runtime::pallet_index(5)] - pub type Indices = pallet_indices; + pub type Indices = pallet_indices::Pallet; #[runtime::pallet_index(6)] - pub type Balances = pallet_balances; + pub type Balances = pallet_balances::Pallet; #[runtime::pallet_index(7)] - pub type TransactionPayment = pallet_transaction_payment; + pub type TransactionPayment = pallet_transaction_payment::Pallet; #[runtime::pallet_index(8)] - pub type AssetTxPayment = pallet_asset_tx_payment; + pub type AssetTxPayment = pallet_asset_tx_payment::Pallet; #[runtime::pallet_index(9)] - pub type AssetConversionTxPayment = pallet_asset_conversion_tx_payment; + pub type AssetConversionTxPayment = pallet_asset_conversion_tx_payment::Pallet; #[runtime::pallet_index(10)] - pub type ElectionProviderMultiPhase = pallet_election_provider_multi_phase; + pub type ElectionProviderMultiPhase = pallet_election_provider_multi_phase::Pallet; #[runtime::pallet_index(11)] - pub type Staking = pallet_staking; + pub type Staking = pallet_staking::Pallet; #[runtime::pallet_index(12)] - pub type Session = pallet_session; + pub type Session = pallet_session::Pallet; #[runtime::pallet_index(13)] - pub type Democracy = pallet_democracy; + pub type Democracy = pallet_democracy::Pallet; #[runtime::pallet_index(14)] - pub type Council = pallet_collective; + pub type Council = pallet_collective::Pallet; #[runtime::pallet_index(15)] - pub type TechnicalCommittee = pallet_collective; + pub type TechnicalCommittee = pallet_collective::Pallet; #[runtime::pallet_index(16)] - pub type Elections = pallet_elections_phragmen; + pub type Elections = pallet_elections_phragmen::Pallet; #[runtime::pallet_index(17)] - pub type TechnicalMembership = pallet_membership; + pub type TechnicalMembership = pallet_membership::Pallet; #[runtime::pallet_index(18)] - pub type Grandpa = pallet_grandpa; + pub type Grandpa = pallet_grandpa::Pallet; #[runtime::pallet_index(19)] - pub type Treasury = pallet_treasury; + pub type Treasury = pallet_treasury::Pallet; #[runtime::pallet_index(20)] - pub type AssetRate = pallet_asset_rate; + pub type AssetRate = pallet_asset_rate::Pallet; #[runtime::pallet_index(21)] - pub type Contracts = pallet_contracts; + pub type Contracts = pallet_contracts::Pallet; #[runtime::pallet_index(22)] - pub type Sudo = pallet_sudo; + pub type Sudo = pallet_sudo::Pallet; #[runtime::pallet_index(23)] - pub type ImOnline = pallet_im_online; + pub type ImOnline = pallet_im_online::Pallet; #[runtime::pallet_index(24)] - pub type AuthorityDiscovery = pallet_authority_discovery; + pub type AuthorityDiscovery = pallet_authority_discovery::Pallet; #[runtime::pallet_index(25)] - pub type Offences = pallet_offences; + pub type Offences = pallet_offences::Pallet; #[runtime::pallet_index(26)] - pub type Historical = pallet_session_historical; + pub type Historical = pallet_session_historical::Pallet; #[runtime::pallet_index(27)] - pub type RandomnessCollectiveFlip = pallet_insecure_randomness_collective_flip; + pub type RandomnessCollectiveFlip = pallet_insecure_randomness_collective_flip::Pallet; #[runtime::pallet_index(28)] - pub type Identity = pallet_identity; + pub type Identity = pallet_identity::Pallet; #[runtime::pallet_index(29)] - pub type Society = pallet_society; + pub type Society = pallet_society::Pallet; #[runtime::pallet_index(30)] - pub type Recovery = pallet_recovery; + pub type Recovery = pallet_recovery::Pallet; #[runtime::pallet_index(31)] - pub type Vesting = pallet_vesting; + pub type Vesting = pallet_vesting::Pallet; #[runtime::pallet_index(32)] - pub type Scheduler = pallet_scheduler; + pub type Scheduler = pallet_scheduler::Pallet; #[runtime::pallet_index(33)] - pub type Glutton = pallet_glutton; + pub type Glutton = pallet_glutton::Pallet; #[runtime::pallet_index(34)] - pub type Preimage = pallet_preimage; + pub type Preimage = pallet_preimage::Pallet; #[runtime::pallet_index(35)] - pub type Proxy = pallet_proxy; + pub type Proxy = pallet_proxy::Pallet; #[runtime::pallet_index(36)] - pub type Multisig = pallet_multisig; + pub type Multisig = pallet_multisig::Pallet; #[runtime::pallet_index(37)] - pub type Bounties = pallet_bounties; + pub type Bounties = pallet_bounties::Pallet; #[runtime::pallet_index(38)] - pub type Tips = pallet_tips; + pub type Tips = pallet_tips::Pallet; #[runtime::pallet_index(39)] - pub type Assets = pallet_assets; + pub type Assets = pallet_assets::Pallet; #[runtime::pallet_index(40)] - pub type PoolAssets = pallet_assets; + pub type PoolAssets = pallet_assets::Pallet; #[runtime::pallet_index(41)] - pub type Beefy = pallet_beefy; + pub type Beefy = pallet_beefy::Pallet; // MMR leaf construction must be after session in order to have a leaf's next_auth_set // refer to block. See issue polkadot-fellows/runtimes#160 for details. #[runtime::pallet_index(42)] - pub type Mmr = pallet_mmr; + pub type Mmr = pallet_mmr::Pallet; #[runtime::pallet_index(43)] - pub type MmrLeaf = pallet_beefy_mmr; + pub type MmrLeaf = pallet_beefy_mmr::Pallet; #[runtime::pallet_index(44)] - pub type Lottery = pallet_lottery; + pub type Lottery = pallet_lottery::Pallet; #[runtime::pallet_index(45)] - pub type Nis = pallet_nis; + pub type Nis = pallet_nis::Pallet; #[runtime::pallet_index(46)] - pub type Uniques = pallet_uniques; + pub type Uniques = pallet_uniques::Pallet; #[runtime::pallet_index(47)] - pub type Nfts = pallet_nfts; + pub type Nfts = pallet_nfts::Pallet; #[runtime::pallet_index(48)] - pub type NftFractionalization = pallet_nft_fractionalization; + pub type NftFractionalization = pallet_nft_fractionalization::Pallet; #[runtime::pallet_index(49)] - pub type Salary = pallet_salary; + pub type Salary = pallet_salary::Pallet; #[runtime::pallet_index(50)] - pub type CoreFellowship = pallet_core_fellowship; + pub type CoreFellowship = pallet_core_fellowship::Pallet; #[runtime::pallet_index(51)] - pub type TransactionStorage = pallet_transaction_storage; + pub type TransactionStorage = pallet_transaction_storage::Pallet; #[runtime::pallet_index(52)] - pub type VoterList = pallet_bags_list; + pub type VoterList = pallet_bags_list::Pallet; #[runtime::pallet_index(53)] - pub type StateTrieMigration = pallet_state_trie_migration; + pub type StateTrieMigration = pallet_state_trie_migration::Pallet; #[runtime::pallet_index(54)] - pub type ChildBounties = pallet_child_bounties; + pub type ChildBounties = pallet_child_bounties::Pallet; #[runtime::pallet_index(55)] - pub type Referenda = pallet_referenda; + pub type Referenda = pallet_referenda::Pallet; #[runtime::pallet_index(56)] - pub type Remark = pallet_remark; + pub type Remark = pallet_remark::Pallet; #[runtime::pallet_index(57)] - pub type RootTesting = pallet_root_testing; + pub type RootTesting = pallet_root_testing::Pallet; #[runtime::pallet_index(58)] - pub type ConvictionVoting = pallet_conviction_voting; + pub type ConvictionVoting = pallet_conviction_voting::Pallet; #[runtime::pallet_index(59)] - pub type Whitelist = pallet_whitelist; + pub type Whitelist = pallet_whitelist::Pallet; #[runtime::pallet_index(60)] - pub type AllianceMotion = pallet_collective; + pub type AllianceMotion = pallet_collective::Pallet; #[runtime::pallet_index(61)] - pub type Alliance = pallet_alliance; + pub type Alliance = pallet_alliance::Pallet; #[runtime::pallet_index(62)] - pub type NominationPools = pallet_nomination_pools; + pub type NominationPools = pallet_nomination_pools::Pallet; #[runtime::pallet_index(63)] - pub type RankedPolls = pallet_referenda; + pub type RankedPolls = pallet_referenda::Pallet; #[runtime::pallet_index(64)] - pub type RankedCollective = pallet_ranked_collective; + pub type RankedCollective = pallet_ranked_collective::Pallet; #[runtime::pallet_index(65)] - pub type AssetConversion = pallet_asset_conversion; + pub type AssetConversion = pallet_asset_conversion::Pallet; #[runtime::pallet_index(66)] - pub type FastUnstake = pallet_fast_unstake; + pub type FastUnstake = pallet_fast_unstake::Pallet; #[runtime::pallet_index(67)] - pub type MessageQueue = pallet_message_queue; + pub type MessageQueue = pallet_message_queue::Pallet; #[runtime::pallet_index(68)] - pub type Pov = frame_benchmarking_pallet_pov; + pub type Pov = frame_benchmarking_pallet_pov::Pallet; #[runtime::pallet_index(69)] - pub type TxPause = pallet_tx_pause; + pub type TxPause = pallet_tx_pause::Pallet; #[runtime::pallet_index(70)] - pub type SafeMode = pallet_safe_mode; + pub type SafeMode = pallet_safe_mode::Pallet; #[runtime::pallet_index(71)] - pub type Statement = pallet_statement; + pub type Statement = pallet_statement::Pallet; #[runtime::pallet_index(72)] - pub type MultiBlockMigrations = pallet_migrations; + pub type MultiBlockMigrations = pallet_migrations::Pallet; #[runtime::pallet_index(73)] - pub type Broker = pallet_broker; + pub type Broker = pallet_broker::Pallet; #[runtime::pallet_index(74)] - pub type TasksExample = pallet_example_tasks; + pub type TasksExample = pallet_example_tasks::Pallet; #[runtime::pallet_index(75)] - pub type Mixnet = pallet_mixnet; + pub type Mixnet = pallet_mixnet::Pallet; #[runtime::pallet_index(76)] - pub type Parameters = pallet_parameters; + pub type Parameters = pallet_parameters::Pallet; #[runtime::pallet_index(77)] - pub type SkipFeelessPayment = pallet_skip_feeless_payment; + pub type SkipFeelessPayment = pallet_skip_feeless_payment::Pallet; #[runtime::pallet_index(78)] - pub type PalletExampleMbms = pallet_example_mbm; + pub type PalletExampleMbms = pallet_example_mbm::Pallet; #[runtime::pallet_index(79)] - pub type AssetConversionMigration = pallet_asset_conversion_ops; + pub type AssetConversionMigration = pallet_asset_conversion_ops::Pallet; } /// The address format for describing accounts. diff --git a/substrate/bin/node/testing/Cargo.toml b/substrate/bin/node/testing/Cargo.toml index 3ba3f07510e006458cf23b246e293af4e288c624..90c9ee0555cf496dcc371b4f697e64855b6d79f0 100644 --- a/substrate/bin/node/testing/Cargo.toml +++ b/substrate/bin/node/testing/Cargo.toml @@ -16,36 +16,36 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12" } -fs_extra = "1" -futures = "0.3.30" +codec = { workspace = true, default-features = true } +fs_extra = { workspace = true } +futures = { workspace = true } log = { workspace = true, default-features = true } -tempfile = "3.1.0" -frame-metadata-hash-extension = { path = "../../../frame/metadata-hash-extension" } -frame-system = { path = "../../../frame/system" } -node-cli = { package = "staging-node-cli", path = "../cli" } -node-primitives = { path = "../primitives" } -kitchensink-runtime = { path = "../runtime" } -pallet-asset-conversion = { path = "../../../frame/asset-conversion" } -pallet-assets = { path = "../../../frame/assets" } -pallet-asset-conversion-tx-payment = { path = "../../../frame/transaction-payment/asset-conversion-tx-payment" } -pallet-asset-tx-payment = { path = "../../../frame/transaction-payment/asset-tx-payment" } -pallet-skip-feeless-payment = { path = "../../../frame/transaction-payment/skip-feeless-payment" } -sc-block-builder = { path = "../../../client/block-builder" } -sc-client-api = { path = "../../../client/api" } -sc-client-db = { path = "../../../client/db", features = ["rocksdb"] } -sc-consensus = { path = "../../../client/consensus/common" } -sc-executor = { path = "../../../client/executor" } -sc-service = { path = "../../../client/service", features = ["rocksdb", "test-helpers"] } -sp-api = { path = "../../../primitives/api" } -sp-block-builder = { path = "../../../primitives/block-builder" } -sp-blockchain = { path = "../../../primitives/blockchain" } -sp-consensus = { path = "../../../primitives/consensus/common" } -sp-core = { path = "../../../primitives/core" } -sp-crypto-hashing = { path = "../../../primitives/crypto/hashing" } -sp-inherents = { path = "../../../primitives/inherents" } -sp-io = { path = "../../../primitives/io" } -sp-keyring = { path = "../../../primitives/keyring" } -sp-runtime = { path = "../../../primitives/runtime" } -sp-timestamp = { path = "../../../primitives/timestamp", default-features = false } -substrate-test-client = { path = "../../../test-utils/client" } +tempfile = { workspace = true } +frame-metadata-hash-extension = { workspace = true, default-features = true } +frame-system = { workspace = true, default-features = true } +node-cli = { workspace = true } +node-primitives = { workspace = true, default-features = true } +kitchensink-runtime = { workspace = true } +pallet-asset-conversion = { workspace = true, default-features = true } +pallet-assets = { workspace = true, default-features = true } +pallet-asset-conversion-tx-payment = { workspace = true, default-features = true } +pallet-asset-tx-payment = { workspace = true, default-features = true } +pallet-skip-feeless-payment = { workspace = true, default-features = true } +sc-block-builder = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-client-db = { features = ["rocksdb"], workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } +sc-executor = { workspace = true, default-features = true } +sc-service = { features = ["rocksdb", "test-helpers"], workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-block-builder = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-crypto-hashing = { workspace = true, default-features = true } +sp-inherents = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-timestamp = { workspace = true } +substrate-test-client = { workspace = true } diff --git a/substrate/bin/utils/chain-spec-builder/Cargo.toml b/substrate/bin/utils/chain-spec-builder/Cargo.toml index 88585649acfe015e2e1e7ca6285c1a3565ca6f78..083f2191f3c5a9a9b3b41639ed20808173d3a3a4 100644 --- a/substrate/bin/utils/chain-spec-builder/Cargo.toml +++ b/substrate/bin/utils/chain-spec-builder/Cargo.toml @@ -24,8 +24,8 @@ name = "chain-spec-builder" crate-type = ["rlib"] [dependencies] -clap = { version = "4.5.3", features = ["derive"] } +clap = { features = ["derive"], workspace = true } log = { workspace = true, default-features = true } -sc-chain-spec = { path = "../../../client/chain-spec", features = ["clap"] } +sc-chain-spec = { features = ["clap"], workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } -sp-tracing = { path = "../../../primitives/tracing" } +sp-tracing = { workspace = true, default-features = true } diff --git a/substrate/bin/utils/chain-spec-builder/bin/main.rs b/substrate/bin/utils/chain-spec-builder/bin/main.rs index 18da3c30691bd895c833454cb6cd9f6fda91531d..39fa054b4806d396acd557947a957c6cfdd519f7 100644 --- a/substrate/bin/utils/chain-spec-builder/bin/main.rs +++ b/substrate/bin/utils/chain-spec-builder/bin/main.rs @@ -17,16 +17,19 @@ // along with this program. If not, see . use chain_spec_builder::{ - generate_chain_spec_for_runtime, ChainSpecBuilder, ChainSpecBuilderCmd, ConvertToRawCmd, - DisplayPresetCmd, ListPresetsCmd, UpdateCodeCmd, VerifyCmd, + generate_chain_spec_for_runtime, AddCodeSubstituteCmd, ChainSpecBuilder, ChainSpecBuilderCmd, + ConvertToRawCmd, DisplayPresetCmd, ListPresetsCmd, UpdateCodeCmd, VerifyCmd, }; use clap::Parser; use sc_chain_spec::{ - update_code_in_json_chain_spec, GenericChainSpec, GenesisConfigBuilderRuntimeCaller, + set_code_substitute_in_json_chain_spec, update_code_in_json_chain_spec, GenericChainSpec, + GenesisConfigBuilderRuntimeCaller, }; use staging_chain_spec_builder as chain_spec_builder; use std::fs; +type ChainSpec = GenericChainSpec<(), ()>; + //avoid error message escaping fn main() { match inner_main() { @@ -50,7 +53,7 @@ fn inner_main() -> Result<(), String> { ref input_chain_spec, ref runtime_wasm_path, }) => { - let chain_spec = GenericChainSpec::<()>::from_json_file(input_chain_spec.clone())?; + let chain_spec = ChainSpec::from_json_file(input_chain_spec.clone())?; let mut chain_spec_json = serde_json::from_str::(&chain_spec.as_json(false)?) @@ -65,8 +68,29 @@ fn inner_main() -> Result<(), String> { .map_err(|e| format!("to pretty failed: {e}"))?; fs::write(chain_spec_path, chain_spec_json).map_err(|err| err.to_string())?; }, + ChainSpecBuilderCmd::AddCodeSubstitute(AddCodeSubstituteCmd { + ref input_chain_spec, + ref runtime_wasm_path, + block_height, + }) => { + let chain_spec = ChainSpec::from_json_file(input_chain_spec.clone())?; + + let mut chain_spec_json = + serde_json::from_str::(&chain_spec.as_json(false)?) + .map_err(|e| format!("Conversion to json failed: {e}"))?; + + set_code_substitute_in_json_chain_spec( + &mut chain_spec_json, + &fs::read(runtime_wasm_path.as_path()) + .map_err(|e| format!("Wasm blob file could not be read: {e}"))?[..], + block_height, + ); + let chain_spec_json = serde_json::to_string_pretty(&chain_spec_json) + .map_err(|e| format!("to pretty failed: {e}"))?; + fs::write(chain_spec_path, chain_spec_json).map_err(|err| err.to_string())?; + }, ChainSpecBuilderCmd::ConvertToRaw(ConvertToRawCmd { ref input_chain_spec }) => { - let chain_spec = GenericChainSpec::<()>::from_json_file(input_chain_spec.clone())?; + let chain_spec = ChainSpec::from_json_file(input_chain_spec.clone())?; let chain_spec_json = serde_json::from_str::(&chain_spec.as_json(true)?) @@ -77,7 +101,7 @@ fn inner_main() -> Result<(), String> { fs::write(chain_spec_path, chain_spec_json).map_err(|err| err.to_string())?; }, ChainSpecBuilderCmd::Verify(VerifyCmd { ref input_chain_spec }) => { - let chain_spec = GenericChainSpec::<()>::from_json_file(input_chain_spec.clone())?; + let chain_spec = ChainSpec::from_json_file(input_chain_spec.clone())?; let _ = serde_json::from_str::(&chain_spec.as_json(true)?) .map_err(|e| format!("Conversion to json failed: {e}"))?; }, diff --git a/substrate/bin/utils/chain-spec-builder/src/lib.rs b/substrate/bin/utils/chain-spec-builder/src/lib.rs index 0f7c003fc8c2da2709076ee3c6f517d9a2ae8beb..6c679f109a002401bb6b25718979c2e8fc58d2a9 100644 --- a/substrate/bin/utils/chain-spec-builder/src/lib.rs +++ b/substrate/bin/utils/chain-spec-builder/src/lib.rs @@ -125,7 +125,7 @@ use serde_json::Value; /// A utility to easily create a chain spec definition. #[derive(Debug, Parser)] -#[command(rename_all = "kebab-case")] +#[command(rename_all = "kebab-case", version, about)] pub struct ChainSpecBuilder { #[command(subcommand)] pub command: ChainSpecBuilderCmd, @@ -143,6 +143,7 @@ pub enum ChainSpecBuilderCmd { ConvertToRaw(ConvertToRawCmd), ListPresets(ListPresetsCmd), DisplayPreset(DisplayPresetCmd), + AddCodeSubstitute(AddCodeSubstituteCmd), } /// Create a new chain spec by interacting with the provided runtime wasm blob. @@ -222,6 +223,25 @@ pub struct UpdateCodeCmd { pub runtime_wasm_path: PathBuf, } +/// Add a code substitute in the chain spec. +/// +/// The `codeSubstitute` object of the chain spec will be updated with the block height as key and +/// runtime code as value. This operation supports both plain and raw formats. The `codeSubstitute` +/// field instructs the node to use the provided runtime code at the given block height. This is +/// useful when the chain can not progress on its own due to a bug that prevents block-building. +/// +/// Note: For parachains, the validation function on the relaychain needs to be adjusted too, +/// otherwise blocks built using the substituted parachain runtime will be rejected. +#[derive(Parser, Debug, Clone)] +pub struct AddCodeSubstituteCmd { + /// Chain spec to be updated. + pub input_chain_spec: PathBuf, + /// New runtime wasm blob that should replace the existing code. + pub runtime_wasm_path: PathBuf, + /// The block height at which the code should be substituted. + pub block_height: u64, +} + /// Converts the given chain spec into the raw format. #[derive(Parser, Debug, Clone)] pub struct ConvertToRawCmd { diff --git a/substrate/bin/utils/subkey/Cargo.toml b/substrate/bin/utils/subkey/Cargo.toml index 8dc4bf254b2d44e1f6b5c96ca16a2e8586e0333c..5aa013097c150add192d25c2b658c61720e39bd8 100644 --- a/substrate/bin/utils/subkey/Cargo.toml +++ b/substrate/bin/utils/subkey/Cargo.toml @@ -20,5 +20,5 @@ path = "src/main.rs" name = "subkey" [dependencies] -clap = { version = "4.5.3", features = ["derive"] } -sc-cli = { path = "../../../client/cli" } +clap = { features = ["derive"], workspace = true } +sc-cli = { workspace = true, default-features = true } diff --git a/substrate/client/allocator/Cargo.toml b/substrate/client/allocator/Cargo.toml index 2c268b548ea9c32fabdc82226c77e82a7ef59cea..5a3b05aa8a98d8366433d574e158a8cd9a2f3a64 100644 --- a/substrate/client/allocator/Cargo.toml +++ b/substrate/client/allocator/Cargo.toml @@ -19,5 +19,5 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] log = { workspace = true, default-features = true } thiserror = { workspace = true } -sp-core = { path = "../../primitives/core" } -sp-wasm-interface = { path = "../../primitives/wasm-interface" } +sp-core = { workspace = true, default-features = true } +sp-wasm-interface = { workspace = true, default-features = true } diff --git a/substrate/client/api/Cargo.toml b/substrate/client/api/Cargo.toml index 147ea2bfbf5df83716c4a7f1f5fb2ade0c41d3f8..a64ee3ab4ce1944672ec87aac34119720834ef59 100644 --- a/substrate/client/api/Cargo.toml +++ b/substrate/client/api/Cargo.toml @@ -17,30 +17,30 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", -] } -fnv = "1.0.6" -futures = "0.3.30" +], workspace = true } +fnv = { workspace = true } +futures = { workspace = true } log = { workspace = true, default-features = true } -parking_lot = "0.12.1" -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../utils/prometheus" } -sc-executor = { path = "../executor" } -sc-transaction-pool-api = { path = "../transaction-pool/api" } -sc-utils = { path = "../utils" } -sp-api = { path = "../../primitives/api" } -sp-blockchain = { path = "../../primitives/blockchain" } -sp-consensus = { path = "../../primitives/consensus/common" } -sp-core = { path = "../../primitives/core", default-features = false } -sp-database = { path = "../../primitives/database" } -sp-externalities = { path = "../../primitives/externalities" } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-state-machine = { path = "../../primitives/state-machine" } -sp-statement-store = { path = "../../primitives/statement-store" } -sp-storage = { path = "../../primitives/storage" } -sp-trie = { path = "../../primitives/trie" } +parking_lot = { workspace = true, default-features = true } +prometheus-endpoint = { workspace = true, default-features = true } +sc-executor = { workspace = true, default-features = true } +sc-transaction-pool-api = { workspace = true, default-features = true } +sc-utils = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-core = { workspace = true } +sp-database = { workspace = true, default-features = true } +sp-externalities = { workspace = true, default-features = true } +sp-runtime = { workspace = true } +sp-state-machine = { workspace = true, default-features = true } +sp-statement-store = { workspace = true, default-features = true } +sp-storage = { workspace = true, default-features = true } +sp-trie = { workspace = true, default-features = true } [dev-dependencies] thiserror = { workspace = true } -sp-test-primitives = { path = "../../primitives/test-primitives" } -substrate-test-runtime = { path = "../../test-utils/runtime" } +sp-test-primitives = { workspace = true } +substrate-test-runtime = { workspace = true } diff --git a/substrate/client/api/src/client.rs b/substrate/client/api/src/client.rs index 2de09840e4dfdc15e1f1d1acaa5f3e438de0caca..45cfafb258463a50c2ce0ce5b843346bd6cb9dcb 100644 --- a/substrate/client/api/src/client.rs +++ b/substrate/client/api/src/client.rs @@ -168,7 +168,7 @@ pub trait ProvideUncles { } /// Client info -#[derive(Debug)] +#[derive(Debug, Clone)] pub struct ClientInfo { /// Best block hash. pub chain: Info, diff --git a/substrate/client/authority-discovery/Cargo.toml b/substrate/client/authority-discovery/Cargo.toml index 435ca88a80079c9da9510b0f505d21677afb52cf..309c9c542a0b10fa8c7fbff14a07c5622634e8f2 100644 --- a/substrate/client/authority-discovery/Cargo.toml +++ b/substrate/client/authority-discovery/Cargo.toml @@ -17,38 +17,33 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [build-dependencies] -prost-build = "0.12.4" +prost-build = { workspace = true } [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -futures = "0.3.30" -futures-timer = "3.0.1" -ip_network = "0.4.1" -libp2p = { version = "0.51.4", features = ["ed25519", "kad"] } -multihash = { version = "0.17.0", default-features = false, features = ["sha2", "std"] } -linked_hash_set = "0.1.4" +codec = { workspace = true } +futures = { workspace = true } +futures-timer = { workspace = true } +ip_network = { workspace = true } +libp2p = { features = ["ed25519", "kad"], workspace = true } +multihash = { workspace = true } +linked_hash_set = { workspace = true } log = { workspace = true, default-features = true } -prost = "0.12.4" -rand = "0.8.5" +prost = { workspace = true } +rand = { workspace = true, default-features = true } thiserror = { workspace = true } -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../utils/prometheus" } -sc-client-api = { path = "../api" } -sc-network = { path = "../network" } -sc-network-types = { path = "../network/types" } -sp-api = { path = "../../primitives/api" } -sp-authority-discovery = { path = "../../primitives/authority-discovery" } -sp-blockchain = { path = "../../primitives/blockchain" } -sp-core = { path = "../../primitives/core" } -sp-keystore = { path = "../../primitives/keystore" } -sp-runtime = { path = "../../primitives/runtime" } -async-trait = "0.1.79" -multihash-codetable = { version = "0.1.1", features = [ - "digest", - "serde", - "sha2", -] } +prometheus-endpoint = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sc-network-types = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-authority-discovery = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +async-trait = { workspace = true } [dev-dependencies] -quickcheck = { version = "1.0.3", default-features = false } -sp-tracing = { path = "../../primitives/tracing" } -substrate-test-runtime-client = { path = "../../test-utils/runtime/client" } +quickcheck = { workspace = true } +sp-tracing = { workspace = true, default-features = true } +substrate-test-runtime-client = { workspace = true } diff --git a/substrate/client/authority-discovery/src/service.rs b/substrate/client/authority-discovery/src/service.rs index 60c7a2b990378f0c91a16854bdb815de8661c53a..852d3ab80c9b8926d291f5a83249515b1c8fabc6 100644 --- a/substrate/client/authority-discovery/src/service.rs +++ b/substrate/client/authority-discovery/src/service.rs @@ -55,7 +55,7 @@ impl Service { /// [`crate::Worker`] failed. /// /// Note: [`Multiaddr`]s returned always include a [`PeerId`] via a - /// [`libp2p::core::multiaddr::Protocol::P2p`] component. Equality of + /// [`sc_network_types::multiaddr::Protocol::P2p`] component. Equality of /// [`PeerId`]s across [`Multiaddr`]s returned by a single call is not /// enforced today, given that there are still authorities out there /// publishing the addresses of their sentry nodes on the DHT. In the future diff --git a/substrate/client/authority-discovery/src/worker.rs b/substrate/client/authority-discovery/src/worker.rs index f20cf6aa2121204063982bc7717bf094ac561c53..b81b10b3ae0a27742caa5454e209fed372e80744 100644 --- a/substrate/client/authority-discovery/src/worker.rs +++ b/substrate/client/authority-discovery/src/worker.rs @@ -45,10 +45,7 @@ use sc_network::{ event::DhtEvent, multiaddr, KademliaKey, Multiaddr, NetworkDHTProvider, NetworkSigner, NetworkStateInfo, }; -use sc_network_types::{ - multihash::{Code, Multihash}, - PeerId, -}; +use sc_network_types::{multihash::Code, PeerId}; use schema::PeerSignature; use sp_api::{ApiError, ProvideRuntimeApi}; use sp_authority_discovery::{ @@ -247,14 +244,14 @@ where }; let public_addresses = { - let local_peer_id: Multihash = network.local_peer_id().into(); + let local_peer_id = network.local_peer_id(); config .public_addresses .into_iter() .map(|mut address| { if let Some(multiaddr::Protocol::P2p(peer_id)) = address.iter().last() { - if peer_id != local_peer_id { + if peer_id != *local_peer_id.as_ref() { error!( target: LOG_TARGET, "Discarding invalid local peer ID in public address {address}.", @@ -401,10 +398,9 @@ where ); // The address must include the local peer id. - let local_peer_id: Multihash = local_peer_id.into(); addresses .into_iter() - .map(move |a| a.with(multiaddr::Protocol::P2p(local_peer_id))) + .map(move |a| a.with(multiaddr::Protocol::P2p(*local_peer_id.as_ref()))) } /// Publish own public addresses. diff --git a/substrate/client/authority-discovery/src/worker/addr_cache.rs b/substrate/client/authority-discovery/src/worker/addr_cache.rs index 77cdfbd4f1502574cd5a1aa2434d3c0fd392fd51..13bb990bf8b9908a5ec9a11e205a4a380c5954b4 100644 --- a/substrate/client/authority-discovery/src/worker/addr_cache.rs +++ b/substrate/client/authority-discovery/src/worker/addr_cache.rs @@ -177,7 +177,7 @@ mod tests { use super::*; use quickcheck::{Arbitrary, Gen, QuickCheck, TestResult}; - use sc_network_types::multihash::Multihash; + use sc_network_types::multihash::{Code, Multihash}; use sp_authority_discovery::{AuthorityId, AuthorityPair}; use sp_core::crypto::Pair; @@ -198,10 +198,9 @@ mod tests { impl Arbitrary for TestMultiaddr { fn arbitrary(g: &mut Gen) -> Self { let seed = (0..32).map(|_| u8::arbitrary(g)).collect::>(); - let peer_id = PeerId::from_multihash( - Multihash::wrap(multihash::Code::Sha2_256.into(), &seed).unwrap(), - ) - .unwrap(); + let peer_id = + PeerId::from_multihash(Multihash::wrap(Code::Sha2_256.into(), &seed).unwrap()) + .unwrap(); let multiaddr = "/ip6/2001:db8:0:0:0:0:0:2/tcp/30333" .parse::() .unwrap() @@ -217,10 +216,9 @@ mod tests { impl Arbitrary for TestMultiaddrsSamePeerCombo { fn arbitrary(g: &mut Gen) -> Self { let seed = (0..32).map(|_| u8::arbitrary(g)).collect::>(); - let peer_id = PeerId::from_multihash( - Multihash::wrap(multihash::Code::Sha2_256.into(), &seed).unwrap(), - ) - .unwrap(); + let peer_id = + PeerId::from_multihash(Multihash::wrap(Code::Sha2_256.into(), &seed).unwrap()) + .unwrap(); let multiaddr1 = "/ip6/2001:db8:0:0:0:0:0:2/tcp/30333" .parse::() .unwrap() diff --git a/substrate/client/basic-authorship/Cargo.toml b/substrate/client/basic-authorship/Cargo.toml index b75cb463b1a874c48a7b8c4511929eade4245704..e3ae80e14f6ffd3f554f59f3debb45a3b0c04431 100644 --- a/substrate/client/basic-authorship/Cargo.toml +++ b/substrate/client/basic-authorship/Cargo.toml @@ -16,24 +16,24 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12" } -futures = "0.3.30" -futures-timer = "3.0.1" +codec = { workspace = true, default-features = true } +futures = { workspace = true } +futures-timer = { workspace = true } log = { workspace = true, default-features = true } -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../utils/prometheus" } -sc-block-builder = { path = "../block-builder" } -sc-proposer-metrics = { path = "../proposer-metrics" } -sc-telemetry = { path = "../telemetry" } -sc-transaction-pool-api = { path = "../transaction-pool/api" } -sp-api = { path = "../../primitives/api" } -sp-blockchain = { path = "../../primitives/blockchain" } -sp-consensus = { path = "../../primitives/consensus/common" } -sp-core = { path = "../../primitives/core" } -sp-inherents = { path = "../../primitives/inherents" } -sp-runtime = { path = "../../primitives/runtime" } +prometheus-endpoint = { workspace = true, default-features = true } +sc-block-builder = { workspace = true, default-features = true } +sc-proposer-metrics = { workspace = true, default-features = true } +sc-telemetry = { workspace = true, default-features = true } +sc-transaction-pool-api = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-inherents = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } [dev-dependencies] -parking_lot = "0.12.1" -sc-client-api = { path = "../api" } -sc-transaction-pool = { path = "../transaction-pool" } -substrate-test-runtime-client = { path = "../../test-utils/runtime/client" } +parking_lot = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-transaction-pool = { workspace = true, default-features = true } +substrate-test-runtime-client = { workspace = true } diff --git a/substrate/client/block-builder/Cargo.toml b/substrate/client/block-builder/Cargo.toml index 62efe977e989c13bfc6e3fe0fb11d13ac3aca298..47e3fc39c289997bdcdfa094ce65193295ab0220 100644 --- a/substrate/client/block-builder/Cargo.toml +++ b/substrate/client/block-builder/Cargo.toml @@ -16,17 +16,17 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", features = [ +codec = { features = [ "derive", -] } -sp-api = { path = "../../primitives/api" } -sp-block-builder = { path = "../../primitives/block-builder" } -sp-blockchain = { path = "../../primitives/blockchain" } -sp-core = { path = "../../primitives/core" } -sp-trie = { path = "../../primitives/trie" } -sp-inherents = { path = "../../primitives/inherents" } -sp-runtime = { path = "../../primitives/runtime" } +], workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-block-builder = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-trie = { workspace = true, default-features = true } +sp-inherents = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } [dev-dependencies] -sp-state-machine = { path = "../../primitives/state-machine" } -substrate-test-runtime-client = { path = "../../test-utils/runtime/client" } +sp-state-machine = { workspace = true, default-features = true } +substrate-test-runtime-client = { workspace = true } diff --git a/substrate/client/chain-spec/Cargo.toml b/substrate/client/chain-spec/Cargo.toml index 5b411b642a0e3aa410517621d99f4ab3cd245a74..b3cd4bd57db86c0384c56316315550edda962f24 100644 --- a/substrate/client/chain-spec/Cargo.toml +++ b/substrate/client/chain-spec/Cargo.toml @@ -16,31 +16,31 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -clap = { version = "4.5.3", features = ["derive"], optional = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -memmap2 = "0.9.3" +clap = { features = ["derive"], optional = true, workspace = true } +codec = { features = ["derive"], workspace = true } +memmap2 = { workspace = true } serde = { features = ["derive"], workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } -sc-client-api = { path = "../api" } -sc-chain-spec-derive = { path = "derive" } -sc-executor = { path = "../executor" } -sp-io = { default-features = false, path = "../../primitives/io" } -sc-network = { path = "../network" } -sc-telemetry = { path = "../telemetry" } -sp-blockchain = { path = "../../primitives/blockchain" } -sp-core = { path = "../../primitives/core" } -sp-crypto-hashing = { path = "../../primitives/crypto/hashing" } -sp-genesis-builder = { path = "../../primitives/genesis-builder" } -sp-runtime = { path = "../../primitives/runtime" } -sp-state-machine = { path = "../../primitives/state-machine" } +sc-client-api = { workspace = true, default-features = true } +sc-chain-spec-derive = { workspace = true, default-features = true } +sc-executor = { workspace = true, default-features = true } +sp-io = { workspace = true } +sc-network = { workspace = true, default-features = true } +sc-telemetry = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-crypto-hashing = { workspace = true, default-features = true } +sp-genesis-builder = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-state-machine = { workspace = true, default-features = true } log = { workspace = true } -sp-tracing = { path = "../../primitives/tracing" } -array-bytes = "6.2.2" -docify = "0.2.8" +sp-tracing = { workspace = true, default-features = true } +array-bytes = { workspace = true, default-features = true } +docify = { workspace = true } [dev-dependencies] -substrate-test-runtime = { path = "../../test-utils/runtime" } -sp-keyring = { path = "../../primitives/keyring" } -sp-application-crypto = { default-features = false, path = "../../primitives/application-crypto", features = ["serde"] } -sp-consensus-babe = { default-features = false, path = "../../primitives/consensus/babe", features = ["serde"] } -regex = "1.6.0" +substrate-test-runtime = { workspace = true } +sp-keyring = { workspace = true, default-features = true } +sp-application-crypto = { features = ["serde"], workspace = true } +sp-consensus-babe = { features = ["serde"], workspace = true } +regex = { workspace = true } diff --git a/substrate/client/chain-spec/derive/Cargo.toml b/substrate/client/chain-spec/derive/Cargo.toml index 521eee578ecae3b03cf86a3b4e3630bb7cd22f02..4ab8c849cc7feb6368c5f74fbbd77703434b7675 100644 --- a/substrate/client/chain-spec/derive/Cargo.toml +++ b/substrate/client/chain-spec/derive/Cargo.toml @@ -18,7 +18,7 @@ targets = ["x86_64-unknown-linux-gnu"] proc-macro = true [dependencies] -proc-macro-crate = "3.0.0" -proc-macro2 = "1.0.56" +proc-macro-crate = { workspace = true } +proc-macro2 = { workspace = true } quote = { workspace = true } syn = { workspace = true } diff --git a/substrate/client/chain-spec/src/chain_spec.rs b/substrate/client/chain-spec/src/chain_spec.rs index 883cd19adfd1c7543ee919a6e436df1838c6efe2..5f90f549e02262e97c3ae8ea82941838faa5e2f7 100644 --- a/substrate/client/chain-spec/src/chain_spec.rs +++ b/substrate/client/chain-spec/src/chain_spec.rs @@ -766,6 +766,16 @@ pub fn update_code_in_json_chain_spec(chain_spec: &mut json::Value, code: &[u8]) } } +/// This function sets a codeSubstitute in the chain spec. +pub fn set_code_substitute_in_json_chain_spec( + chain_spec: &mut json::Value, + code: &[u8], + block_height: u64, +) { + let substitutes = json::json!({"codeSubstitutes":{ &block_height.to_string(): sp_core::bytes::to_hex(code, false) }}); + crate::json_patch::merge(chain_spec, substitutes); +} + #[cfg(test)] mod tests { use super::*; diff --git a/substrate/client/chain-spec/src/lib.rs b/substrate/client/chain-spec/src/lib.rs index b59ad68610ecee8fc78ea15eb7cd717fe2bb4d40..c43f9e89b8a993f6a349b3eb612b41346acc62ec 100644 --- a/substrate/client/chain-spec/src/lib.rs +++ b/substrate/client/chain-spec/src/lib.rs @@ -333,8 +333,8 @@ pub mod json_patch; pub use self::{ chain_spec::{ - update_code_in_json_chain_spec, ChainSpec as GenericChainSpec, ChainSpecBuilder, - NoExtension, + set_code_substitute_in_json_chain_spec, update_code_in_json_chain_spec, + ChainSpec as GenericChainSpec, ChainSpecBuilder, NoExtension, }, extension::{get_extension, get_extension_mut, Extension, Fork, Forks, GetExtension, Group}, genesis_block::{ diff --git a/substrate/client/cli/Cargo.toml b/substrate/client/cli/Cargo.toml index 169ed72c96e489ee35dca02edc6e098c2426eadb..1e4017c23af231baf0946ed26cc37e7767276cbb 100644 --- a/substrate/client/cli/Cargo.toml +++ b/substrate/client/cli/Cargo.toml @@ -16,46 +16,46 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -array-bytes = "6.2.2" -chrono = "0.4.31" -clap = { version = "4.5.3", features = ["derive", "string", "wrap_help"] } -fdlimit = "0.3.0" -futures = "0.3.30" -itertools = "0.11" -libp2p-identity = { version = "0.1.3", features = ["ed25519", "peerid"] } +array-bytes = { workspace = true, default-features = true } +chrono = { workspace = true } +clap = { features = ["derive", "string", "wrap_help"], workspace = true } +fdlimit = { workspace = true } +futures = { workspace = true } +itertools = { workspace = true } +libp2p-identity = { features = ["ed25519", "peerid"], workspace = true } log = { workspace = true, default-features = true } -names = { version = "0.14.0", default-features = false } -codec = { package = "parity-scale-codec", version = "3.6.12" } -rand = "0.8.5" -regex = "1.6.0" -rpassword = "7.0.0" +names = { workspace = true } +codec = { workspace = true, default-features = true } +rand = { workspace = true, default-features = true } +regex = { workspace = true } +rpassword = { workspace = true } serde = { workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } thiserror = { workspace = true } # personal fork here as workaround for: https://github.com/rust-bitcoin/rust-bip39/pull/64 bip39 = { package = "parity-bip39", version = "2.0.1", features = ["rand"] } -tokio = { version = "1.22.0", features = ["parking_lot", "rt-multi-thread", "signal"] } -sc-client-api = { path = "../api" } -sc-client-db = { path = "../db", default-features = false } -sc-keystore = { path = "../keystore" } -sc-mixnet = { path = "../mixnet" } -sc-network = { path = "../network" } -sc-service = { path = "../service", default-features = false } -sc-telemetry = { path = "../telemetry" } -sc-tracing = { path = "../tracing" } -sc-utils = { path = "../utils" } -sp-blockchain = { path = "../../primitives/blockchain" } -sp-core = { path = "../../primitives/core" } -sp-keyring = { path = "../../primitives/keyring" } -sp-keystore = { path = "../../primitives/keystore" } -sp-panic-handler = { path = "../../primitives/panic-handler" } -sp-runtime = { path = "../../primitives/runtime" } -sp-version = { path = "../../primitives/version" } +tokio = { features = ["parking_lot", "rt-multi-thread", "signal"], workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-client-db = { workspace = true } +sc-keystore = { workspace = true, default-features = true } +sc-mixnet = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sc-service = { workspace = true } +sc-telemetry = { workspace = true, default-features = true } +sc-tracing = { workspace = true, default-features = true } +sc-utils = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-panic-handler = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-version = { workspace = true, default-features = true } [dev-dependencies] -tempfile = "3.1.0" -futures-timer = "3.0.1" -sp-tracing = { path = "../../primitives/tracing" } +tempfile = { workspace = true } +futures-timer = { workspace = true } +sp-tracing = { workspace = true, default-features = true } [features] default = ["rocksdb"] diff --git a/substrate/client/cli/src/params/pruning_params.rs b/substrate/client/cli/src/params/pruning_params.rs index 25b17b53289818ba02e839e98b9738f380fc1067..6b7b0e7ffa9976e7121b7392fb25f0adaf493c45 100644 --- a/substrate/client/cli/src/params/pruning_params.rs +++ b/substrate/client/cli/src/params/pruning_params.rs @@ -29,11 +29,18 @@ pub struct PruningParams { /// should be pruned (ie, removed) from the database. /// This setting can only be set on the first creation of the database. Every subsequent run /// will load the pruning mode from the database and will error if the stored mode doesn't - /// match this CLI value. It is fine to drop this CLI flag for subsequent runs. + /// match this CLI value. It is fine to drop this CLI flag for subsequent runs. The only + /// exception is that `NUMBER` can change between subsequent runs (increasing it will not + /// lead to restoring pruned state). + /// /// Possible values: - /// - archive: Keep the state of all blocks. - /// - 'archive-canonical' Keep only the state of finalized blocks. - /// - number Keep the state of the last number of finalized blocks. + /// + /// - archive: Keep the data of all blocks. + /// + /// - archive-canonical: Keep only the data of finalized blocks. + /// + /// - NUMBER: Keep the data of the last NUMBER of finalized blocks. + /// /// [default: 256] #[arg(alias = "pruning", long, value_name = "PRUNING_MODE")] pub state_pruning: Option, @@ -42,11 +49,14 @@ pub struct PruningParams { /// /// This mode specifies when the block's body (including justifications) /// should be pruned (ie, removed) from the database. + /// /// Possible values: - /// - 'archive' Keep all blocks. - /// - 'archive-canonical' Keep only finalized blocks. - /// - number - /// Keep the last `number` of finalized blocks. + /// + /// - archive: Keep the data of all blocks. + /// + /// - archive-canonical: Keep only the data of finalized blocks. + /// + /// - NUMBER: Keep the data of the last NUMBER of finalized blocks. #[arg( alias = "keep-blocks", long, @@ -117,3 +127,39 @@ impl Into for DatabasePruningMode { } } } + +#[cfg(test)] +mod tests { + use super::*; + use clap::Parser; + + #[derive(Parser)] + struct Cli { + #[clap(flatten)] + pruning: PruningParams, + } + + #[test] + fn pruning_params_parse_works() { + let Cli { pruning } = + Cli::parse_from(["", "--state-pruning=1000", "--blocks-pruning=1000"]); + + assert!(matches!(pruning.state_pruning, Some(DatabasePruningMode::Custom(1000)))); + assert!(matches!(pruning.blocks_pruning, DatabasePruningMode::Custom(1000))); + + let Cli { pruning } = + Cli::parse_from(["", "--state-pruning=archive", "--blocks-pruning=archive"]); + + assert!(matches!(dbg!(pruning.state_pruning), Some(DatabasePruningMode::Archive))); + assert!(matches!(pruning.blocks_pruning, DatabasePruningMode::Archive)); + + let Cli { pruning } = Cli::parse_from([ + "", + "--state-pruning=archive-canonical", + "--blocks-pruning=archive-canonical", + ]); + + assert!(matches!(dbg!(pruning.state_pruning), Some(DatabasePruningMode::ArchiveCanonical))); + assert!(matches!(pruning.blocks_pruning, DatabasePruningMode::ArchiveCanonical)); + } +} diff --git a/substrate/client/consensus/aura/Cargo.toml b/substrate/client/consensus/aura/Cargo.toml index d1460c45356d7ec86204b52c42c08ee28e9c5faf..3a3d7ae18d711e0c9b952e4f1383ae8ecb28fbc3 100644 --- a/substrate/client/consensus/aura/Cargo.toml +++ b/substrate/client/consensus/aura/Cargo.toml @@ -16,37 +16,37 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -async-trait = "0.1.79" -codec = { package = "parity-scale-codec", version = "3.6.12" } -futures = "0.3.30" +async-trait = { workspace = true } +codec = { workspace = true, default-features = true } +futures = { workspace = true } log = { workspace = true, default-features = true } thiserror = { workspace = true } -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../../utils/prometheus" } -sc-block-builder = { path = "../../block-builder" } -sc-client-api = { path = "../../api" } -sc-consensus = { path = "../common" } -sc-consensus-slots = { path = "../slots" } -sc-telemetry = { path = "../../telemetry" } -sp-api = { path = "../../../primitives/api" } -sp-application-crypto = { path = "../../../primitives/application-crypto" } -sp-block-builder = { path = "../../../primitives/block-builder" } -sp-blockchain = { path = "../../../primitives/blockchain" } -sp-consensus = { path = "../../../primitives/consensus/common" } -sp-consensus-aura = { path = "../../../primitives/consensus/aura" } -sp-consensus-slots = { path = "../../../primitives/consensus/slots" } -sp-core = { path = "../../../primitives/core" } -sp-inherents = { path = "../../../primitives/inherents" } -sp-keystore = { path = "../../../primitives/keystore" } -sp-runtime = { path = "../../../primitives/runtime" } +prometheus-endpoint = { workspace = true, default-features = true } +sc-block-builder = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } +sc-consensus-slots = { workspace = true, default-features = true } +sc-telemetry = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-application-crypto = { workspace = true, default-features = true } +sp-block-builder = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-consensus-aura = { workspace = true, default-features = true } +sp-consensus-slots = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-inherents = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } [dev-dependencies] -parking_lot = "0.12.1" -tempfile = "3.1.0" -sc-keystore = { path = "../../keystore" } -sc-network = { path = "../../network" } -sc-network-test = { path = "../../network/test" } -sp-keyring = { path = "../../../primitives/keyring" } -sp-timestamp = { path = "../../../primitives/timestamp" } -sp-tracing = { path = "../../../primitives/tracing" } -substrate-test-runtime-client = { path = "../../../test-utils/runtime/client" } -tokio = { version = "1.22.0" } +parking_lot = { workspace = true, default-features = true } +tempfile = { workspace = true } +sc-keystore = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sc-network-test = { workspace = true } +sp-keyring = { workspace = true, default-features = true } +sp-timestamp = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +substrate-test-runtime-client = { workspace = true } +tokio = { workspace = true, default-features = true } diff --git a/substrate/client/consensus/aura/src/import_queue.rs b/substrate/client/consensus/aura/src/import_queue.rs index a8777ef8788cc3a247d6d09c146f61bf4cb23e62..79f4faa5ebf97657b0f6d02933a1e7f8421d4f56 100644 --- a/substrate/client/consensus/aura/src/import_queue.rs +++ b/substrate/client/consensus/aura/src/import_queue.rs @@ -174,7 +174,7 @@ where CIDP::InherentDataProviders: InherentDataProviderExt + Send + Sync, { async fn verify( - &mut self, + &self, mut block: BlockImportParams, ) -> Result, String> { // Skip checks that include execution, if being told so or when importing only state. diff --git a/substrate/client/consensus/babe/Cargo.toml b/substrate/client/consensus/babe/Cargo.toml index c51082a018b5cfd558efe0b76985d6add890057d..bba60bc45ea50d5c14b2d6a742de690ea95c98d6 100644 --- a/substrate/client/consensus/babe/Cargo.toml +++ b/substrate/client/consensus/babe/Cargo.toml @@ -17,41 +17,41 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -async-trait = "0.1.79" -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } -futures = "0.3.30" +async-trait = { workspace = true } +codec = { features = ["derive"], workspace = true, default-features = true } +futures = { workspace = true } log = { workspace = true, default-features = true } -num-bigint = "0.4.3" -num-rational = "0.4.1" -num-traits = "0.2.17" -parking_lot = "0.12.1" +num-bigint = { workspace = true } +num-rational = { workspace = true } +num-traits = { workspace = true, default-features = true } +parking_lot = { workspace = true, default-features = true } thiserror = { workspace = true } -fork-tree = { path = "../../../utils/fork-tree" } -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../../utils/prometheus" } -sc-client-api = { path = "../../api" } -sc-consensus = { path = "../common" } -sc-consensus-epochs = { path = "../epochs" } -sc-consensus-slots = { path = "../slots" } -sc-telemetry = { path = "../../telemetry" } -sc-transaction-pool-api = { path = "../../transaction-pool/api" } -sp-api = { path = "../../../primitives/api" } -sp-application-crypto = { path = "../../../primitives/application-crypto" } -sp-block-builder = { path = "../../../primitives/block-builder" } -sp-blockchain = { path = "../../../primitives/blockchain" } -sp-consensus = { path = "../../../primitives/consensus/common" } -sp-consensus-babe = { path = "../../../primitives/consensus/babe" } -sp-consensus-slots = { path = "../../../primitives/consensus/slots" } -sp-core = { path = "../../../primitives/core" } -sp-crypto-hashing = { path = "../../../primitives/crypto/hashing" } -sp-inherents = { path = "../../../primitives/inherents" } -sp-keystore = { path = "../../../primitives/keystore" } -sp-runtime = { path = "../../../primitives/runtime" } +fork-tree = { workspace = true, default-features = true } +prometheus-endpoint = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } +sc-consensus-epochs = { workspace = true, default-features = true } +sc-consensus-slots = { workspace = true, default-features = true } +sc-telemetry = { workspace = true, default-features = true } +sc-transaction-pool-api = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-application-crypto = { workspace = true, default-features = true } +sp-block-builder = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-consensus-babe = { workspace = true, default-features = true } +sp-consensus-slots = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-crypto-hashing = { workspace = true, default-features = true } +sp-inherents = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } [dev-dependencies] -sc-block-builder = { path = "../../block-builder" } -sp-keyring = { path = "../../../primitives/keyring" } -sc-network-test = { path = "../../network/test" } -sp-timestamp = { path = "../../../primitives/timestamp" } -sp-tracing = { path = "../../../primitives/tracing" } -substrate-test-runtime-client = { path = "../../../test-utils/runtime/client" } -tokio = "1.37" +sc-block-builder = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +sc-network-test = { workspace = true } +sp-timestamp = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +substrate-test-runtime-client = { workspace = true } +tokio = { workspace = true, default-features = true } diff --git a/substrate/client/consensus/babe/rpc/Cargo.toml b/substrate/client/consensus/babe/rpc/Cargo.toml index 4c755df541d70315dea241092145e17c2bd28800..1ef049c3dbcc412ae94bc849b066e2ff154ae57c 100644 --- a/substrate/client/consensus/babe/rpc/Cargo.toml +++ b/substrate/client/consensus/babe/rpc/Cargo.toml @@ -16,27 +16,27 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -jsonrpsee = { version = "0.22.5", features = ["client-core", "macros", "server-core"] } -futures = "0.3.30" +jsonrpsee = { features = ["client-core", "macros", "server-core"], workspace = true } +futures = { workspace = true } serde = { features = ["derive"], workspace = true, default-features = true } thiserror = { workspace = true } -sc-consensus-babe = { path = ".." } -sc-consensus-epochs = { path = "../../epochs" } -sc-rpc-api = { path = "../../../rpc-api" } -sp-api = { path = "../../../../primitives/api" } -sp-application-crypto = { path = "../../../../primitives/application-crypto" } -sp-blockchain = { path = "../../../../primitives/blockchain" } -sp-consensus = { path = "../../../../primitives/consensus/common" } -sp-consensus-babe = { path = "../../../../primitives/consensus/babe" } -sp-core = { path = "../../../../primitives/core" } -sp-keystore = { path = "../../../../primitives/keystore" } -sp-runtime = { path = "../../../../primitives/runtime" } +sc-consensus-babe = { workspace = true, default-features = true } +sc-consensus-epochs = { workspace = true, default-features = true } +sc-rpc-api = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-application-crypto = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-consensus-babe = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } [dev-dependencies] serde_json = { workspace = true, default-features = true } -tokio = "1.37" -sc-consensus = { path = "../../common" } -sc-keystore = { path = "../../../keystore" } -sc-transaction-pool-api = { path = "../../../transaction-pool/api" } -sp-keyring = { path = "../../../../primitives/keyring" } -substrate-test-runtime-client = { path = "../../../../test-utils/runtime/client" } +tokio = { workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } +sc-keystore = { workspace = true, default-features = true } +sc-transaction-pool-api = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +substrate-test-runtime-client = { workspace = true } diff --git a/substrate/client/consensus/babe/src/lib.rs b/substrate/client/consensus/babe/src/lib.rs index 0c85de24004031fce96be35bc413506069093eb1..0c1eb88758644c0d661c25c4feb670c6054781f4 100644 --- a/substrate/client/consensus/babe/src/lib.rs +++ b/substrate/client/consensus/babe/src/lib.rs @@ -1128,7 +1128,7 @@ where CIDP::InherentDataProviders: InherentDataProviderExt + Send + Sync, { async fn verify( - &mut self, + &self, mut block: BlockImportParams, ) -> Result, String> { trace!( @@ -1681,7 +1681,7 @@ where } async fn check_block( - &mut self, + &self, block: BlockCheckParams, ) -> Result { self.inner.check_block(block).await.map_err(Into::into) diff --git a/substrate/client/consensus/babe/src/tests.rs b/substrate/client/consensus/babe/src/tests.rs index 716067ae4000661beab6aeb90772087720d0a5ae..6f805188b9a42d806f45c01715f1a088770c3bfe 100644 --- a/substrate/client/consensus/babe/src/tests.rs +++ b/substrate/client/consensus/babe/src/tests.rs @@ -143,11 +143,11 @@ thread_local! { pub struct PanickingBlockImport(B); #[async_trait::async_trait] -impl> BlockImport for PanickingBlockImport +impl BlockImport for PanickingBlockImport where - B: Send, + BI: BlockImport + Send + Sync, { - type Error = B::Error; + type Error = BI::Error; async fn import_block( &mut self, @@ -157,7 +157,7 @@ where } async fn check_block( - &mut self, + &self, block: BlockCheckParams, ) -> Result { Ok(self.0.check_block(block).await.expect("checking block failed")) @@ -198,7 +198,7 @@ impl Verifier for TestVerifier { /// new set of validators to import. If not, err with an Error-Message /// presented to the User in the logs. async fn verify( - &mut self, + &self, mut block: BlockImportParams, ) -> Result, String> { // apply post-sealing mutations (i.e. stripping seal, if desired). diff --git a/substrate/client/consensus/beefy/Cargo.toml b/substrate/client/consensus/beefy/Cargo.toml index f5528ec5931dbc5d77321e903b57e4ef70349afc..b2031e0d1e077ef1d793faf570698499487aa4b2 100644 --- a/substrate/client/consensus/beefy/Cargo.toml +++ b/substrate/client/consensus/beefy/Cargo.toml @@ -12,46 +12,46 @@ homepage = "https://substrate.io" workspace = true [dependencies] -array-bytes = "6.2.2" -async-channel = "1.8.0" -async-trait = "0.1.79" -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } -fnv = "1.0.6" -futures = "0.3.30" +array-bytes = { workspace = true, default-features = true } +async-channel = { workspace = true } +async-trait = { workspace = true } +codec = { features = ["derive"], workspace = true, default-features = true } +fnv = { workspace = true } +futures = { workspace = true } log = { workspace = true, default-features = true } -parking_lot = "0.12.1" +parking_lot = { workspace = true, default-features = true } thiserror = { workspace = true } -wasm-timer = "0.2.5" -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../../utils/prometheus" } -sc-client-api = { path = "../../api" } -sc-consensus = { path = "../common" } -sc-network = { path = "../../network" } -sc-network-gossip = { path = "../../network-gossip" } -sc-network-sync = { path = "../../network/sync" } -sc-network-types = { path = "../../network/types" } -sc-utils = { path = "../../utils" } -sp-api = { path = "../../../primitives/api" } -sp-application-crypto = { path = "../../../primitives/application-crypto" } -sp-arithmetic = { path = "../../../primitives/arithmetic" } -sp-blockchain = { path = "../../../primitives/blockchain" } -sp-consensus = { path = "../../../primitives/consensus/common" } -sp-consensus-beefy = { path = "../../../primitives/consensus/beefy" } -sp-core = { path = "../../../primitives/core" } -sp-crypto-hashing = { path = "../../../primitives/crypto/hashing" } -sp-keystore = { path = "../../../primitives/keystore" } -sp-runtime = { path = "../../../primitives/runtime" } -tokio = "1.37" +wasm-timer = { workspace = true } +prometheus-endpoint = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sc-network-gossip = { workspace = true, default-features = true } +sc-network-sync = { workspace = true, default-features = true } +sc-network-types = { workspace = true, default-features = true } +sc-utils = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-application-crypto = { workspace = true, default-features = true } +sp-arithmetic = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-consensus-beefy = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-crypto-hashing = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +tokio = { workspace = true, default-features = true } [dev-dependencies] serde = { workspace = true, default-features = true } -tempfile = "3.1.0" -sc-block-builder = { path = "../../block-builder" } -sc-network-test = { path = "../../network/test" } -sp-consensus-grandpa = { path = "../../../primitives/consensus/grandpa" } -sp-keyring = { path = "../../../primitives/keyring" } -sp-mmr-primitives = { path = "../../../primitives/merkle-mountain-range" } -sp-tracing = { path = "../../../primitives/tracing" } -substrate-test-runtime-client = { path = "../../../test-utils/runtime/client" } +tempfile = { workspace = true } +sc-block-builder = { workspace = true, default-features = true } +sc-network-test = { workspace = true } +sp-consensus-grandpa = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +sp-mmr-primitives = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +substrate-test-runtime-client = { workspace = true } [features] # This feature adds BLS crypto primitives. It should not be used in production since diff --git a/substrate/client/consensus/beefy/rpc/Cargo.toml b/substrate/client/consensus/beefy/rpc/Cargo.toml index 84f90622b5c14f8b7cba19749c877a6ce53ec226..7869f5a336b1135bb471fc584b8f826e17fb9d02 100644 --- a/substrate/client/consensus/beefy/rpc/Cargo.toml +++ b/substrate/client/consensus/beefy/rpc/Cargo.toml @@ -12,22 +12,22 @@ homepage = "https://substrate.io" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } -futures = "0.3.30" -jsonrpsee = { version = "0.22.5", features = ["client-core", "macros", "server-core"] } +codec = { features = ["derive"], workspace = true, default-features = true } +futures = { workspace = true } +jsonrpsee = { features = ["client-core", "macros", "server-core"], workspace = true } log = { workspace = true, default-features = true } -parking_lot = "0.12.1" +parking_lot = { workspace = true, default-features = true } serde = { features = ["derive"], workspace = true, default-features = true } thiserror = { workspace = true } -sc-consensus-beefy = { path = ".." } -sp-consensus-beefy = { path = "../../../../primitives/consensus/beefy" } -sc-rpc = { path = "../../../rpc" } -sp-core = { path = "../../../../primitives/core" } -sp-runtime = { path = "../../../../primitives/runtime" } -sp-application-crypto = { path = "../../../../primitives/application-crypto" } +sc-consensus-beefy = { workspace = true, default-features = true } +sp-consensus-beefy = { workspace = true, default-features = true } +sc-rpc = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-application-crypto = { workspace = true, default-features = true } [dev-dependencies] serde_json = { workspace = true, default-features = true } -sc-rpc = { path = "../../../rpc", features = ["test-helpers"] } -substrate-test-runtime-client = { path = "../../../../test-utils/runtime/client" } -tokio = { version = "1.22.0", features = ["macros"] } +sc-rpc = { features = ["test-helpers"], workspace = true, default-features = true } +substrate-test-runtime-client = { workspace = true } +tokio = { features = ["macros"], workspace = true, default-features = true } diff --git a/substrate/client/consensus/beefy/src/import.rs b/substrate/client/consensus/beefy/src/import.rs index c01fb3db4845eb9e413e0dbe781ae395a3b31217..8480268529338fe09333719a2e26141e37c792ea 100644 --- a/substrate/client/consensus/beefy/src/import.rs +++ b/substrate/client/consensus/beefy/src/import.rs @@ -192,7 +192,7 @@ where } async fn check_block( - &mut self, + &self, block: BlockCheckParams, ) -> Result { self.inner.check_block(block).await diff --git a/substrate/client/consensus/common/Cargo.toml b/substrate/client/consensus/common/Cargo.toml index 6d642ec78fefa88692503152595f8548d715426c..a6f59e600f269c67ab87f295c268f3d185dafcf4 100644 --- a/substrate/client/consensus/common/Cargo.toml +++ b/substrate/client/consensus/common/Cargo.toml @@ -16,24 +16,23 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -async-trait = "0.1.79" -futures = { version = "0.3.30", features = ["thread-pool"] } -futures-timer = "3.0.1" +async-trait = { workspace = true } +futures = { features = ["thread-pool"], workspace = true } log = { workspace = true, default-features = true } -mockall = "0.11.3" -parking_lot = "0.12.1" +mockall = { workspace = true } +parking_lot = { workspace = true, default-features = true } serde = { features = ["derive"], workspace = true, default-features = true } thiserror = { workspace = true } -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../../utils/prometheus" } -sc-client-api = { path = "../../api" } -sc-network-types = { path = "../../network/types" } -sc-utils = { path = "../../utils" } -sp-api = { path = "../../../primitives/api" } -sp-blockchain = { path = "../../../primitives/blockchain" } -sp-consensus = { path = "../../../primitives/consensus/common" } -sp-core = { path = "../../../primitives/core" } -sp-runtime = { path = "../../../primitives/runtime" } -sp-state-machine = { path = "../../../primitives/state-machine" } +prometheus-endpoint = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-network-types = { workspace = true, default-features = true } +sc-utils = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-state-machine = { workspace = true, default-features = true } [dev-dependencies] -sp-test-primitives = { path = "../../../primitives/test-primitives" } +sp-test-primitives = { workspace = true } diff --git a/substrate/client/consensus/common/src/block_import.rs b/substrate/client/consensus/common/src/block_import.rs index d91851aea62cf4564464b67bcd0bdcd5d712e139..c5adbb5a5fca0634b1cdb038c569a1de312cf859 100644 --- a/substrate/client/consensus/common/src/block_import.rs +++ b/substrate/client/consensus/common/src/block_import.rs @@ -307,10 +307,7 @@ pub trait BlockImport { type Error: std::error::Error + Send + 'static; /// Check block preconditions. - async fn check_block( - &mut self, - block: BlockCheckParams, - ) -> Result; + async fn check_block(&self, block: BlockCheckParams) -> Result; /// Import a block. async fn import_block( @@ -324,10 +321,7 @@ impl BlockImport for crate::import_queue::BoxBlockImport { type Error = sp_consensus::error::Error; /// Check block preconditions. - async fn check_block( - &mut self, - block: BlockCheckParams, - ) -> Result { + async fn check_block(&self, block: BlockCheckParams) -> Result { (**self).check_block(block).await } @@ -348,10 +342,7 @@ where { type Error = E; - async fn check_block( - &mut self, - block: BlockCheckParams, - ) -> Result { + async fn check_block(&self, block: BlockCheckParams) -> Result { (&**self).check_block(block).await } diff --git a/substrate/client/consensus/common/src/import_queue.rs b/substrate/client/consensus/common/src/import_queue.rs index 371465536c35a5feea5d6e157eb3ee8b019b94db..35fc8ad4a402e72d9f6c8d110a468bea5f3c5195 100644 --- a/substrate/client/consensus/common/src/import_queue.rs +++ b/substrate/client/consensus/common/src/import_queue.rs @@ -28,6 +28,10 @@ //! queues to be instantiated simply. use log::{debug, trace}; +use std::{ + fmt, + time::{Duration, Instant}, +}; use sp_consensus::{error::Error as ConsensusError, BlockOrigin}; use sp_runtime::{ @@ -93,18 +97,18 @@ pub struct IncomingBlock { /// Verify a justification of a block #[async_trait::async_trait] -pub trait Verifier: Send { +pub trait Verifier: Send + Sync { /// Verify the given block data and return the `BlockImportParams` to /// continue the block import process. - async fn verify(&mut self, block: BlockImportParams) - -> Result, String>; + async fn verify(&self, block: BlockImportParams) -> Result, String>; } /// Blocks import queue API. /// /// The `import_*` methods can be called in order to send elements for the import queue to verify. pub trait ImportQueueService: Send { - /// Import bunch of blocks. + /// Import bunch of blocks, every next block must be an ancestor of the previous block in the + /// list. fn import_blocks(&mut self, origin: BlockOrigin, blocks: Vec>); /// Import block justifications. @@ -165,16 +169,16 @@ pub trait Link: Send { /// Block import successful result. #[derive(Debug, PartialEq)] -pub enum BlockImportStatus { +pub enum BlockImportStatus { /// Imported known block. - ImportedKnown(N, Option), + ImportedKnown(BlockNumber, Option), /// Imported unknown block. - ImportedUnknown(N, ImportedAux, Option), + ImportedUnknown(BlockNumber, ImportedAux, Option), } -impl BlockImportStatus { +impl BlockImportStatus { /// Returns the imported block number. - pub fn number(&self) -> &N { + pub fn number(&self) -> &BlockNumber { match self { BlockImportStatus::ImportedKnown(n, _) | BlockImportStatus::ImportedUnknown(n, _, _) => n, @@ -223,44 +227,30 @@ pub async fn import_single_block>( block: IncomingBlock, verifier: &mut V, ) -> BlockImportResult { - import_single_block_metered(import_handle, block_origin, block, verifier, None).await + match verify_single_block_metered(import_handle, block_origin, block, verifier, None).await? { + SingleBlockVerificationOutcome::Imported(import_status) => Ok(import_status), + SingleBlockVerificationOutcome::Verified(import_parameters) => + import_single_block_metered(import_handle, import_parameters, None).await, + } } -/// Single block import function with metering. -pub(crate) async fn import_single_block_metered>( - import_handle: &mut impl BlockImport, - block_origin: BlockOrigin, - block: IncomingBlock, - verifier: &mut V, - metrics: Option, -) -> BlockImportResult { - let peer = block.origin; - - let (header, justifications) = match (block.header, block.justifications) { - (Some(header), justifications) => (header, justifications), - (None, _) => { - if let Some(ref peer) = peer { - debug!(target: LOG_TARGET, "Header {} was not provided by {} ", block.hash, peer); - } else { - debug!(target: LOG_TARGET, "Header {} was not provided ", block.hash); - } - return Err(BlockImportError::IncompleteHeader(peer)) - }, - }; - - trace!(target: LOG_TARGET, "Header {} has {:?} logs", block.hash, header.digest().logs().len()); - - let number = *header.number(); - let hash = block.hash; - let parent_hash = *header.parent_hash(); - - let import_handler = |import| match import { +fn import_handler( + number: NumberFor, + hash: Block::Hash, + parent_hash: Block::Hash, + block_origin: Option, + import: Result, +) -> Result>, BlockImportError> +where + Block: BlockT, +{ + match import { Ok(ImportResult::AlreadyInChain) => { trace!(target: LOG_TARGET, "Block already in chain {}: {:?}", number, hash); - Ok(BlockImportStatus::ImportedKnown(number, peer)) + Ok(BlockImportStatus::ImportedKnown(number, block_origin)) }, Ok(ImportResult::Imported(aux)) => - Ok(BlockImportStatus::ImportedUnknown(number, aux, peer)), + Ok(BlockImportStatus::ImportedUnknown(number, aux, block_origin)), Ok(ImportResult::MissingState) => { debug!( target: LOG_TARGET, @@ -277,15 +267,60 @@ pub(crate) async fn import_single_block_metered>( }, Ok(ImportResult::KnownBad) => { debug!(target: LOG_TARGET, "Peer gave us a bad block {}: {:?}", number, hash); - Err(BlockImportError::BadBlock(peer)) + Err(BlockImportError::BadBlock(block_origin)) }, Err(e) => { debug!(target: LOG_TARGET, "Error importing block {}: {:?}: {}", number, hash, e); Err(BlockImportError::Other(e)) }, + } +} + +pub(crate) enum SingleBlockVerificationOutcome { + /// Block is already imported. + Imported(BlockImportStatus>), + /// Block is verified, but needs to be imported. + Verified(SingleBlockImportParameters), +} + +pub(crate) struct SingleBlockImportParameters { + import_block: BlockImportParams, + hash: Block::Hash, + block_origin: Option, + verification_time: Duration, +} + +/// Single block import function with metering. +pub(crate) async fn verify_single_block_metered>( + import_handle: &impl BlockImport, + block_origin: BlockOrigin, + block: IncomingBlock, + verifier: &mut V, + metrics: Option<&Metrics>, +) -> Result, BlockImportError> { + let peer = block.origin; + let justifications = block.justifications; + + let Some(header) = block.header else { + if let Some(ref peer) = peer { + debug!(target: LOG_TARGET, "Header {} was not provided by {peer} ", block.hash); + } else { + debug!(target: LOG_TARGET, "Header {} was not provided ", block.hash); + } + return Err(BlockImportError::IncompleteHeader(peer)) }; - match import_handler( + trace!(target: LOG_TARGET, "Header {} has {:?} logs", block.hash, header.digest().logs().len()); + + let number = *header.number(); + let hash = block.hash; + let parent_hash = *header.parent_hash(); + + match import_handler::( + number, + hash, + parent_hash, + peer, import_handle .check_block(BlockCheckParams { hash, @@ -298,10 +333,13 @@ pub(crate) async fn import_single_block_metered>( .await, )? { BlockImportStatus::ImportedUnknown { .. } => (), - r => return Ok(r), // Any other successful result means that the block is already imported. + r => { + // Any other successful result means that the block is already imported. + return Ok(SingleBlockVerificationOutcome::Imported(r)) + }, } - let started = std::time::Instant::now(); + let started = Instant::now(); let mut import_block = BlockImportParams::new(block_origin, header); import_block.body = block.body; @@ -332,19 +370,42 @@ pub(crate) async fn import_single_block_metered>( } else { trace!(target: LOG_TARGET, "Verifying {}({}) failed: {}", number, hash, msg); } - if let Some(metrics) = metrics.as_ref() { + if let Some(metrics) = metrics { metrics.report_verification(false, started.elapsed()); } BlockImportError::VerificationFailed(peer, msg) })?; - if let Some(metrics) = metrics.as_ref() { - metrics.report_verification(true, started.elapsed()); + let verification_time = started.elapsed(); + if let Some(metrics) = metrics { + metrics.report_verification(true, verification_time); } + Ok(SingleBlockVerificationOutcome::Verified(SingleBlockImportParameters { + import_block, + hash, + block_origin: peer, + verification_time, + })) +} + +pub(crate) async fn import_single_block_metered( + import_handle: &mut impl BlockImport, + import_parameters: SingleBlockImportParameters, + metrics: Option<&Metrics>, +) -> BlockImportResult { + let started = Instant::now(); + + let SingleBlockImportParameters { import_block, hash, block_origin, verification_time } = + import_parameters; + + let number = *import_block.header.number(); + let parent_hash = *import_block.header.parent_hash(); + let imported = import_handle.import_block(import_block).await; - if let Some(metrics) = metrics.as_ref() { - metrics.report_verification_and_import(started.elapsed()); + if let Some(metrics) = metrics { + metrics.report_verification_and_import(started.elapsed() + verification_time); } - import_handler(imported) + + import_handler::(number, hash, parent_hash, block_origin, imported) } diff --git a/substrate/client/consensus/common/src/import_queue/basic_queue.rs b/substrate/client/consensus/common/src/import_queue/basic_queue.rs index f4f618d1b31825e17987130b20a96c21e475b098..05f2b252796146f62ba7c258b208fa4c2eb4a3d1 100644 --- a/substrate/client/consensus/common/src/import_queue/basic_queue.rs +++ b/substrate/client/consensus/common/src/import_queue/basic_queue.rs @@ -19,7 +19,6 @@ use futures::{ prelude::*, task::{Context, Poll}, }; -use futures_timer::Delay; use log::{debug, trace}; use prometheus_endpoint::Registry; use sc_utils::mpsc::{tracing_unbounded, TracingUnboundedReceiver, TracingUnboundedSender}; @@ -28,14 +27,14 @@ use sp_runtime::{ traits::{Block as BlockT, Header as HeaderT, NumberFor}, Justification, Justifications, }; -use std::{pin::Pin, time::Duration}; +use std::pin::Pin; use crate::{ import_queue::{ buffered_link::{self, BufferedLinkReceiver, BufferedLinkSender}, - import_single_block_metered, BlockImportError, BlockImportStatus, BoxBlockImport, - BoxJustificationImport, ImportQueue, ImportQueueService, IncomingBlock, Link, - RuntimeOrigin, Verifier, LOG_TARGET, + import_single_block_metered, verify_single_block_metered, BlockImportError, + BlockImportStatus, BoxBlockImport, BoxJustificationImport, ImportQueue, ImportQueueService, + IncomingBlock, Link, RuntimeOrigin, SingleBlockVerificationOutcome, Verifier, LOG_TARGET, }, metrics::Metrics, }; @@ -61,13 +60,16 @@ impl BasicQueue { /// Instantiate a new basic queue, with given verifier. /// /// This creates a background task, and calls `on_start` on the justification importer. - pub fn new>( + pub fn new( verifier: V, block_import: BoxBlockImport, justification_import: Option>, spawner: &impl sp_core::traits::SpawnEssentialNamed, prometheus_registry: Option<&Registry>, - ) -> Self { + ) -> Self + where + V: Verifier + 'static, + { let (result_sender, result_port) = buffered_link::buffered_link(100_000); let metrics = prometheus_registry.and_then(|r| { @@ -224,7 +226,6 @@ async fn block_import_process( mut result_sender: BufferedLinkSender, mut block_import_receiver: TracingUnboundedReceiver>, metrics: Option, - delay_between_blocks: Duration, ) { loop { let worker_messages::ImportBlocks(origin, blocks) = match block_import_receiver.next().await @@ -239,15 +240,9 @@ async fn block_import_process( }, }; - let res = import_many_blocks( - &mut block_import, - origin, - blocks, - &mut verifier, - delay_between_blocks, - metrics.clone(), - ) - .await; + let res = + import_many_blocks(&mut block_import, origin, blocks, &mut verifier, metrics.clone()) + .await; result_sender.blocks_processed(res.imported, res.block_count, res.results); } @@ -260,7 +255,7 @@ struct BlockImportWorker { } impl BlockImportWorker { - fn new>( + fn new( result_sender: BufferedLinkSender, verifier: V, block_import: BoxBlockImport, @@ -270,19 +265,20 @@ impl BlockImportWorker { impl Future + Send, TracingUnboundedSender>, TracingUnboundedSender>, - ) { + ) + where + V: Verifier + 'static, + { use worker_messages::*; let (justification_sender, mut justification_port) = tracing_unbounded("mpsc_import_queue_worker_justification", 100_000); - let (block_import_sender, block_import_port) = + let (block_import_sender, block_import_receiver) = tracing_unbounded("mpsc_import_queue_worker_blocks", 100_000); let mut worker = BlockImportWorker { result_sender, justification_import, metrics }; - let delay_between_blocks = Duration::default(); - let future = async move { // Let's initialize `justification_import` if let Some(justification_import) = worker.justification_import.as_mut() { @@ -295,9 +291,8 @@ impl BlockImportWorker { block_import, verifier, worker.result_sender.clone(), - block_import_port, + block_import_receiver, worker.metrics.clone(), - delay_between_blocks, ); futures::pin_mut!(block_import_process); @@ -394,7 +389,6 @@ async fn import_many_blocks>( blocks_origin: BlockOrigin, blocks: Vec>, verifier: &mut V, - delay_between_blocks: Duration, metrics: Option, ) -> ImportManyBlocksResult { let count = blocks.len(); @@ -431,15 +425,22 @@ async fn import_many_blocks>( let import_result = if has_error { Err(BlockImportError::Cancelled) } else { - // The actual import. - import_single_block_metered( + let verification_fut = verify_single_block_metered( import_handle, blocks_origin, block, verifier, - metrics.clone(), - ) - .await + metrics.as_ref(), + ); + match verification_fut.await { + Ok(SingleBlockVerificationOutcome::Imported(import_status)) => Ok(import_status), + Ok(SingleBlockVerificationOutcome::Verified(import_parameters)) => { + // The actual import. + import_single_block_metered(import_handle, import_parameters, metrics.as_ref()) + .await + }, + Err(e) => Err(e), + } }; if let Some(metrics) = metrics.as_ref() { @@ -460,11 +461,7 @@ async fn import_many_blocks>( results.push((import_result, block_hash)); - if delay_between_blocks != Duration::default() && !has_error { - Delay::new(delay_between_blocks).await; - } else { - Yield::new().await - } + Yield::new().await } } @@ -510,7 +507,7 @@ mod tests { #[async_trait::async_trait] impl Verifier for () { async fn verify( - &mut self, + &self, block: BlockImportParams, ) -> Result, String> { Ok(BlockImportParams::new(block.origin, block.header)) @@ -522,7 +519,7 @@ mod tests { type Error = sp_consensus::Error; async fn check_block( - &mut self, + &self, _block: BlockCheckParams, ) -> Result { Ok(ImportResult::imported(false)) diff --git a/substrate/client/consensus/epochs/Cargo.toml b/substrate/client/consensus/epochs/Cargo.toml index e409e171e477c2452903a09ee78916808a210011..127cc9ebec207b27f9bf2f54c9e07184b290ebae 100644 --- a/substrate/client/consensus/epochs/Cargo.toml +++ b/substrate/client/consensus/epochs/Cargo.toml @@ -16,9 +16,9 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } -fork-tree = { path = "../../../utils/fork-tree" } -sc-client-api = { path = "../../api" } -sc-consensus = { path = "../common" } -sp-blockchain = { path = "../../../primitives/blockchain" } -sp-runtime = { path = "../../../primitives/runtime" } +codec = { features = ["derive"], workspace = true, default-features = true } +fork-tree = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } diff --git a/substrate/client/consensus/grandpa/Cargo.toml b/substrate/client/consensus/grandpa/Cargo.toml index b03a263ae0a37d3a304b54096ad71a06b89c99bd..e49c7c9f0d7a93e727453592d7f300d54bc96acf 100644 --- a/substrate/client/consensus/grandpa/Cargo.toml +++ b/substrate/client/consensus/grandpa/Cargo.toml @@ -17,51 +17,51 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -ahash = "0.8.2" -array-bytes = "6.2.2" -async-trait = "0.1.79" -dyn-clone = "1.0" -finality-grandpa = { version = "0.16.2", features = ["derive-codec"] } -futures = "0.3.30" -futures-timer = "3.0.1" +ahash = { workspace = true } +array-bytes = { workspace = true, default-features = true } +async-trait = { workspace = true } +dyn-clone = { workspace = true } +finality-grandpa = { features = ["derive-codec"], workspace = true, default-features = true } +futures = { workspace = true } +futures-timer = { workspace = true } log = { workspace = true, default-features = true } -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } -parking_lot = "0.12.1" -rand = "0.8.5" +codec = { features = ["derive"], workspace = true, default-features = true } +parking_lot = { workspace = true, default-features = true } +rand = { workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } thiserror = { workspace = true } -fork-tree = { path = "../../../utils/fork-tree" } -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../../utils/prometheus" } -sc-block-builder = { path = "../../block-builder" } -sc-chain-spec = { path = "../../chain-spec" } -sc-client-api = { path = "../../api" } -sc-transaction-pool-api = { path = "../../transaction-pool/api" } -sc-consensus = { path = "../common" } -sc-network = { path = "../../network" } -sc-network-gossip = { path = "../../network-gossip" } -sc-network-common = { path = "../../network/common" } -sc-network-sync = { path = "../../network/sync" } -sc-network-types = { path = "../../network/types" } -sc-telemetry = { path = "../../telemetry" } -sc-utils = { path = "../../utils" } -sp-api = { path = "../../../primitives/api" } -sp-application-crypto = { path = "../../../primitives/application-crypto" } -sp-arithmetic = { path = "../../../primitives/arithmetic" } -sp-blockchain = { path = "../../../primitives/blockchain" } -sp-consensus = { path = "../../../primitives/consensus/common" } -sp-core = { path = "../../../primitives/core" } -sp-crypto-hashing = { path = "../../../primitives/crypto/hashing" } -sp-consensus-grandpa = { path = "../../../primitives/consensus/grandpa" } -sp-keystore = { path = "../../../primitives/keystore" } -sp-runtime = { path = "../../../primitives/runtime" } +fork-tree = { workspace = true, default-features = true } +prometheus-endpoint = { workspace = true, default-features = true } +sc-block-builder = { workspace = true, default-features = true } +sc-chain-spec = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-transaction-pool-api = { workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sc-network-gossip = { workspace = true, default-features = true } +sc-network-common = { workspace = true, default-features = true } +sc-network-sync = { workspace = true, default-features = true } +sc-network-types = { workspace = true, default-features = true } +sc-telemetry = { workspace = true, default-features = true } +sc-utils = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-application-crypto = { workspace = true, default-features = true } +sp-arithmetic = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-crypto-hashing = { workspace = true, default-features = true } +sp-consensus-grandpa = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } [dev-dependencies] -assert_matches = "1.3.0" -finality-grandpa = { version = "0.16.2", features = ["derive-codec", "test-helpers"] } +assert_matches = { workspace = true } +finality-grandpa = { features = ["derive-codec", "test-helpers"], workspace = true, default-features = true } serde = { workspace = true, default-features = true } -tokio = "1.37" -sc-network = { path = "../../network" } -sc-network-test = { path = "../../network/test" } -sp-keyring = { path = "../../../primitives/keyring" } -sp-tracing = { path = "../../../primitives/tracing" } -substrate-test-runtime-client = { path = "../../../test-utils/runtime/client" } +tokio = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sc-network-test = { workspace = true } +sp-keyring = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +substrate-test-runtime-client = { workspace = true } diff --git a/substrate/client/consensus/grandpa/rpc/Cargo.toml b/substrate/client/consensus/grandpa/rpc/Cargo.toml index a9437a9be07544060e2b05aff4a86e0edcc3dcc5..0215fe2e3e64244ac5143dff0b18237fedc23bba 100644 --- a/substrate/client/consensus/grandpa/rpc/Cargo.toml +++ b/substrate/client/consensus/grandpa/rpc/Cargo.toml @@ -13,25 +13,25 @@ homepage = "https://substrate.io" workspace = true [dependencies] -finality-grandpa = { version = "0.16.2", features = ["derive-codec"] } -futures = "0.3.30" -jsonrpsee = { version = "0.22.5", features = ["client-core", "macros", "server-core"] } +finality-grandpa = { features = ["derive-codec"], workspace = true, default-features = true } +futures = { workspace = true } +jsonrpsee = { features = ["client-core", "macros", "server-core"], workspace = true } log = { workspace = true, default-features = true } -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } +codec = { features = ["derive"], workspace = true, default-features = true } serde = { features = ["derive"], workspace = true, default-features = true } thiserror = { workspace = true } -sc-client-api = { path = "../../../api" } -sc-consensus-grandpa = { path = ".." } -sc-rpc = { path = "../../../rpc" } -sp-blockchain = { path = "../../../../primitives/blockchain" } -sp-core = { path = "../../../../primitives/core" } -sp-runtime = { path = "../../../../primitives/runtime" } +sc-client-api = { workspace = true, default-features = true } +sc-consensus-grandpa = { workspace = true, default-features = true } +sc-rpc = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } [dev-dependencies] -sc-block-builder = { path = "../../../block-builder" } -sc-rpc = { path = "../../../rpc", features = ["test-helpers"] } -sp-core = { path = "../../../../primitives/core" } -sp-consensus-grandpa = { path = "../../../../primitives/consensus/grandpa" } -sp-keyring = { path = "../../../../primitives/keyring" } -substrate-test-runtime-client = { path = "../../../../test-utils/runtime/client" } -tokio = { version = "1.22.0", features = ["macros"] } +sc-block-builder = { workspace = true, default-features = true } +sc-rpc = { features = ["test-helpers"], workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-consensus-grandpa = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +substrate-test-runtime-client = { workspace = true } +tokio = { features = ["macros"], workspace = true, default-features = true } diff --git a/substrate/client/consensus/grandpa/src/import.rs b/substrate/client/consensus/grandpa/src/import.rs index b594c0f678cea64efae7980ee17a9876ce6d5013..8b7b02f180ecd582063c5b02e1f4217c0a507e13 100644 --- a/substrate/client/consensus/grandpa/src/import.rs +++ b/substrate/client/consensus/grandpa/src/import.rs @@ -518,7 +518,7 @@ where Client: ClientForGrandpa, Client::Api: GrandpaApi, for<'a> &'a Client: BlockImport, - SC: Send, + SC: Send + Sync, { type Error = ConsensusError; @@ -697,7 +697,7 @@ where } async fn check_block( - &mut self, + &self, block: BlockCheckParams, ) -> Result { self.inner.check_block(block).await diff --git a/substrate/client/consensus/manual-seal/Cargo.toml b/substrate/client/consensus/manual-seal/Cargo.toml index 33f5bf1f8c1501e0e366edab6c3606716aeb47ab..3d74eda8fa01f838b063c134163a61a8d98af081 100644 --- a/substrate/client/consensus/manual-seal/Cargo.toml +++ b/substrate/client/consensus/manual-seal/Cargo.toml @@ -16,37 +16,37 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -jsonrpsee = { version = "0.22.5", features = ["client-core", "macros", "server-core"] } -assert_matches = "1.3.0" -async-trait = "0.1.79" -codec = { package = "parity-scale-codec", version = "3.6.12" } -futures = "0.3.30" -futures-timer = "3.0.1" +jsonrpsee = { features = ["client-core", "macros", "server-core"], workspace = true } +assert_matches = { workspace = true } +async-trait = { workspace = true } +codec = { workspace = true, default-features = true } +futures = { workspace = true } +futures-timer = { workspace = true } log = { workspace = true, default-features = true } serde = { features = ["derive"], workspace = true, default-features = true } thiserror = { workspace = true } -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../../utils/prometheus" } -sc-client-api = { path = "../../api" } -sc-consensus = { path = "../common" } -sc-consensus-aura = { path = "../aura" } -sc-consensus-babe = { path = "../babe" } -sc-consensus-epochs = { path = "../epochs" } -sc-transaction-pool = { path = "../../transaction-pool" } -sc-transaction-pool-api = { path = "../../transaction-pool/api" } -sp-api = { path = "../../../primitives/api" } -sp-blockchain = { path = "../../../primitives/blockchain" } -sp-consensus = { path = "../../../primitives/consensus/common" } -sp-consensus-aura = { path = "../../../primitives/consensus/aura" } -sp-consensus-babe = { path = "../../../primitives/consensus/babe" } -sp-consensus-slots = { path = "../../../primitives/consensus/slots" } -sp-core = { path = "../../../primitives/core" } -sp-inherents = { path = "../../../primitives/inherents" } -sp-keystore = { path = "../../../primitives/keystore" } -sp-runtime = { path = "../../../primitives/runtime" } -sp-timestamp = { path = "../../../primitives/timestamp" } +prometheus-endpoint = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } +sc-consensus-aura = { workspace = true, default-features = true } +sc-consensus-babe = { workspace = true, default-features = true } +sc-consensus-epochs = { workspace = true, default-features = true } +sc-transaction-pool = { workspace = true, default-features = true } +sc-transaction-pool-api = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-consensus-aura = { workspace = true, default-features = true } +sp-consensus-babe = { workspace = true, default-features = true } +sp-consensus-slots = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-inherents = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-timestamp = { workspace = true, default-features = true } [dev-dependencies] -tokio = { version = "1.22.0", features = ["macros", "rt-multi-thread"] } -sc-basic-authorship = { path = "../../basic-authorship" } -substrate-test-runtime-client = { path = "../../../test-utils/runtime/client" } -substrate-test-runtime-transaction-pool = { path = "../../../test-utils/runtime/transaction-pool" } +tokio = { features = ["macros", "rt-multi-thread"], workspace = true, default-features = true } +sc-basic-authorship = { workspace = true, default-features = true } +substrate-test-runtime-client = { workspace = true } +substrate-test-runtime-transaction-pool = { workspace = true } diff --git a/substrate/client/consensus/manual-seal/src/consensus/babe.rs b/substrate/client/consensus/manual-seal/src/consensus/babe.rs index bc56ce0227142fee2c001c39ce8d31cd9e6fb9b5..a68e46f0134d655d1b034b2b4a40727627724164 100644 --- a/substrate/client/consensus/manual-seal/src/consensus/babe.rs +++ b/substrate/client/consensus/manual-seal/src/consensus/babe.rs @@ -96,7 +96,7 @@ where C: HeaderBackend + HeaderMetadata, { async fn verify( - &mut self, + &self, mut import_params: BlockImportParams, ) -> Result, String> { import_params.finalized = false; diff --git a/substrate/client/consensus/manual-seal/src/lib.rs b/substrate/client/consensus/manual-seal/src/lib.rs index 8fc7e7ecab2f45cf8359c2f449dde3b480bb3ad3..39f8f8609d8d7f35867cc8108ad6667263fe5b74 100644 --- a/substrate/client/consensus/manual-seal/src/lib.rs +++ b/substrate/client/consensus/manual-seal/src/lib.rs @@ -65,7 +65,7 @@ struct ManualSealVerifier; #[async_trait::async_trait] impl Verifier for ManualSealVerifier { async fn verify( - &mut self, + &self, mut block: BlockImportParams, ) -> Result, String> { block.finalized = false; diff --git a/substrate/client/consensus/pow/Cargo.toml b/substrate/client/consensus/pow/Cargo.toml index 51a2be1b6cf5d4be2d5a5c3af6b0e6ea2bc25406..f2a071ec25c2c3fb97e64229e2fac662532d5969 100644 --- a/substrate/client/consensus/pow/Cargo.toml +++ b/substrate/client/consensus/pow/Cargo.toml @@ -16,21 +16,21 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -async-trait = "0.1.79" -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } -futures = "0.3.30" -futures-timer = "3.0.1" +async-trait = { workspace = true } +codec = { features = ["derive"], workspace = true, default-features = true } +futures = { workspace = true } +futures-timer = { workspace = true } log = { workspace = true, default-features = true } -parking_lot = "0.12.1" +parking_lot = { workspace = true, default-features = true } thiserror = { workspace = true } -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../../utils/prometheus" } -sc-client-api = { path = "../../api" } -sc-consensus = { path = "../common" } -sp-api = { path = "../../../primitives/api" } -sp-block-builder = { path = "../../../primitives/block-builder" } -sp-blockchain = { path = "../../../primitives/blockchain" } -sp-consensus = { path = "../../../primitives/consensus/common" } -sp-consensus-pow = { path = "../../../primitives/consensus/pow" } -sp-core = { path = "../../../primitives/core" } -sp-inherents = { path = "../../../primitives/inherents" } -sp-runtime = { path = "../../../primitives/runtime" } +prometheus-endpoint = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-block-builder = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-consensus-pow = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-inherents = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } diff --git a/substrate/client/consensus/pow/src/lib.rs b/substrate/client/consensus/pow/src/lib.rs index ee5c1dfc6f11a26599c0f01efee9224caded43cd..50e9533abb36ab24e5d4942d154a378f84c4beec 100644 --- a/substrate/client/consensus/pow/src/lib.rs +++ b/substrate/client/consensus/pow/src/lib.rs @@ -312,10 +312,7 @@ where { type Error = ConsensusError; - async fn check_block( - &mut self, - block: BlockCheckParams, - ) -> Result { + async fn check_block(&self, block: BlockCheckParams) -> Result { self.inner.check_block(block).await.map_err(Into::into) } @@ -442,7 +439,7 @@ where Algorithm::Difficulty: 'static + Send, { async fn verify( - &mut self, + &self, mut block: BlockImportParams, ) -> Result, String> { let hash = block.header.hash(); diff --git a/substrate/client/consensus/slots/Cargo.toml b/substrate/client/consensus/slots/Cargo.toml index 8e88ee68d7d739a888f3b0e32b7a8fee3ac1e41c..2b795b13f8e338d6ed982ef2bd261e76336e683d 100644 --- a/substrate/client/consensus/slots/Cargo.toml +++ b/substrate/client/consensus/slots/Cargo.toml @@ -17,22 +17,22 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -async-trait = "0.1.79" -codec = { package = "parity-scale-codec", version = "3.6.12" } -futures = "0.3.30" -futures-timer = "3.0.1" +async-trait = { workspace = true } +codec = { workspace = true, default-features = true } +futures = { workspace = true } +futures-timer = { workspace = true } log = { workspace = true, default-features = true } -sc-client-api = { path = "../../api" } -sc-consensus = { path = "../common" } -sc-telemetry = { path = "../../telemetry" } -sp-arithmetic = { path = "../../../primitives/arithmetic" } -sp-blockchain = { path = "../../../primitives/blockchain" } -sp-consensus = { path = "../../../primitives/consensus/common" } -sp-consensus-slots = { path = "../../../primitives/consensus/slots" } -sp-core = { path = "../../../primitives/core" } -sp-inherents = { path = "../../../primitives/inherents" } -sp-runtime = { path = "../../../primitives/runtime" } -sp-state-machine = { path = "../../../primitives/state-machine" } +sc-client-api = { workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } +sc-telemetry = { workspace = true, default-features = true } +sp-arithmetic = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-consensus-slots = { workspace = true, default-features = true } +sp-core = { 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 } [dev-dependencies] -substrate-test-runtime-client = { path = "../../../test-utils/runtime/client" } +substrate-test-runtime-client = { workspace = true } diff --git a/substrate/client/db/Cargo.toml b/substrate/client/db/Cargo.toml index b10c42d50f0bcbf9aed764a2df85cffe7c6baf66..c8372701ac3290377ae54f0aed7c7eb8ed781511 100644 --- a/substrate/client/db/Cargo.toml +++ b/substrate/client/db/Cargo.toml @@ -16,38 +16,38 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", features = [ +codec = { features = [ "derive", -] } -hash-db = "0.16.0" -kvdb = "0.13.0" -kvdb-memorydb = "0.13.0" -kvdb-rocksdb = { version = "0.19.0", optional = true } -linked-hash-map = "0.5.4" +], workspace = true, default-features = true } +hash-db = { workspace = true, default-features = true } +kvdb = { workspace = true } +kvdb-memorydb = { workspace = true } +kvdb-rocksdb = { optional = true, workspace = true } +linked-hash-map = { workspace = true } log = { workspace = true, default-features = true } -parity-db = "0.4.12" -parking_lot = "0.12.1" -sc-client-api = { path = "../api" } -sc-state-db = { path = "../state-db" } -schnellru = "0.2.1" -sp-arithmetic = { path = "../../primitives/arithmetic" } -sp-blockchain = { path = "../../primitives/blockchain" } -sp-core = { path = "../../primitives/core" } -sp-database = { path = "../../primitives/database" } -sp-runtime = { path = "../../primitives/runtime" } -sp-state-machine = { path = "../../primitives/state-machine" } -sp-trie = { path = "../../primitives/trie" } +parity-db = { workspace = true } +parking_lot = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-state-db = { workspace = true, default-features = true } +schnellru = { workspace = true } +sp-arithmetic = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-core = { 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 } +sp-trie = { workspace = true, default-features = true } [dev-dependencies] -criterion = "0.5.1" -kvdb-rocksdb = "0.19.0" -rand = "0.8.5" -tempfile = "3.1.0" -quickcheck = { version = "1.0.3", default-features = false } -kitchensink-runtime = { path = "../../bin/node/runtime" } -sp-tracing = { path = "../../primitives/tracing" } -substrate-test-runtime-client = { path = "../../test-utils/runtime/client" } -array-bytes = "6.2.2" +criterion = { workspace = true, default-features = true } +kvdb-rocksdb = { workspace = true } +rand = { workspace = true, default-features = true } +tempfile = { workspace = true } +quickcheck = { workspace = true } +kitchensink-runtime = { workspace = true } +sp-tracing = { workspace = true, default-features = true } +substrate-test-runtime-client = { workspace = true } +array-bytes = { workspace = true, default-features = true } [features] default = [] diff --git a/substrate/client/db/src/lib.rs b/substrate/client/db/src/lib.rs index 36f9aea817c9c7031ae69a588a9385e88e786b0c..8d8b7a2aff88f88a3f034845a3422bad51258e69 100644 --- a/substrate/client/db/src/lib.rs +++ b/substrate/client/db/src/lib.rs @@ -2547,7 +2547,7 @@ pub(crate) mod tests { backend::{Backend as BTrait, BlockImportOperation as Op}, blockchain::Backend as BLBTrait, }; - use sp_blockchain::{lowest_common_ancestor, tree_route}; + use sp_blockchain::{lowest_common_ancestor, lowest_common_ancestor_multiblock, tree_route}; use sp_core::H256; use sp_runtime::{ testing::{Block as RawBlock, ExtrinsicWrapper, Header}, @@ -3108,6 +3108,125 @@ pub(crate) mod tests { } } + #[test] + fn lowest_common_ancestors_multiblock_works() { + let backend = Backend::::new_test(1000, 100); + let blockchain = backend.blockchain(); + let block0 = insert_header(&backend, 0, Default::default(), None, Default::default()); + + // fork from genesis: 3 prong. + // block 0 -> a1 -> a2 -> a3 + // | + // -> b1 -> b2 -> c1 -> c2 + // | + // -> d1 -> d2 + let a1 = insert_header(&backend, 1, block0, None, Default::default()); + let a2 = insert_header(&backend, 2, a1, None, Default::default()); + let a3 = insert_header(&backend, 3, a2, None, Default::default()); + + // fork from genesis: 2 prong. + let b1 = insert_header(&backend, 1, block0, None, H256::from([1; 32])); + let b2 = insert_header(&backend, 2, b1, None, Default::default()); + + // fork from b2. + let c1 = insert_header(&backend, 3, b2, None, H256::from([2; 32])); + let c2 = insert_header(&backend, 4, c1, None, Default::default()); + + // fork from b1. + let d1 = insert_header(&backend, 2, b1, None, H256::from([3; 32])); + let d2 = insert_header(&backend, 3, d1, None, Default::default()); + { + let lca = lowest_common_ancestor_multiblock(blockchain, vec![a3, b2]).unwrap().unwrap(); + + assert_eq!(lca.hash, block0); + assert_eq!(lca.number, 0); + } + + { + let lca = lowest_common_ancestor_multiblock(blockchain, vec![a1, a3]).unwrap().unwrap(); + + assert_eq!(lca.hash, a1); + assert_eq!(lca.number, 1); + } + + { + let lca = lowest_common_ancestor_multiblock(blockchain, vec![a3, a1]).unwrap().unwrap(); + + assert_eq!(lca.hash, a1); + assert_eq!(lca.number, 1); + } + + { + let lca = lowest_common_ancestor_multiblock(blockchain, vec![a2, a3]).unwrap().unwrap(); + + assert_eq!(lca.hash, a2); + assert_eq!(lca.number, 2); + } + + { + let lca = lowest_common_ancestor_multiblock(blockchain, vec![a2, a1]).unwrap().unwrap(); + + assert_eq!(lca.hash, a1); + assert_eq!(lca.number, 1); + } + + { + let lca = lowest_common_ancestor_multiblock(blockchain, vec![a2, a2]).unwrap().unwrap(); + + assert_eq!(lca.hash, a2); + assert_eq!(lca.number, 2); + } + + { + let lca = lowest_common_ancestor_multiblock(blockchain, vec![a3, d2, c2]) + .unwrap() + .unwrap(); + + assert_eq!(lca.hash, block0); + assert_eq!(lca.number, 0); + } + + { + let lca = lowest_common_ancestor_multiblock(blockchain, vec![c2, d2, b2]) + .unwrap() + .unwrap(); + + assert_eq!(lca.hash, b1); + assert_eq!(lca.number, 1); + } + + { + let lca = lowest_common_ancestor_multiblock(blockchain, vec![a1, a2, a3]) + .unwrap() + .unwrap(); + + assert_eq!(lca.hash, a1); + assert_eq!(lca.number, 1); + } + + { + let lca = lowest_common_ancestor_multiblock(blockchain, vec![b1, b2, d1]) + .unwrap() + .unwrap(); + + assert_eq!(lca.hash, b1); + assert_eq!(lca.number, 1); + } + + { + let lca = lowest_common_ancestor_multiblock(blockchain, vec![]); + + assert_eq!(true, matches!(lca, Ok(None))); + } + + { + let lca = lowest_common_ancestor_multiblock(blockchain, vec![a1]).unwrap().unwrap(); + + assert_eq!(lca.hash, a1); + assert_eq!(lca.number, 1); + } + } + #[test] fn test_tree_route_regression() { // NOTE: this is a test for a regression introduced in #3665, the result diff --git a/substrate/client/executor/Cargo.toml b/substrate/client/executor/Cargo.toml index 1f54b82030ff226b179afe8f167e134417b859e9..c10c60822ff8dbec0b3ac800a1c3c2b0a3d8b0d8 100644 --- a/substrate/client/executor/Cargo.toml +++ b/substrate/client/executor/Cargo.toml @@ -17,43 +17,43 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -parking_lot = "0.12.1" -schnellru = "0.2.1" -tracing = "0.1.29" +parking_lot = { workspace = true, default-features = true } +schnellru = { workspace = true } +tracing = { workspace = true, default-features = true } -codec = { package = "parity-scale-codec", version = "3.6.12" } -sc-executor-common = { path = "common" } -sc-executor-polkavm = { path = "polkavm" } -sc-executor-wasmtime = { path = "wasmtime" } -sp-api = { path = "../../primitives/api" } -sp-core = { path = "../../primitives/core" } -sp-externalities = { path = "../../primitives/externalities" } -sp-io = { path = "../../primitives/io" } -sp-panic-handler = { path = "../../primitives/panic-handler" } -sp-runtime-interface = { path = "../../primitives/runtime-interface" } -sp-trie = { path = "../../primitives/trie" } -sp-version = { path = "../../primitives/version" } -sp-wasm-interface = { path = "../../primitives/wasm-interface" } +codec = { workspace = true, default-features = true } +sc-executor-common = { workspace = true, default-features = true } +sc-executor-polkavm = { workspace = true, default-features = true } +sc-executor-wasmtime = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-externalities = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-panic-handler = { workspace = true, default-features = true } +sp-runtime-interface = { workspace = true, default-features = true } +sp-trie = { workspace = true, default-features = true } +sp-version = { workspace = true, default-features = true } +sp-wasm-interface = { workspace = true, default-features = true } [dev-dependencies] -array-bytes = "6.2.2" -assert_matches = "1.3.0" -wat = "1.0" -sc-runtime-test = { path = "runtime-test" } -substrate-test-runtime = { path = "../../test-utils/runtime" } -sp-crypto-hashing = { path = "../../primitives/crypto/hashing" } -sp-state-machine = { path = "../../primitives/state-machine" } -sp-runtime = { path = "../../primitives/runtime" } -sp-maybe-compressed-blob = { path = "../../primitives/maybe-compressed-blob" } -sc-tracing = { path = "../tracing" } -sp-tracing = { path = "../../primitives/tracing" } +array-bytes = { workspace = true, default-features = true } +assert_matches = { workspace = true } +wat = { workspace = true } +sc-runtime-test = { workspace = true } +substrate-test-runtime = { workspace = true } +sp-crypto-hashing = { workspace = true, default-features = true } +sp-state-machine = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-maybe-compressed-blob = { workspace = true, default-features = true } +sc-tracing = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } tracing-subscriber = { workspace = true } -paste = "1.0" -regex = "1.6.0" -criterion = "0.5.1" -env_logger = "0.11" -num_cpus = "1.13.1" -tempfile = "3.3.0" +paste = { workspace = true, default-features = true } +regex = { workspace = true } +criterion = { workspace = true, default-features = true } +env_logger = { workspace = true } +num_cpus = { workspace = true } +tempfile = { workspace = true } [[bench]] name = "bench" diff --git a/substrate/client/executor/common/Cargo.toml b/substrate/client/executor/common/Cargo.toml index 8ff34c3709a5e486fb9036a638788a532c6f296c..e985c75ca908a669f0ff7e6cc7368269e0814343 100644 --- a/substrate/client/executor/common/Cargo.toml +++ b/substrate/client/executor/common/Cargo.toml @@ -18,10 +18,10 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] thiserror = { workspace = true } -wasm-instrument = "0.4" -sc-allocator = { path = "../../allocator" } -sp-maybe-compressed-blob = { path = "../../../primitives/maybe-compressed-blob" } -sp-wasm-interface = { path = "../../../primitives/wasm-interface" } +wasm-instrument = { workspace = true, default-features = true } +sc-allocator = { workspace = true, default-features = true } +sp-maybe-compressed-blob = { workspace = true, default-features = true } +sp-wasm-interface = { workspace = true, default-features = true } polkavm = { workspace = true } [features] diff --git a/substrate/client/executor/polkavm/Cargo.toml b/substrate/client/executor/polkavm/Cargo.toml index 9d0eb8ccf0ee072c86195068a589309edd132ba4..8b849209a07cf17838c89e32cc53fcb80fe3c6ab 100644 --- a/substrate/client/executor/polkavm/Cargo.toml +++ b/substrate/client/executor/polkavm/Cargo.toml @@ -19,5 +19,5 @@ targets = ["x86_64-unknown-linux-gnu"] log = { workspace = true } polkavm = { workspace = true } -sc-executor-common = { path = "../common" } -sp-wasm-interface = { path = "../../../primitives/wasm-interface" } +sc-executor-common = { workspace = true, default-features = true } +sp-wasm-interface = { workspace = true, default-features = true } diff --git a/substrate/client/executor/runtime-test/Cargo.toml b/substrate/client/executor/runtime-test/Cargo.toml index 82610c4f50c2841fea13c1f859cc242f8ae427c7..5f5e7eb46d623782916e55637dfd93e892cab6fe 100644 --- a/substrate/client/executor/runtime-test/Cargo.toml +++ b/substrate/client/executor/runtime-test/Cargo.toml @@ -16,14 +16,14 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-core = { path = "../../../primitives/core", default-features = false } -sp-io = { path = "../../../primitives/io", default-features = false, features = ["improved_panic_error_reporting"] } -sp-runtime = { path = "../../../primitives/runtime", default-features = false } -sp-runtime-interface = { path = "../../../primitives/runtime-interface", default-features = false } -sp-std = { path = "../../../primitives/std", default-features = false } +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 = { path = "../../../utils/wasm-builder", optional = true } +substrate-wasm-builder = { optional = true, workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/client/executor/src/integration_tests/mod.rs b/substrate/client/executor/src/integration_tests/mod.rs index 7f91b3ffe7644e37ebee0bc035faafbf38e21148..5d94ec6dcd38628be7858b8477e7e4892a45b210 100644 --- a/substrate/client/executor/src/integration_tests/mod.rs +++ b/substrate/client/executor/src/integration_tests/mod.rs @@ -178,7 +178,7 @@ fn storage_should_work(wasm_method: WasmExecutionMethod) { assert_eq!(output, b"all ok!".to_vec().encode()); } - let expected = TestExternalities::new(sp_core::storage::Storage { + let mut expected = TestExternalities::new(sp_core::storage::Storage { top: map![ b"input".to_vec() => value, b"foo".to_vec() => b"bar".to_vec(), @@ -186,7 +186,7 @@ fn storage_should_work(wasm_method: WasmExecutionMethod) { ], children_default: map![], }); - assert_eq!(ext, expected); + assert!(ext.eq(&mut expected)); } test_wasm_execution!(clear_prefix_should_work); @@ -208,7 +208,7 @@ fn clear_prefix_should_work(wasm_method: WasmExecutionMethod) { assert_eq!(output, b"all ok!".to_vec().encode()); } - let expected = TestExternalities::new(sp_core::storage::Storage { + let mut expected = TestExternalities::new(sp_core::storage::Storage { top: map![ b"aaa".to_vec() => b"1".to_vec(), b"aab".to_vec() => b"2".to_vec(), @@ -216,7 +216,7 @@ fn clear_prefix_should_work(wasm_method: WasmExecutionMethod) { ], children_default: map![], }); - assert_eq!(expected, ext); + assert!(expected.eq(&mut ext)); } test_wasm_execution!(blake2_256_should_work); diff --git a/substrate/client/executor/wasmtime/Cargo.toml b/substrate/client/executor/wasmtime/Cargo.toml index d3d670650db789b2b9b854a5fda8724a506833ee..e58b19bb12431a3ffb5b9fc77526b523e7cf4863 100644 --- a/substrate/client/executor/wasmtime/Cargo.toml +++ b/substrate/client/executor/wasmtime/Cargo.toml @@ -17,24 +17,24 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] log = { workspace = true, default-features = true } -cfg-if = "1.0" -libc = "0.2.152" -parking_lot = "0.12.1" +cfg-if = { workspace = true } +libc = { workspace = true } +parking_lot = { workspace = true, default-features = true } # When bumping wasmtime do not forget to also bump rustix # to exactly the same version as used by wasmtime! -wasmtime = { version = "8.0.1", default-features = false, features = [ +wasmtime = { features = [ "cache", "cranelift", "jitdump", "parallel-compilation", "pooling-allocator", -] } -anyhow = "1.0.81" -sc-allocator = { path = "../../allocator" } -sc-executor-common = { path = "../common" } -sp-runtime-interface = { path = "../../../primitives/runtime-interface" } -sp-wasm-interface = { path = "../../../primitives/wasm-interface", features = ["wasmtime"] } +], workspace = true } +anyhow = { workspace = true } +sc-allocator = { workspace = true, default-features = true } +sc-executor-common = { workspace = true, default-features = true } +sp-runtime-interface = { workspace = true, default-features = true } +sp-wasm-interface = { features = ["wasmtime"], workspace = true, default-features = true } # Here we include the rustix crate in the exactly same semver-compatible version as used by # wasmtime and enable its 'use-libc' flag. @@ -42,13 +42,13 @@ sp-wasm-interface = { path = "../../../primitives/wasm-interface", features = [" # By default rustix directly calls the appropriate syscalls completely bypassing libc; # this doesn't have any actual benefits for us besides making it harder to debug memory # problems (since then `mmap` etc. cannot be easily hooked into). -rustix = { version = "0.36.7", default-features = false, features = ["fs", "mm", "param", "std", "use-libc"] } +rustix = { features = ["fs", "mm", "param", "std", "use-libc"], workspace = true } [dev-dependencies] -wat = "1.0" -sc-runtime-test = { path = "../runtime-test" } -sp-io = { path = "../../../primitives/io" } -tempfile = "3.3.0" -paste = "1.0" -codec = { package = "parity-scale-codec", version = "3.6.12" } -cargo_metadata = "0.15.4" +wat = { workspace = true } +sc-runtime-test = { workspace = true } +sp-io = { workspace = true, default-features = true } +tempfile = { workspace = true } +paste = { workspace = true, default-features = true } +codec = { workspace = true, default-features = true } +cargo_metadata = { workspace = true } diff --git a/substrate/client/informant/Cargo.toml b/substrate/client/informant/Cargo.toml index 191ef5f19f8df65b3c817129fe34c4db7438826d..9da2296deee3c2cdec7d2ba2ef7d2958dc03d86c 100644 --- a/substrate/client/informant/Cargo.toml +++ b/substrate/client/informant/Cargo.toml @@ -16,13 +16,13 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -ansi_term = "0.12.1" -futures = "0.3.30" -futures-timer = "3.0.1" +ansi_term = { workspace = true } +futures = { workspace = true } +futures-timer = { workspace = true } log = { workspace = true, default-features = true } -sc-client-api = { path = "../api" } -sc-network-common = { path = "../network/common" } -sc-network-sync = { path = "../network/sync" } -sc-network = { path = "../network" } -sp-blockchain = { path = "../../primitives/blockchain" } -sp-runtime = { path = "../../primitives/runtime" } +sc-client-api = { workspace = true, default-features = true } +sc-network-common = { workspace = true, default-features = true } +sc-network-sync = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } diff --git a/substrate/client/keystore/Cargo.toml b/substrate/client/keystore/Cargo.toml index 443ce3507542c155119f2d424d18e9268b4d391b..cf128016370b41fde1c5c1fb151008a8a589c581 100644 --- a/substrate/client/keystore/Cargo.toml +++ b/substrate/client/keystore/Cargo.toml @@ -17,16 +17,16 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -array-bytes = "6.2.2" -parking_lot = "0.12.1" +array-bytes = { workspace = true, default-features = true } +parking_lot = { workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } thiserror = { workspace = true } -sp-application-crypto = { path = "../../primitives/application-crypto" } -sp-core = { path = "../../primitives/core" } -sp-keystore = { path = "../../primitives/keystore" } +sp-application-crypto = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } [dev-dependencies] -tempfile = "3.1.0" +tempfile = { workspace = true } [features] # This feature adds BLS crypto primitives. diff --git a/substrate/client/merkle-mountain-range/Cargo.toml b/substrate/client/merkle-mountain-range/Cargo.toml index 3cf3cdd15dad9bb30fe2a9a70b6adc9f4541e56e..e219d36d3f79cf8770c58b33c138b8d1ffd01df0 100644 --- a/substrate/client/merkle-mountain-range/Cargo.toml +++ b/substrate/client/merkle-mountain-range/Cargo.toml @@ -14,22 +14,22 @@ workspace = true # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12" } -futures = "0.3.30" +codec = { workspace = true, default-features = true } +futures = { workspace = true } log = { workspace = true, default-features = true } -sp-api = { path = "../../primitives/api" } -sp-blockchain = { path = "../../primitives/blockchain" } -sc-client-api = { path = "../api" } -sp-consensus-beefy = { path = "../../primitives/consensus/beefy" } -sp-consensus = { path = "../../primitives/consensus/common" } -sp-core = { path = "../../primitives/core" } -sp-mmr-primitives = { path = "../../primitives/merkle-mountain-range" } -sc-offchain = { path = "../offchain" } -sp-runtime = { path = "../../primitives/runtime" } +sp-api = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sp-consensus-beefy = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-mmr-primitives = { workspace = true, default-features = true } +sc-offchain = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } [dev-dependencies] -parking_lot = "0.12.1" -sc-block-builder = { path = "../block-builder" } -sp-tracing = { path = "../../primitives/tracing" } -substrate-test-runtime-client = { path = "../../test-utils/runtime/client" } -tokio = "1.37" +parking_lot = { workspace = true, default-features = true } +sc-block-builder = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +substrate-test-runtime-client = { workspace = true } +tokio = { workspace = true, default-features = true } diff --git a/substrate/client/merkle-mountain-range/rpc/Cargo.toml b/substrate/client/merkle-mountain-range/rpc/Cargo.toml index 25e6e316a8be0ab6ec0ff70f38a05f603ebf8404..5f856b4069a0f37a37189418a2a0e36976e1f98f 100644 --- a/substrate/client/merkle-mountain-range/rpc/Cargo.toml +++ b/substrate/client/merkle-mountain-range/rpc/Cargo.toml @@ -15,14 +15,14 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12" } -jsonrpsee = { version = "0.22.5", features = ["client-core", "macros", "server-core"] } +codec = { workspace = true, default-features = true } +jsonrpsee = { features = ["client-core", "macros", "server-core"], workspace = true } serde = { features = ["derive"], workspace = true, default-features = true } -sp-api = { path = "../../../primitives/api" } -sp-blockchain = { path = "../../../primitives/blockchain" } -sp-core = { path = "../../../primitives/core" } -sp-mmr-primitives = { path = "../../../primitives/merkle-mountain-range" } -sp-runtime = { path = "../../../primitives/runtime" } +sp-api = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-mmr-primitives = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } [dev-dependencies] serde_json = { workspace = true, default-features = true } diff --git a/substrate/client/mixnet/Cargo.toml b/substrate/client/mixnet/Cargo.toml index 1626305639498855148b515e666e1e91a603643f..2b06c3eca2344440b8391e9a351e0739d12352be 100644 --- a/substrate/client/mixnet/Cargo.toml +++ b/substrate/client/mixnet/Cargo.toml @@ -16,25 +16,25 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -array-bytes = "6.2.2" -arrayvec = "0.7.2" -blake2 = "0.10.4" -bytes = "1" -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -futures = "0.3.30" -futures-timer = "3.0.2" +array-bytes = { workspace = true, default-features = true } +arrayvec = { workspace = true } +blake2 = { workspace = true, default-features = true } +bytes = { workspace = true, default-features = true } +codec = { features = ["derive"], workspace = true } +futures = { workspace = true } +futures-timer = { workspace = true } log = { workspace = true, default-features = true } -mixnet = "0.7.0" -multiaddr = "0.17.1" -parking_lot = "0.12.1" -sc-client-api = { path = "../api" } -sc-network = { path = "../network" } -sc-network-types = { path = "../network/types" } -sc-transaction-pool-api = { path = "../transaction-pool/api" } -sp-api = { path = "../../primitives/api" } -sp-consensus = { path = "../../primitives/consensus/common" } -sp-core = { path = "../../primitives/core" } -sp-keystore = { path = "../../primitives/keystore" } -sp-mixnet = { path = "../../primitives/mixnet" } -sp-runtime = { path = "../../primitives/runtime" } +mixnet = { workspace = true } +multiaddr = { workspace = true } +parking_lot = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sc-network-types = { workspace = true, default-features = true } +sc-transaction-pool-api = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-mixnet = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } thiserror = { workspace = true } diff --git a/substrate/client/network-gossip/Cargo.toml b/substrate/client/network-gossip/Cargo.toml index 3eeea6651186162ed2f28bdf12ec08ad184df906..f1441e4a1cf274996df7baf40183142f8bf2a2a0 100644 --- a/substrate/client/network-gossip/Cargo.toml +++ b/substrate/client/network-gossip/Cargo.toml @@ -17,23 +17,22 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -ahash = "0.8.2" -futures = "0.3.30" -futures-timer = "3.0.1" -libp2p = "0.51.4" +ahash = { workspace = true } +futures = { workspace = true } +futures-timer = { workspace = true } log = { workspace = true, default-features = true } -schnellru = "0.2.1" -tracing = "0.1.29" -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../utils/prometheus" } -sc-network = { path = "../network" } -sc-network-common = { path = "../network/common" } -sc-network-sync = { path = "../network/sync" } -sc-network-types = { path = "../network/types" } -sp-runtime = { path = "../../primitives/runtime" } +schnellru = { workspace = true } +tracing = { workspace = true, default-features = true } +prometheus-endpoint = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sc-network-common = { workspace = true, default-features = true } +sc-network-sync = { workspace = true, default-features = true } +sc-network-types = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } [dev-dependencies] -tokio = "1.37" -async-trait = "0.1.79" -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } -quickcheck = { version = "1.0.3", default-features = false } -substrate-test-runtime-client = { path = "../../test-utils/runtime/client" } +tokio = { workspace = true, default-features = true } +async-trait = { workspace = true } +codec = { features = ["derive"], workspace = true, default-features = true } +quickcheck = { workspace = true } +substrate-test-runtime-client = { workspace = true } diff --git a/substrate/client/network-gossip/src/bridge.rs b/substrate/client/network-gossip/src/bridge.rs index cd344d9196d873b820c11246f1518e81a87f8683..414da9b2a5890bb61fb77e3d942bb04e3e44add7 100644 --- a/substrate/client/network-gossip/src/bridge.rs +++ b/substrate/client/network-gossip/src/bridge.rs @@ -348,7 +348,7 @@ impl futures::future::FusedFuture for GossipEngine { #[cfg(test)] mod tests { use super::*; - use crate::{multiaddr::Multiaddr, ValidationResult, ValidatorContext}; + use crate::{ValidationResult, ValidatorContext}; use codec::{DecodeAll, Encode}; use futures::{ channel::mpsc::{unbounded, UnboundedReceiver, UnboundedSender}, @@ -363,6 +363,7 @@ mod tests { }; use sc_network_common::role::ObservedRole; use sc_network_sync::SyncEventStream; + use sc_network_types::multiaddr::Multiaddr; use sp_runtime::{ testing::H256, traits::{Block as BlockT, NumberFor}, diff --git a/substrate/client/network-gossip/src/lib.rs b/substrate/client/network-gossip/src/lib.rs index e04ea2a91e7cbc59ae652dace7ede5398bedf01c..20d9922200c2c3c6cf394692099a21c01b540bd0 100644 --- a/substrate/client/network-gossip/src/lib.rs +++ b/substrate/client/network-gossip/src/lib.rs @@ -67,9 +67,12 @@ pub use self::{ validator::{DiscardAll, MessageIntent, ValidationResult, Validator, ValidatorContext}, }; -use sc_network::{multiaddr, types::ProtocolName, NetworkBlock, NetworkEventStream, NetworkPeers}; +use sc_network::{types::ProtocolName, NetworkBlock, NetworkEventStream, NetworkPeers}; use sc_network_sync::SyncEventStream; -use sc_network_types::PeerId; +use sc_network_types::{ + multiaddr::{Multiaddr, Protocol}, + PeerId, +}; use sp_runtime::traits::{Block as BlockT, NumberFor}; use std::iter; @@ -80,8 +83,7 @@ mod validator; /// Abstraction over a network. pub trait Network: NetworkPeers + NetworkEventStream { fn add_set_reserved(&self, who: PeerId, protocol: ProtocolName) { - let addr = - iter::once(multiaddr::Protocol::P2p(who.into())).collect::(); + let addr = Multiaddr::empty().with(Protocol::P2p(*who.as_ref())); let result = self.add_peers_to_reserved_set(protocol, iter::once(addr).collect()); if let Err(err) = result { log::error!(target: "gossip", "add_set_reserved failed: {}", err); diff --git a/substrate/client/network-gossip/src/state_machine.rs b/substrate/client/network-gossip/src/state_machine.rs index 016afa95eceaed228012641af0982e103c51eb64..ac3f7a1b8c74c24fbccf44906f97249739bee247 100644 --- a/substrate/client/network-gossip/src/state_machine.rs +++ b/substrate/client/network-gossip/src/state_machine.rs @@ -542,12 +542,12 @@ impl Metrics { #[cfg(test)] mod tests { use super::*; - use crate::multiaddr::Multiaddr; use futures::prelude::*; use sc_network::{ config::MultiaddrWithPeerId, event::Event, service::traits::NotificationEvent, MessageSink, NetworkBlock, NetworkEventStream, NetworkPeers, ReputationChange, }; + use sc_network_types::multiaddr::Multiaddr; use sp_runtime::{ testing::{Block as RawBlock, ExtrinsicWrapper, H256}, traits::NumberFor, diff --git a/substrate/client/network/Cargo.toml b/substrate/client/network/Cargo.toml index 29b14a4511cac655096b3e3dded5013462ae7e9e..a0cf42eaab22f54685a9087ac0fc3f9c68e1d31a 100644 --- a/substrate/client/network/Cargo.toml +++ b/substrate/client/network/Cargo.toml @@ -17,71 +17,71 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [build-dependencies] -prost-build = "0.12.4" +prost-build = { workspace = true } [dependencies] -array-bytes = "6.2.2" -async-channel = "1.8.0" -async-trait = "0.1.79" -asynchronous-codec = "0.6" -bytes = "1" -cid = "0.9.0" -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } -either = "1.5.3" -fnv = "1.0.6" -futures = "0.3.30" -futures-timer = "3.0.2" -ip_network = "0.4.1" -libp2p = { version = "0.51.4", features = ["dns", "identify", "kad", "macros", "mdns", "noise", "ping", "request-response", "tcp", "tokio", "websocket", "yamux"] } -linked_hash_set = "0.1.4" +array-bytes = { workspace = true, default-features = true } +async-channel = { workspace = true } +async-trait = { workspace = true } +asynchronous-codec = { workspace = true } +bytes = { workspace = true, default-features = true } +cid = { workspace = true } +codec = { features = ["derive"], workspace = true, default-features = true } +either = { workspace = true, default-features = true } +fnv = { workspace = true } +futures = { workspace = true } +futures-timer = { workspace = true } +ip_network = { workspace = true } +libp2p = { features = ["dns", "identify", "kad", "macros", "mdns", "noise", "ping", "request-response", "tcp", "tokio", "websocket", "yamux"], workspace = true } +linked_hash_set = { workspace = true } log = { workspace = true, default-features = true } -mockall = "0.11.3" -parking_lot = "0.12.1" -partial_sort = "0.2.0" -pin-project = "1.0.12" -rand = "0.8.5" +mockall = { workspace = true } +parking_lot = { workspace = true, default-features = true } +partial_sort = { workspace = true } +pin-project = { workspace = true } +rand = { workspace = true, default-features = true } serde = { features = ["derive"], workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } -smallvec = "1.11.0" +smallvec = { workspace = true, default-features = true } thiserror = { workspace = true } -tokio = { version = "1.22.0", features = ["macros", "sync"] } -tokio-stream = "0.1.7" -unsigned-varint = { version = "0.7.2", features = ["asynchronous_codec", "futures"] } -zeroize = "1.4.3" -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../utils/prometheus" } -prost = "0.12.4" -sc-client-api = { path = "../api" } -sc-network-common = { path = "common" } -sc-network-types = { path = "types" } -sc-utils = { path = "../utils" } -sp-arithmetic = { path = "../../primitives/arithmetic" } -sp-blockchain = { path = "../../primitives/blockchain" } -sp-core = { path = "../../primitives/core" } -sp-runtime = { path = "../../primitives/runtime" } -wasm-timer = "0.2" -litep2p = "0.5.0" -once_cell = "1.18.0" -void = "1.0.2" -schnellru = "0.2.1" +tokio = { features = ["macros", "sync"], workspace = true, default-features = true } +tokio-stream = { workspace = true } +unsigned-varint = { features = ["asynchronous_codec", "futures"], workspace = true } +zeroize = { workspace = true, default-features = true } +prometheus-endpoint = { workspace = true, default-features = true } +prost = { workspace = true } +sc-client-api = { workspace = true, default-features = true } +sc-network-common = { workspace = true, default-features = true } +sc-network-types = { workspace = true, default-features = true } +sc-utils = { workspace = true, default-features = true } +sp-arithmetic = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +wasm-timer = { workspace = true } +litep2p = { workspace = true } +once_cell = { workspace = true } +void = { workspace = true } +schnellru = { workspace = true } [dev-dependencies] -assert_matches = "1.3" -mockall = "0.11.3" -multistream-select = "0.12.1" -rand = "0.8.5" -tempfile = "3.1.0" -tokio = { version = "1.22.0", features = ["macros"] } -tokio-util = { version = "0.7.4", features = ["compat"] } -tokio-test = "0.4.2" -sc-block-builder = { path = "../block-builder" } -sc-network-light = { path = "light" } -sc-network-sync = { path = "sync" } -sp-crypto-hashing = { path = "../../primitives/crypto/hashing" } -sp-consensus = { path = "../../primitives/consensus/common" } -sp-test-primitives = { path = "../../primitives/test-primitives" } -sp-tracing = { path = "../../primitives/tracing" } -substrate-test-runtime = { path = "../../test-utils/runtime" } -substrate-test-runtime-client = { path = "../../test-utils/runtime/client" } +assert_matches = { workspace = true } +mockall = { workspace = true } +multistream-select = { workspace = true } +rand = { workspace = true, default-features = true } +tempfile = { workspace = true } +tokio = { features = ["macros"], workspace = true, default-features = true } +tokio-util = { features = ["compat"], workspace = true } +tokio-test = { workspace = true } +sc-block-builder = { workspace = true, default-features = true } +sc-network-light = { workspace = true, default-features = true } +sc-network-sync = { workspace = true, default-features = true } +sp-crypto-hashing = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-test-primitives = { workspace = true } +sp-tracing = { workspace = true, default-features = true } +substrate-test-runtime = { workspace = true } +substrate-test-runtime-client = { workspace = true } [features] default = [] diff --git a/substrate/client/network/common/Cargo.toml b/substrate/client/network/common/Cargo.toml index 9a1bf5b88ea1a97cf6bdfe358a44338561500b50..79326492159b153ad8e8c91932aeac0fa4ecb6bc 100644 --- a/substrate/client/network/common/Cargo.toml +++ b/substrate/client/network/common/Cargo.toml @@ -16,21 +16,21 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [build-dependencies] -prost-build = "0.12.4" +prost-build = { workspace = true } [dependencies] -async-trait = "0.1.79" -bitflags = "1.3.2" -codec = { package = "parity-scale-codec", version = "3.6.12", features = [ +async-trait = { workspace = true } +bitflags = { workspace = true } +codec = { features = [ "derive", -] } -futures = "0.3.30" -libp2p-identity = { version = "0.1.3", features = ["peerid"] } -sc-consensus = { path = "../../consensus/common" } -sc-network-types = { path = "../types" } -sp-consensus = { path = "../../../primitives/consensus/common" } -sp-consensus-grandpa = { path = "../../../primitives/consensus/grandpa" } -sp-runtime = { path = "../../../primitives/runtime" } +], workspace = true, default-features = true } +futures = { workspace = true } +libp2p-identity = { features = ["peerid"], workspace = true } +sc-consensus = { workspace = true, default-features = true } +sc-network-types = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-consensus-grandpa = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } [dev-dependencies] -tempfile = "3.1.0" +tempfile = { workspace = true } diff --git a/substrate/client/network/light/Cargo.toml b/substrate/client/network/light/Cargo.toml index baaed578b884172bdcfba5eb2a66e48ac32c56a5..52deaa93852af84213a4515c7bf3a3e9cb6892f2 100644 --- a/substrate/client/network/light/Cargo.toml +++ b/substrate/client/network/light/Cargo.toml @@ -16,21 +16,21 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [build-dependencies] -prost-build = "0.12.4" +prost-build = { workspace = true } [dependencies] -async-channel = "1.8.0" -array-bytes = "6.2.2" -codec = { package = "parity-scale-codec", version = "3.6.12", features = [ +async-channel = { workspace = true } +array-bytes = { workspace = true, default-features = true } +codec = { features = [ "derive", -] } -futures = "0.3.30" +], workspace = true, default-features = true } +futures = { workspace = true } log = { workspace = true, default-features = true } -prost = "0.12.4" -sp-blockchain = { path = "../../../primitives/blockchain" } -sc-client-api = { path = "../../api" } -sc-network-types = { path = "../types" } -sc-network = { path = ".." } -sp-core = { path = "../../../primitives/core" } -sp-runtime = { path = "../../../primitives/runtime" } +prost = { workspace = true } +sp-blockchain = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-network-types = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } thiserror = { workspace = true } diff --git a/substrate/client/network/src/behaviour.rs b/substrate/client/network/src/behaviour.rs index 68deac0f47bc1e3b367fc56ba77e67ba63380648..68816a10980d46565cc05e58d81e86b10bbc92e5 100644 --- a/substrate/client/network/src/behaviour.rs +++ b/substrate/client/network/src/behaviour.rs @@ -31,8 +31,8 @@ use crate::{ use futures::channel::oneshot; use libp2p::{ - core::Multiaddr, identify::Info as IdentifyInfo, identity::PublicKey, kad::RecordKey, - swarm::NetworkBehaviour, PeerId, + connection_limits::ConnectionLimits, core::Multiaddr, identify::Info as IdentifyInfo, + identity::PublicKey, kad::RecordKey, swarm::NetworkBehaviour, PeerId, StreamProtocol, }; use parking_lot::Mutex; @@ -47,8 +47,10 @@ pub use crate::request_responses::{InboundFailure, OutboundFailure, ResponseFail /// General behaviour of the network. Combines all protocols together. #[derive(NetworkBehaviour)] -#[behaviour(out_event = "BehaviourOut")] +#[behaviour(to_swarm = "BehaviourOut")] pub struct Behaviour { + /// Connection limits. + connection_limits: libp2p::connection_limits::Behaviour, /// All the substrate-specific protocols. substrate: Protocol, /// Periodically pings and identifies the nodes we are connected to, and store information in a @@ -180,6 +182,7 @@ impl Behaviour { request_response_protocols: Vec, peer_store_handle: Arc, external_addresses: Arc>>, + connection_limits: ConnectionLimits, ) -> Result { Ok(Self { substrate, @@ -193,6 +196,7 @@ impl Behaviour { request_response_protocols.into_iter(), peer_store_handle, )?, + connection_limits: libp2p::connection_limits::Behaviour::new(connection_limits), }) } @@ -267,7 +271,7 @@ impl Behaviour { pub fn add_self_reported_address_to_dht( &mut self, peer_id: &PeerId, - supported_protocols: &[impl AsRef<[u8]>], + supported_protocols: &[StreamProtocol], addr: Multiaddr, ) { self.discovery.add_self_reported_address(peer_id, supported_protocols, addr); @@ -376,3 +380,9 @@ impl From for BehaviourOut { } } } + +impl From for BehaviourOut { + fn from(e: void::Void) -> Self { + void::unreachable(e) + } +} diff --git a/substrate/client/network/src/config.rs b/substrate/client/network/src/config.rs index 100a1e9dfb38ea23d4bb7d846aed0295f1cdaaea..e939558b20b8b021d8b38140d84365621b93413f 100644 --- a/substrate/client/network/src/config.rs +++ b/substrate/client/network/src/config.rs @@ -114,13 +114,13 @@ pub fn parse_str_addr(addr_str: &str) -> Result<(PeerId, Multiaddr), ParseErr> { /// Splits a Multiaddress into a Multiaddress and PeerId. pub fn parse_addr(mut addr: Multiaddr) -> Result<(PeerId, Multiaddr), ParseErr> { - let who = match addr.pop() { - Some(multiaddr::Protocol::P2p(key)) => - PeerId::from_multihash(key).map_err(|_| ParseErr::InvalidPeerId)?, + let multihash = match addr.pop() { + Some(multiaddr::Protocol::P2p(multihash)) => multihash, _ => return Err(ParseErr::PeerIdMissing), }; + let peer_id = PeerId::from_multihash(multihash).map_err(|_| ParseErr::InvalidPeerId)?; - Ok((who, addr)) + Ok((peer_id, addr)) } /// Address of a node, including its identity. diff --git a/substrate/client/network/src/discovery.rs b/substrate/client/network/src/discovery.rs index 2c788ec713f345ef18d421a07c279e9dfd9f7ba0..3145b891a8d3c1d0287b7d070d9ed40402847c49 100644 --- a/substrate/client/network/src/discovery.rs +++ b/substrate/client/network/src/discovery.rs @@ -55,20 +55,20 @@ use ip_network::IpNetwork; use libp2p::{ core::{Endpoint, Multiaddr}, kad::{ - handler::KademliaHandler, + self, record::store::{MemoryStore, RecordStore}, - GetClosestPeersError, GetRecordOk, Kademlia, KademliaBucketInserts, KademliaConfig, - KademliaEvent, QueryId, QueryResult, Quorum, Record, RecordKey, + Behaviour as Kademlia, BucketInserts, Config as KademliaConfig, Event as KademliaEvent, + GetClosestPeersError, GetRecordOk, QueryId, QueryResult, Quorum, Record, RecordKey, }, mdns::{self, tokio::Behaviour as TokioMdns}, multiaddr::Protocol, swarm::{ behaviour::{ toggle::{Toggle, ToggleConnectionHandler}, - DialFailure, FromSwarm, NewExternalAddr, + DialFailure, ExternalAddrConfirmed, FromSwarm, }, - ConnectionDenied, ConnectionId, DialError, NetworkBehaviour, PollParameters, THandler, - THandlerInEvent, THandlerOutEvent, ToSwarm, + ConnectionDenied, ConnectionId, DialError, NetworkBehaviour, PollParameters, + StreamProtocol, THandler, THandlerInEvent, THandlerOutEvent, ToSwarm, }, PeerId, }; @@ -105,8 +105,8 @@ pub struct DiscoveryConfig { discovery_only_if_under_num: u64, enable_mdns: bool, kademlia_disjoint_query_paths: bool, - kademlia_protocol: Vec, - kademlia_legacy_protocol: Vec, + kademlia_protocol: Option, + kademlia_legacy_protocol: Option, kademlia_replication_factor: NonZeroUsize, } @@ -122,8 +122,8 @@ impl DiscoveryConfig { discovery_only_if_under_num: std::u64::MAX, enable_mdns: false, kademlia_disjoint_query_paths: false, - kademlia_protocol: Vec::new(), - kademlia_legacy_protocol: Vec::new(), + kademlia_protocol: None, + kademlia_legacy_protocol: None, kademlia_replication_factor: NonZeroUsize::new(DEFAULT_KADEMLIA_REPLICATION_FACTOR) .expect("value is a constant; constant is non-zero; qed."), } @@ -179,8 +179,8 @@ impl DiscoveryConfig { fork_id: Option<&str>, protocol_id: &ProtocolId, ) -> &mut Self { - self.kademlia_protocol = kademlia_protocol_name(genesis_hash, fork_id); - self.kademlia_legacy_protocol = legacy_kademlia_protocol_name(protocol_id); + self.kademlia_protocol = Some(kademlia_protocol_name(genesis_hash, fork_id)); + self.kademlia_legacy_protocol = Some(legacy_kademlia_protocol_name(protocol_id)); self } @@ -213,26 +213,31 @@ impl DiscoveryConfig { kademlia_replication_factor, } = self; - let kademlia = if !kademlia_protocol.is_empty() { + let kademlia = if let Some(ref kademlia_protocol) = kademlia_protocol { let mut config = KademliaConfig::default(); config.set_replication_factor(kademlia_replication_factor); // Populate kad with both the legacy and the new protocol names. // Remove the legacy protocol: // https://github.com/paritytech/polkadot-sdk/issues/504 - let kademlia_protocols = [kademlia_protocol.clone(), kademlia_legacy_protocol]; + let kademlia_protocols = if let Some(legacy_protocol) = kademlia_legacy_protocol { + vec![kademlia_protocol.clone(), legacy_protocol] + } else { + vec![kademlia_protocol.clone()] + }; config.set_protocol_names(kademlia_protocols.into_iter().map(Into::into).collect()); - config.set_record_filtering(libp2p::kad::KademliaStoreInserts::FilterBoth); + config.set_record_filtering(libp2p::kad::StoreInserts::FilterBoth); // By default Kademlia attempts to insert all peers into its routing table once a // dialing attempt succeeds. In order to control which peer is added, disable the // auto-insertion and instead add peers manually. - config.set_kbucket_inserts(KademliaBucketInserts::Manual); + config.set_kbucket_inserts(BucketInserts::Manual); config.disjoint_query_paths(kademlia_disjoint_query_paths); let store = MemoryStore::new(local_peer_id); let mut kad = Kademlia::with_config(local_peer_id, store, config); + kad.set_mode(Some(kad::Mode::Server)); for (peer_id, addr) in &permanent_addresses { kad.add_address(peer_id, addr.clone()); @@ -323,7 +328,7 @@ pub struct DiscoveryBehaviour { /// /// Remove when all nodes are upgraded to genesis hash and fork ID-based Kademlia: /// . - kademlia_protocol: Vec, + kademlia_protocol: Option, } impl DiscoveryBehaviour { @@ -369,7 +374,7 @@ impl DiscoveryBehaviour { pub fn add_self_reported_address( &mut self, peer_id: &PeerId, - supported_protocols: &[impl AsRef<[u8]>], + supported_protocols: &[StreamProtocol], addr: Multiaddr, ) { if let Some(kademlia) = self.kademlia.as_mut() { @@ -386,10 +391,12 @@ impl DiscoveryBehaviour { // Extract the chain-based Kademlia protocol from `kademlia.protocol_name()` // when all nodes are upgraded to genesis hash and fork ID-based Kademlia: // https://github.com/paritytech/polkadot-sdk/issues/504. - if !supported_protocols - .iter() - .any(|p| p.as_ref() == self.kademlia_protocol.as_slice()) - { + if !supported_protocols.iter().any(|p| { + p == self + .kademlia_protocol + .as_ref() + .expect("kademlia protocol was checked above to be enabled; qed") + }) { trace!( target: "sub-libp2p", "Ignoring self-reported address {} from {} as remote node is not part of the \ @@ -503,7 +510,7 @@ impl DiscoveryBehaviour { #[derive(Debug)] pub enum DiscoveryOut { /// A connection to a peer has been established but the peer has not been - /// added to the routing table because [`KademliaBucketInserts::Manual`] is + /// added to the routing table because [`BucketInserts::Manual`] is /// configured. If the peer is to be included in the routing table, it must /// be explicitly added via /// [`DiscoveryBehaviour::add_self_reported_address`]. @@ -552,8 +559,9 @@ pub enum DiscoveryOut { } impl NetworkBehaviour for DiscoveryBehaviour { - type ConnectionHandler = ToggleConnectionHandler>; - type OutEvent = DiscoveryOut; + type ConnectionHandler = + ToggleConnectionHandler< as NetworkBehaviour>::ConnectionHandler>; + type ToSwarm = DiscoveryOut; fn handle_established_inbound_connection( &mut self, @@ -689,11 +697,11 @@ impl NetworkBehaviour for DiscoveryBehaviour { FromSwarm::ListenerError(e) => { self.kademlia.on_swarm_event(FromSwarm::ListenerError(e)); }, - FromSwarm::ExpiredExternalAddr(e) => { + FromSwarm::ExternalAddrExpired(e) => { // We intentionally don't remove the element from `known_external_addresses` in // order to not print the log line again. - self.kademlia.on_swarm_event(FromSwarm::ExpiredExternalAddr(e)); + self.kademlia.on_swarm_event(FromSwarm::ExternalAddrExpired(e)); }, FromSwarm::NewListener(e) => { self.kademlia.on_swarm_event(FromSwarm::NewListener(e)); @@ -701,8 +709,18 @@ impl NetworkBehaviour for DiscoveryBehaviour { FromSwarm::ExpiredListenAddr(e) => { self.kademlia.on_swarm_event(FromSwarm::ExpiredListenAddr(e)); }, - FromSwarm::NewExternalAddr(e @ NewExternalAddr { addr }) => { - let new_addr = addr.clone().with(Protocol::P2p(self.local_peer_id.into())); + FromSwarm::NewExternalAddrCandidate(e) => { + self.kademlia.on_swarm_event(FromSwarm::NewExternalAddrCandidate(e)); + }, + FromSwarm::AddressChange(e) => { + self.kademlia.on_swarm_event(FromSwarm::AddressChange(e)); + }, + FromSwarm::NewListenAddr(e) => { + self.kademlia.on_swarm_event(FromSwarm::NewListenAddr(e)); + self.mdns.on_swarm_event(FromSwarm::NewListenAddr(e)); + }, + FromSwarm::ExternalAddrConfirmed(e @ ExternalAddrConfirmed { addr }) => { + let new_addr = addr.clone().with(Protocol::P2p(self.local_peer_id)); if Self::can_add_to_dht(addr) { // NOTE: we might re-discover the same address multiple times @@ -716,14 +734,7 @@ impl NetworkBehaviour for DiscoveryBehaviour { } } - self.kademlia.on_swarm_event(FromSwarm::NewExternalAddr(e)); - }, - FromSwarm::AddressChange(e) => { - self.kademlia.on_swarm_event(FromSwarm::AddressChange(e)); - }, - FromSwarm::NewListenAddr(e) => { - self.kademlia.on_swarm_event(FromSwarm::NewListenAddr(e)); - self.mdns.on_swarm_event(FromSwarm::NewListenAddr(e)); + self.kademlia.on_swarm_event(FromSwarm::ExternalAddrConfirmed(e)); }, } } @@ -741,7 +752,7 @@ impl NetworkBehaviour for DiscoveryBehaviour { &mut self, cx: &mut Context, params: &mut impl PollParameters, - ) -> Poll>> { + ) -> Poll>> { // Immediately process the content of `discovered`. if let Some(ev) = self.pending_events.pop_front() { return Poll::Ready(ToSwarm::GenerateEvent(ev)) @@ -963,10 +974,17 @@ impl NetworkBehaviour for DiscoveryBehaviour { ToSwarm::Dial { opts } => return Poll::Ready(ToSwarm::Dial { opts }), ToSwarm::NotifyHandler { peer_id, handler, event } => return Poll::Ready(ToSwarm::NotifyHandler { peer_id, handler, event }), - ToSwarm::ReportObservedAddr { address, score } => - return Poll::Ready(ToSwarm::ReportObservedAddr { address, score }), ToSwarm::CloseConnection { peer_id, connection } => return Poll::Ready(ToSwarm::CloseConnection { peer_id, connection }), + ToSwarm::NewExternalAddrCandidate(observed) => + return Poll::Ready(ToSwarm::NewExternalAddrCandidate(observed)), + ToSwarm::ExternalAddrConfirmed(addr) => + return Poll::Ready(ToSwarm::ExternalAddrConfirmed(addr)), + ToSwarm::ExternalAddrExpired(addr) => + return Poll::Ready(ToSwarm::ExternalAddrExpired(addr)), + ToSwarm::ListenOn { opts } => return Poll::Ready(ToSwarm::ListenOn { opts }), + ToSwarm::RemoveListener { id } => + return Poll::Ready(ToSwarm::RemoveListener { id }), } } @@ -979,8 +997,9 @@ impl NetworkBehaviour for DiscoveryBehaviour { continue } - self.pending_events - .extend(list.map(|(peer_id, _)| DiscoveryOut::Discovered(peer_id))); + self.pending_events.extend( + list.into_iter().map(|(peer_id, _)| DiscoveryOut::Discovered(peer_id)), + ); if let Some(ev) = self.pending_events.pop_front() { return Poll::Ready(ToSwarm::GenerateEvent(ev)) } @@ -990,13 +1009,19 @@ impl NetworkBehaviour for DiscoveryBehaviour { ToSwarm::Dial { .. } => { unreachable!("mDNS never dials!"); }, - ToSwarm::NotifyHandler { event, .. } => match event {}, /* `event` is an */ - // enum with no - // variant - ToSwarm::ReportObservedAddr { address, score } => - return Poll::Ready(ToSwarm::ReportObservedAddr { address, score }), + // `event` is an enum with no variant + ToSwarm::NotifyHandler { event, .. } => match event {}, ToSwarm::CloseConnection { peer_id, connection } => return Poll::Ready(ToSwarm::CloseConnection { peer_id, connection }), + ToSwarm::NewExternalAddrCandidate(observed) => + return Poll::Ready(ToSwarm::NewExternalAddrCandidate(observed)), + ToSwarm::ExternalAddrConfirmed(addr) => + return Poll::Ready(ToSwarm::ExternalAddrConfirmed(addr)), + ToSwarm::ExternalAddrExpired(addr) => + return Poll::Ready(ToSwarm::ExternalAddrExpired(addr)), + ToSwarm::ListenOn { opts } => return Poll::Ready(ToSwarm::ListenOn { opts }), + ToSwarm::RemoveListener { id } => + return Poll::Ready(ToSwarm::RemoveListener { id }), } } @@ -1005,21 +1030,24 @@ impl NetworkBehaviour for DiscoveryBehaviour { } /// Legacy (fallback) Kademlia protocol name based on `protocol_id`. -fn legacy_kademlia_protocol_name(id: &ProtocolId) -> Vec { - let mut v = vec![b'/']; - v.extend_from_slice(id.as_ref().as_bytes()); - v.extend_from_slice(b"/kad"); - v +fn legacy_kademlia_protocol_name(id: &ProtocolId) -> StreamProtocol { + let name = format!("/{}/kad", id.as_ref()); + StreamProtocol::try_from_owned(name).expect("protocol name is valid. qed") } /// Kademlia protocol name based on `genesis_hash` and `fork_id`. -fn kademlia_protocol_name>(genesis_hash: Hash, fork_id: Option<&str>) -> Vec { +fn kademlia_protocol_name>( + genesis_hash: Hash, + fork_id: Option<&str>, +) -> StreamProtocol { let genesis_hash_hex = bytes2hex("", genesis_hash.as_ref()); - if let Some(fork_id) = fork_id { - format!("/{}/{}/kad", genesis_hash_hex, fork_id).as_bytes().into() + let name = if let Some(fork_id) = fork_id { + format!("/{genesis_hash_hex}/{fork_id}/kad") } else { - format!("/{}/kad", genesis_hash_hex).as_bytes().into() - } + format!("/{genesis_hash_hex}/kad") + }; + + StreamProtocol::try_from_owned(name).expect("protocol name is valid. qed") } #[cfg(test)] @@ -1036,7 +1064,7 @@ mod tests { }, identity::Keypair, noise, - swarm::{Executor, Swarm, SwarmBuilder, SwarmEvent}, + swarm::{Executor, Swarm, SwarmEvent}, yamux, Multiaddr, }; use sp_core::hash::H256; @@ -1082,7 +1110,8 @@ mod tests { }; let runtime = tokio::runtime::Runtime::new().unwrap(); - let mut swarm = SwarmBuilder::with_executor( + #[allow(deprecated)] + let mut swarm = libp2p::swarm::SwarmBuilder::with_executor( transport, behaviour, keypair.public().to_peer_id(), diff --git a/substrate/client/network/src/event.rs b/substrate/client/network/src/event.rs index d0ccbd8622b885730864d29ac835441cd276d970..b518a2094d7665ce4e44b67fcac99c992f73c08c 100644 --- a/substrate/client/network/src/event.rs +++ b/substrate/client/network/src/event.rs @@ -16,7 +16,7 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -//! Network event types. These are are not the part of the protocol, but rather +//! Network event types. These are not the part of the protocol, but rather //! events that happen on the network like DHT get/put results received. use crate::types::ProtocolName; diff --git a/substrate/client/network/src/litep2p/service.rs b/substrate/client/network/src/litep2p/service.rs index 8f36b0828bd39d7f159111cea4713c8d1b04e54c..20bf6cd12d21e058a1fadaf9d95bde6fb806a92f 100644 --- a/substrate/client/network/src/litep2p/service.rs +++ b/substrate/client/network/src/litep2p/service.rs @@ -264,8 +264,20 @@ impl NetworkStatusProvider for Litep2pNetworkService { async fn network_state(&self) -> Result { Ok(NetworkState { peer_id: self.local_peer_id.to_base58(), - listened_addresses: self.listen_addresses.read().iter().cloned().collect(), - external_addresses: self.external_addresses.read().iter().cloned().collect(), + listened_addresses: self + .listen_addresses + .read() + .iter() + .cloned() + .map(|a| Multiaddr::from(a).into()) + .collect(), + external_addresses: self + .external_addresses + .read() + .iter() + .cloned() + .map(|a| Multiaddr::from(a).into()) + .collect(), connected_peers: HashMap::new(), not_connected_peers: HashMap::new(), // TODO: Check what info we can include here. diff --git a/substrate/client/network/src/peer_info.rs b/substrate/client/network/src/peer_info.rs index 2735bd873db91dbcc0a54786e2c64408d6f21133..21eeea6bcc0c30415c646fdd18abb6f5f56ae09d 100644 --- a/substrate/client/network/src/peer_info.rs +++ b/substrate/client/network/src/peer_info.rs @@ -31,14 +31,15 @@ use libp2p::{ Info as IdentifyInfo, }, identity::PublicKey, - ping::{Behaviour as Ping, Config as PingConfig, Event as PingEvent, Success as PingSuccess}, + ping::{Behaviour as Ping, Config as PingConfig, Event as PingEvent}, swarm::{ behaviour::{ - AddressChange, ConnectionClosed, ConnectionEstablished, DialFailure, FromSwarm, - ListenFailure, + AddressChange, ConnectionClosed, ConnectionEstablished, DialFailure, + ExternalAddrConfirmed, FromSwarm, ListenFailure, }, - ConnectionDenied, ConnectionHandler, ConnectionId, IntoConnectionHandlerSelect, - NetworkBehaviour, PollParameters, THandler, THandlerInEvent, THandlerOutEvent, ToSwarm, + ConnectionDenied, ConnectionHandler, ConnectionHandlerSelect, ConnectionId, + NetworkBehaviour, NewExternalAddrCandidate, PollParameters, THandler, THandlerInEvent, + THandlerOutEvent, ToSwarm, }, Multiaddr, PeerId, }; @@ -47,7 +48,7 @@ use parking_lot::Mutex; use smallvec::SmallVec; use std::{ - collections::{hash_map::Entry, HashSet}, + collections::{hash_map::Entry, HashSet, VecDeque}, pin::Pin, sync::Arc, task::{Context, Poll}, @@ -71,6 +72,8 @@ pub struct PeerInfoBehaviour { garbage_collect: Pin + Send>>, /// Record keeping of external addresses. Data is queried by the `NetworkService`. external_addresses: ExternalAddresses, + /// Pending events to emit to [`Swarm`](libp2p::swarm::Swarm). + pending_actions: VecDeque>>, } /// Information about a node we're connected to. @@ -134,6 +137,7 @@ impl PeerInfoBehaviour { nodes_info: FnvHashMap::default(), garbage_collect: Box::pin(interval(GARBAGE_COLLECT_INTERVAL)), external_addresses: ExternalAddresses { addresses: external_addresses }, + pending_actions: Default::default(), } } @@ -148,13 +152,18 @@ impl PeerInfoBehaviour { /// Inserts a ping time in the cache. Has no effect if we don't have any entry for that node, /// which shouldn't happen. - fn handle_ping_report(&mut self, peer_id: &PeerId, ping_time: Duration) { - trace!(target: "sub-libp2p", "Ping time with {:?}: {:?}", peer_id, ping_time); + fn handle_ping_report( + &mut self, + peer_id: &PeerId, + ping_time: Duration, + connection: ConnectionId, + ) { + trace!(target: "sub-libp2p", "Ping time with {:?} via {:?}: {:?}", peer_id, connection, ping_time); if let Some(entry) = self.nodes_info.get_mut(peer_id) { entry.latest_ping = Some(ping_time); } else { error!(target: "sub-libp2p", - "Received ping from node we're not connected to {:?}", peer_id); + "Received ping from node we're not connected to {:?} via {:?}", peer_id, connection); } } @@ -208,11 +217,11 @@ pub enum PeerInfoEvent { } impl NetworkBehaviour for PeerInfoBehaviour { - type ConnectionHandler = IntoConnectionHandlerSelect< + type ConnectionHandler = ConnectionHandlerSelect< ::ConnectionHandler, ::ConnectionHandler, >; - type OutEvent = PeerInfoEvent; + type ToSwarm = PeerInfoEvent; fn handle_pending_inbound_connection( &mut self, @@ -378,9 +387,9 @@ impl NetworkBehaviour for PeerInfoBehaviour { self.ping.on_swarm_event(FromSwarm::ListenerError(e)); self.identify.on_swarm_event(FromSwarm::ListenerError(e)); }, - FromSwarm::ExpiredExternalAddr(e) => { - self.ping.on_swarm_event(FromSwarm::ExpiredExternalAddr(e)); - self.identify.on_swarm_event(FromSwarm::ExpiredExternalAddr(e)); + FromSwarm::ExternalAddrExpired(e) => { + self.ping.on_swarm_event(FromSwarm::ExternalAddrExpired(e)); + self.identify.on_swarm_event(FromSwarm::ExternalAddrExpired(e)); }, FromSwarm::NewListener(e) => { self.ping.on_swarm_event(FromSwarm::NewListener(e)); @@ -391,10 +400,23 @@ impl NetworkBehaviour for PeerInfoBehaviour { self.identify.on_swarm_event(FromSwarm::ExpiredListenAddr(e)); self.external_addresses.remove(e.addr); }, - FromSwarm::NewExternalAddr(e) => { - self.ping.on_swarm_event(FromSwarm::NewExternalAddr(e)); - self.identify.on_swarm_event(FromSwarm::NewExternalAddr(e)); - self.external_addresses.add(e.addr.clone()); + FromSwarm::NewExternalAddrCandidate(e @ NewExternalAddrCandidate { addr }) => { + self.ping.on_swarm_event(FromSwarm::NewExternalAddrCandidate(e)); + self.identify.on_swarm_event(FromSwarm::NewExternalAddrCandidate(e)); + + // Manually confirm all external address candidates. + // TODO: consider adding [AutoNAT protocol](https://docs.rs/libp2p/0.52.3/libp2p/autonat/index.html) + // (must go through the polkadot protocol spec) or implemeting heuristics for + // approving external address candidates. This can be done, for example, by + // approving only addresses reported by multiple peers. + // See also https://github.com/libp2p/rust-libp2p/pull/4721 introduced + // in libp2p v0.53 for heuristics approach. + self.pending_actions.push_back(ToSwarm::ExternalAddrConfirmed(addr.clone())); + }, + FromSwarm::ExternalAddrConfirmed(e @ ExternalAddrConfirmed { addr }) => { + self.ping.on_swarm_event(FromSwarm::ExternalAddrConfirmed(e)); + self.identify.on_swarm_event(FromSwarm::ExternalAddrConfirmed(e)); + self.external_addresses.add(addr.clone()); }, FromSwarm::AddressChange(e @ AddressChange { peer_id, old, new, .. }) => { self.ping.on_swarm_event(FromSwarm::AddressChange(e)); @@ -437,13 +459,17 @@ impl NetworkBehaviour for PeerInfoBehaviour { &mut self, cx: &mut Context, params: &mut impl PollParameters, - ) -> Poll>> { + ) -> Poll>> { + if let Some(event) = self.pending_actions.pop_front() { + return Poll::Ready(event) + } + loop { match self.ping.poll(cx, params) { Poll::Pending => break, Poll::Ready(ToSwarm::GenerateEvent(ev)) => { - if let PingEvent { peer, result: Ok(PingSuccess::Ping { rtt }) } = ev { - self.handle_ping_report(&peer, rtt) + if let PingEvent { peer, result: Ok(rtt), connection } = ev { + self.handle_ping_report(&peer, rtt, connection) } }, Poll::Ready(ToSwarm::Dial { opts }) => return Poll::Ready(ToSwarm::Dial { opts }), @@ -453,10 +479,18 @@ impl NetworkBehaviour for PeerInfoBehaviour { handler, event: Either::Left(event), }), - Poll::Ready(ToSwarm::ReportObservedAddr { address, score }) => - return Poll::Ready(ToSwarm::ReportObservedAddr { address, score }), Poll::Ready(ToSwarm::CloseConnection { peer_id, connection }) => return Poll::Ready(ToSwarm::CloseConnection { peer_id, connection }), + Poll::Ready(ToSwarm::NewExternalAddrCandidate(observed)) => + return Poll::Ready(ToSwarm::NewExternalAddrCandidate(observed)), + Poll::Ready(ToSwarm::ExternalAddrConfirmed(addr)) => + return Poll::Ready(ToSwarm::ExternalAddrConfirmed(addr)), + Poll::Ready(ToSwarm::ExternalAddrExpired(addr)) => + return Poll::Ready(ToSwarm::ExternalAddrExpired(addr)), + Poll::Ready(ToSwarm::ListenOn { opts }) => + return Poll::Ready(ToSwarm::ListenOn { opts }), + Poll::Ready(ToSwarm::RemoveListener { id }) => + return Poll::Ready(ToSwarm::RemoveListener { id }), } } @@ -482,10 +516,18 @@ impl NetworkBehaviour for PeerInfoBehaviour { handler, event: Either::Right(event), }), - Poll::Ready(ToSwarm::ReportObservedAddr { address, score }) => - return Poll::Ready(ToSwarm::ReportObservedAddr { address, score }), Poll::Ready(ToSwarm::CloseConnection { peer_id, connection }) => return Poll::Ready(ToSwarm::CloseConnection { peer_id, connection }), + Poll::Ready(ToSwarm::NewExternalAddrCandidate(observed)) => + return Poll::Ready(ToSwarm::NewExternalAddrCandidate(observed)), + Poll::Ready(ToSwarm::ExternalAddrConfirmed(addr)) => + return Poll::Ready(ToSwarm::ExternalAddrConfirmed(addr)), + Poll::Ready(ToSwarm::ExternalAddrExpired(addr)) => + return Poll::Ready(ToSwarm::ExternalAddrExpired(addr)), + Poll::Ready(ToSwarm::ListenOn { opts }) => + return Poll::Ready(ToSwarm::ListenOn { opts }), + Poll::Ready(ToSwarm::RemoveListener { id }) => + return Poll::Ready(ToSwarm::RemoveListener { id }), } } diff --git a/substrate/client/network/src/protocol.rs b/substrate/client/network/src/protocol.rs index 2e57ff1b6a86f7512acd704c755692daeec51a0f..977c4c4de663211a5e1694ada392c3e1164818a3 100644 --- a/substrate/client/network/src/protocol.rs +++ b/substrate/client/network/src/protocol.rs @@ -163,9 +163,6 @@ impl Protocol { pub fn disconnect_peer(&mut self, peer_id: &PeerId, protocol_name: ProtocolName) { if let Some(position) = self.notification_protocols.iter().position(|p| *p == protocol_name) { - // Note: no need to remove a peer from `self.peers` if we are dealing with sync - // protocol, because it will be done when handling - // `NotificationsOut::CustomProtocolClosed`. self.behaviour.disconnect_peer(peer_id, SetId::from(position)); } else { warn!(target: "sub-libp2p", "disconnect_peer() with invalid protocol name") @@ -229,7 +226,7 @@ pub enum CustomMessageOutcome { impl NetworkBehaviour for Protocol { type ConnectionHandler = ::ConnectionHandler; - type OutEvent = CustomMessageOutcome; + type ToSwarm = CustomMessageOutcome; fn handle_established_inbound_connection( &mut self, @@ -290,17 +287,25 @@ impl NetworkBehaviour for Protocol { &mut self, cx: &mut std::task::Context, params: &mut impl PollParameters, - ) -> Poll>> { + ) -> Poll>> { let event = match self.behaviour.poll(cx, params) { Poll::Pending => return Poll::Pending, Poll::Ready(ToSwarm::GenerateEvent(ev)) => ev, Poll::Ready(ToSwarm::Dial { opts }) => return Poll::Ready(ToSwarm::Dial { opts }), Poll::Ready(ToSwarm::NotifyHandler { peer_id, handler, event }) => return Poll::Ready(ToSwarm::NotifyHandler { peer_id, handler, event }), - Poll::Ready(ToSwarm::ReportObservedAddr { address, score }) => - return Poll::Ready(ToSwarm::ReportObservedAddr { address, score }), Poll::Ready(ToSwarm::CloseConnection { peer_id, connection }) => return Poll::Ready(ToSwarm::CloseConnection { peer_id, connection }), + Poll::Ready(ToSwarm::NewExternalAddrCandidate(observed)) => + return Poll::Ready(ToSwarm::NewExternalAddrCandidate(observed)), + Poll::Ready(ToSwarm::ExternalAddrConfirmed(addr)) => + return Poll::Ready(ToSwarm::ExternalAddrConfirmed(addr)), + Poll::Ready(ToSwarm::ExternalAddrExpired(addr)) => + return Poll::Ready(ToSwarm::ExternalAddrExpired(addr)), + Poll::Ready(ToSwarm::ListenOn { opts }) => + return Poll::Ready(ToSwarm::ListenOn { opts }), + Poll::Ready(ToSwarm::RemoveListener { id }) => + return Poll::Ready(ToSwarm::RemoveListener { id }), }; let outcome = match event { diff --git a/substrate/client/network/src/protocol/notifications/behaviour.rs b/substrate/client/network/src/protocol/notifications/behaviour.rs index 03ba437a66726caf6c284fc3863c4aca01118488..cb4f089995e3c6bffce8e6b8460602343d310174 100644 --- a/substrate/client/network/src/protocol/notifications/behaviour.rs +++ b/substrate/client/network/src/protocol/notifications/behaviour.rs @@ -1198,7 +1198,7 @@ impl Notifications { impl NetworkBehaviour for Notifications { type ConnectionHandler = NotifsHandler; - type OutEvent = NotificationsOut; + type ToSwarm = NotificationsOut; fn handle_pending_inbound_connection( &mut self, @@ -1678,10 +1678,11 @@ impl NetworkBehaviour for Notifications { FromSwarm::ListenerClosed(_) => {}, FromSwarm::ListenFailure(_) => {}, FromSwarm::ListenerError(_) => {}, - FromSwarm::ExpiredExternalAddr(_) => {}, + FromSwarm::ExternalAddrExpired(_) => {}, FromSwarm::NewListener(_) => {}, FromSwarm::ExpiredListenAddr(_) => {}, - FromSwarm::NewExternalAddr(_) => {}, + FromSwarm::NewExternalAddrCandidate(_) => {}, + FromSwarm::ExternalAddrConfirmed(_) => {}, FromSwarm::AddressChange(_) => {}, FromSwarm::NewListenAddr(_) => {}, } @@ -2239,7 +2240,7 @@ impl NetworkBehaviour for Notifications { &mut self, cx: &mut Context, _params: &mut impl PollParameters, - ) -> Poll>> { + ) -> Poll>> { if let Some(event) = self.events.pop_front() { return Poll::Ready(event) } @@ -2382,7 +2383,6 @@ mod tests { protocol::notifications::handler::tests::*, protocol_controller::{IncomingIndex, ProtoSetConfig, ProtocolController}, }; - use libp2p::swarm::AddressRecord; use sc_utils::mpsc::tracing_unbounded; use std::{collections::HashSet, iter}; @@ -2402,31 +2402,14 @@ mod tests { } #[derive(Clone)] - struct MockPollParams { - peer_id: PeerId, - addr: Multiaddr, - } + struct MockPollParams {} impl PollParameters for MockPollParams { type SupportedProtocolsIter = std::vec::IntoIter>; - type ListenedAddressesIter = std::vec::IntoIter; - type ExternalAddressesIter = std::vec::IntoIter; fn supported_protocols(&self) -> Self::SupportedProtocolsIter { vec![].into_iter() } - - fn listened_addresses(&self) -> Self::ListenedAddressesIter { - vec![self.addr.clone()].into_iter() - } - - fn external_addresses(&self) -> Self::ExternalAddressesIter { - vec![].into_iter() - } - - fn local_peer_id(&self) -> &PeerId { - &self.peer_id - } } fn development_notifs( @@ -3331,7 +3314,7 @@ mod tests { notif.on_swarm_event(FromSwarm::DialFailure(libp2p::swarm::behaviour::DialFailure { peer_id: Some(peer), - error: &libp2p::swarm::DialError::Banned, + error: &libp2p::swarm::DialError::Aborted, connection_id: ConnectionId::new_unchecked(1337), })); @@ -3877,7 +3860,7 @@ mod tests { let now = Instant::now(); notif.on_swarm_event(FromSwarm::DialFailure(libp2p::swarm::behaviour::DialFailure { peer_id: Some(peer), - error: &libp2p::swarm::DialError::Banned, + error: &libp2p::swarm::DialError::Aborted, connection_id: ConnectionId::new_unchecked(0), })); @@ -4003,7 +3986,7 @@ mod tests { assert!(notif.peers.get(&(peer, set_id)).is_some()); if tokio::time::timeout(Duration::from_secs(5), async { - let mut params = MockPollParams { peer_id: PeerId::random(), addr: Multiaddr::empty() }; + let mut params = MockPollParams {}; loop { futures::future::poll_fn(|cx| { @@ -4115,7 +4098,7 @@ mod tests { // verify that the code continues to keep the peer disabled by resetting the timer // after the first one expired. if tokio::time::timeout(Duration::from_secs(5), async { - let mut params = MockPollParams { peer_id: PeerId::random(), addr: Multiaddr::empty() }; + let mut params = MockPollParams {}; loop { futures::future::poll_fn(|cx| { diff --git a/substrate/client/network/src/protocol/notifications/handler.rs b/substrate/client/network/src/protocol/notifications/handler.rs index cb09583b73a2d32592fa6b70180779ba52c3de01..967ef614c5560ca5815193bbd597b13e35b2076e 100644 --- a/substrate/client/network/src/protocol/notifications/handler.rs +++ b/substrate/client/network/src/protocol/notifications/handler.rs @@ -75,8 +75,8 @@ use futures::{ use libp2p::{ core::ConnectedPoint, swarm::{ - handler::ConnectionEvent, ConnectionHandler, ConnectionHandlerEvent, KeepAlive, - NegotiatedSubstream, SubstreamProtocol, + handler::ConnectionEvent, ConnectionHandler, ConnectionHandlerEvent, KeepAlive, Stream, + SubstreamProtocol, }, PeerId, }; @@ -199,7 +199,7 @@ enum State { /// emitted. OpenDesiredByRemote { /// Substream opened by the remote and that hasn't been accepted/rejected yet. - in_substream: NotificationsInSubstream, + in_substream: NotificationsInSubstream, /// See [`State::Closed::pending_opening`]. pending_opening: bool, @@ -212,7 +212,7 @@ enum State { /// be emitted when transitioning to respectively [`State::Open`] or [`State::Closed`]. Opening { /// Substream opened by the remote. If `Some`, has been accepted. - in_substream: Option>, + in_substream: Option>, /// Is the connection inbound. inbound: bool, }, @@ -236,14 +236,14 @@ enum State { /// Always `Some` on transition to [`State::Open`]. Switched to `None` only if the remote /// closed the substream. If `None`, a [`NotifsHandlerOut::CloseDesired`] event has been /// emitted. - out_substream: Option>, + out_substream: Option>, /// Substream opened by the remote. /// /// Contrary to the `out_substream` field, operations continue as normal even if the /// substream has been closed by the remote. A `None` is treated the same way as if there /// was an idle substream. - in_substream: Option>, + in_substream: Option>, }, } @@ -481,8 +481,8 @@ pub enum NotifsHandlerError { } impl ConnectionHandler for NotifsHandler { - type InEvent = NotifsHandlerIn; - type OutEvent = NotifsHandlerOut; + type FromBehaviour = NotifsHandlerIn; + type ToBehaviour = NotifsHandlerOut; type Error = NotifsHandlerError; type InboundProtocol = UpgradeCollec; type OutboundProtocol = NotificationsOut; @@ -517,7 +517,7 @@ impl ConnectionHandler for NotifsHandler { match protocol_info.state { State::Closed { pending_opening } => { - self.events_queue.push_back(ConnectionHandlerEvent::Custom( + self.events_queue.push_back(ConnectionHandlerEvent::NotifyBehaviour( NotifsHandlerOut::OpenDesiredByRemote { protocol_index, handshake: in_substream_open.handshake, @@ -586,7 +586,7 @@ impl ConnectionHandler for NotifsHandler { in_substream: in_substream.take(), }; - self.events_queue.push_back(ConnectionHandlerEvent::Custom( + self.events_queue.push_back(ConnectionHandlerEvent::NotifyBehaviour( NotifsHandlerOut::OpenResultOk { protocol_index, negotiated_fallback: new_open.negotiated_fallback, @@ -600,6 +600,8 @@ impl ConnectionHandler for NotifsHandler { } }, ConnectionEvent::AddressChange(_address_change) => {}, + ConnectionEvent::LocalProtocolsChange(_) => {}, + ConnectionEvent::RemoteProtocolsChange(_) => {}, ConnectionEvent::DialUpgradeError(dial_upgrade_error) => match self.protocols [dial_upgrade_error.info] .state @@ -614,7 +616,7 @@ impl ConnectionHandler for NotifsHandler { self.protocols[dial_upgrade_error.info].state = State::Closed { pending_opening: false }; - self.events_queue.push_back(ConnectionHandlerEvent::Custom( + self.events_queue.push_back(ConnectionHandlerEvent::NotifyBehaviour( NotifsHandlerOut::OpenResultErr { protocol_index: dial_upgrade_error.info }, )); }, @@ -701,7 +703,7 @@ impl ConnectionHandler for NotifsHandler { self.protocols[protocol_index].state = State::Closed { pending_opening: true }; - self.events_queue.push_back(ConnectionHandlerEvent::Custom( + self.events_queue.push_back(ConnectionHandlerEvent::NotifyBehaviour( NotifsHandlerOut::OpenResultErr { protocol_index }, )); }, @@ -711,7 +713,7 @@ impl ConnectionHandler for NotifsHandler { State::Closed { .. } => {}, } - self.events_queue.push_back(ConnectionHandlerEvent::Custom( + self.events_queue.push_back(ConnectionHandlerEvent::NotifyBehaviour( NotifsHandlerOut::CloseResult { protocol_index }, )); }, @@ -726,9 +728,11 @@ impl ConnectionHandler for NotifsHandler { // A grace period of `INITIAL_KEEPALIVE_TIME` must be given to leave time for the remote // to express desire to open substreams. + #[allow(deprecated)] KeepAlive::Until(self.when_connection_open + INITIAL_KEEPALIVE_TIME) } + #[allow(deprecated)] fn poll( &mut self, cx: &mut Context, @@ -736,7 +740,7 @@ impl ConnectionHandler for NotifsHandler { ConnectionHandlerEvent< Self::OutboundProtocol, Self::OutboundOpenInfo, - Self::OutEvent, + Self::ToBehaviour, Self::Error, >, > { @@ -755,6 +759,7 @@ impl ConnectionHandler for NotifsHandler { // Only proceed with `out_substream.poll_ready_unpin` if there is an element // available in `notifications_sink_rx`. This avoids waking up the task when // a substream is ready to send if there isn't actually something to send. + #[allow(deprecated)] match Pin::new(&mut *notifications_sink_rx).as_mut().poll_peek(cx) { Poll::Ready(Some(&NotificationsSinkMessage::ForceClose)) => return Poll::Ready(ConnectionHandlerEvent::Close( @@ -808,7 +813,7 @@ impl ConnectionHandler for NotifsHandler { Poll::Ready(Err(_)) => { *out_substream = None; let event = NotifsHandlerOut::CloseDesired { protocol_index }; - return Poll::Ready(ConnectionHandlerEvent::Custom(event)) + return Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour(event)) }, }; }, @@ -830,11 +835,14 @@ impl ConnectionHandler for NotifsHandler { State::Opening { in_substream: None, .. } => {}, State::Open { in_substream: in_substream @ Some(_), .. } => - match Stream::poll_next(Pin::new(in_substream.as_mut().unwrap()), cx) { + match futures::prelude::stream::Stream::poll_next( + Pin::new(in_substream.as_mut().unwrap()), + cx, + ) { Poll::Pending => {}, Poll::Ready(Some(Ok(message))) => { let event = NotifsHandlerOut::Notification { protocol_index, message }; - return Poll::Ready(ConnectionHandlerEvent::Custom(event)) + return Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour(event)) }, Poll::Ready(None) | Poll::Ready(Some(Err(_))) => *in_substream = None, }, @@ -846,7 +854,7 @@ impl ConnectionHandler for NotifsHandler { Poll::Ready(Err(_)) => { self.protocols[protocol_index].state = State::Closed { pending_opening: *pending_opening }; - return Poll::Ready(ConnectionHandlerEvent::Custom( + return Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour( NotifsHandlerOut::CloseDesired { protocol_index }, )) }, @@ -880,8 +888,8 @@ pub mod tests { use asynchronous_codec::Framed; use libp2p::{ core::muxing::SubstreamBox, - swarm::{handler, ConnectionHandlerUpgrErr}, - Multiaddr, + swarm::handler::{self, StreamUpgradeError}, + Multiaddr, Stream, }; use multistream_select::{dialer_select_proto, listener_select_proto, Negotiated, Version}; use std::{ @@ -972,6 +980,7 @@ pub mod tests { .await } } + struct MockSubstream { pub rx: mpsc::Receiver>, pub tx: mpsc::Sender>, @@ -991,18 +1000,35 @@ pub mod tests { } /// Create new negotiated substream pair. - pub async fn negotiated() -> (Negotiated, Negotiated) { + pub async fn negotiated() -> (Stream, Stream) { let (socket1, socket2) = Self::new(); let socket1 = SubstreamBox::new(socket1); let socket2 = SubstreamBox::new(socket2); - let protos = vec![b"/echo/1.0.0", b"/echo/2.5.0"]; + let protos = vec!["/echo/1.0.0", "/echo/2.5.0"]; let (res1, res2) = tokio::join!( dialer_select_proto(socket1, protos.clone(), Version::V1), listener_select_proto(socket2, protos), ); - (res1.unwrap().1, res2.unwrap().1) + (Self::stream_new(res1.unwrap().1), Self::stream_new(res2.unwrap().1)) + } + + /// Unsafe substitute for `Stream::new` private constructor. + fn stream_new(stream: Negotiated) -> Stream { + // Static asserts to make sure this doesn't break. + const _: () = { + assert!( + core::mem::size_of::() == + core::mem::size_of::>() + ); + assert!( + core::mem::align_of::() == + core::mem::align_of::>() + ); + }; + + unsafe { core::mem::transmute(stream) } } } @@ -1504,7 +1530,7 @@ pub mod tests { // inject dial failure to an already closed substream and verify outbound state is reset handler.on_connection_event(handler::ConnectionEvent::DialUpgradeError( - handler::DialUpgradeError { info: 0, error: ConnectionHandlerUpgrErr::Timeout }, + handler::DialUpgradeError { info: 0, error: StreamUpgradeError::Timeout }, )); assert!(std::matches!( handler.protocols[0].state, @@ -1574,7 +1600,7 @@ pub mod tests { // inject dial failure to an already closed substream and verify outbound state is reset handler.on_connection_event(handler::ConnectionEvent::DialUpgradeError( - handler::DialUpgradeError { info: 0, error: ConnectionHandlerUpgrErr::Timeout }, + handler::DialUpgradeError { info: 0, error: StreamUpgradeError::Timeout }, )); assert!(std::matches!( handler.protocols[0].state, @@ -1610,6 +1636,7 @@ pub mod tests { notifications_sink.send_sync_notification(vec![1, 3, 3, 9]); notifications_sink.send_sync_notification(vec![1, 3, 4, 0]); + #[allow(deprecated)] futures::future::poll_fn(|cx| { assert!(std::matches!( handler.poll(cx), @@ -1648,15 +1675,15 @@ pub mod tests { futures::future::poll_fn(|cx| { assert!(std::matches!( handler.poll(cx), - Poll::Ready(ConnectionHandlerEvent::Custom( + Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour( NotifsHandlerOut::OpenDesiredByRemote { protocol_index: 0, .. }, )) )); assert!(std::matches!( handler.poll(cx), - Poll::Ready(ConnectionHandlerEvent::Custom(NotifsHandlerOut::CloseDesired { - protocol_index: 0 - },)) + Poll::Ready(ConnectionHandlerEvent::NotifyBehaviour( + NotifsHandlerOut::CloseDesired { protocol_index: 0 }, + )) )); Poll::Ready(()) }) diff --git a/substrate/client/network/src/protocol/notifications/tests.rs b/substrate/client/network/src/protocol/notifications/tests.rs index a72b5b4a6748f0754279cef3f37dd37f601263dd..90c9cc5b7cde3b57f622e5cd04a07344e06a50f8 100644 --- a/substrate/client/network/src/protocol/notifications/tests.rs +++ b/substrate/client/network/src/protocol/notifications/tests.rs @@ -33,9 +33,8 @@ use libp2p::{ core::{transport::MemoryTransport, upgrade, Endpoint}, identity, noise, swarm::{ - behaviour::FromSwarm, ConnectionDenied, ConnectionId, Executor, NetworkBehaviour, - PollParameters, Swarm, SwarmBuilder, SwarmEvent, THandler, THandlerInEvent, - THandlerOutEvent, ToSwarm, + self, behaviour::FromSwarm, ConnectionDenied, ConnectionId, Executor, NetworkBehaviour, + PollParameters, Swarm, SwarmEvent, THandler, THandlerInEvent, THandlerOutEvent, ToSwarm, }, yamux, Multiaddr, PeerId, Transport, }; @@ -141,13 +140,12 @@ fn build_nodes() -> (Swarm, Swarm) { } }); - let mut swarm = SwarmBuilder::with_executor( + let mut swarm = Swarm::new( transport, behaviour, keypairs[index].public().to_peer_id(), - TokioExecutor(runtime), - ) - .build(); + swarm::Config::with_executor(TokioExecutor(runtime)), + ); swarm.listen_on(addrs[index].clone()).unwrap(); out.push(swarm); } @@ -183,7 +181,7 @@ impl std::ops::DerefMut for CustomProtoWithAddr { impl NetworkBehaviour for CustomProtoWithAddr { type ConnectionHandler = ::ConnectionHandler; - type OutEvent = ::OutEvent; + type ToSwarm = ::ToSwarm; fn handle_pending_inbound_connection( &mut self, @@ -261,7 +259,7 @@ impl NetworkBehaviour for CustomProtoWithAddr { &mut self, cx: &mut Context, params: &mut impl PollParameters, - ) -> Poll>> { + ) -> Poll>> { let _ = self.peer_store_future.poll_unpin(cx); let _ = self.protocol_controller_future.poll_unpin(cx); self.inner.poll(cx, params) diff --git a/substrate/client/network/src/protocol/notifications/upgrade.rs b/substrate/client/network/src/protocol/notifications/upgrade.rs index 8fd837f949d8a10d744513b9225ecf53d8a74d1e..72e0c2d10396232ec53b2e61e0dc5ceb4cb48dac 100644 --- a/substrate/client/network/src/protocol/notifications/upgrade.rs +++ b/substrate/client/network/src/protocol/notifications/upgrade.rs @@ -20,6 +20,7 @@ pub(crate) use self::notifications::{ NotificationsInOpen, NotificationsInSubstreamHandshake, NotificationsOutOpen, }; + pub use self::{ collec::UpgradeCollec, notifications::{ diff --git a/substrate/client/network/src/protocol/notifications/upgrade/collec.rs b/substrate/client/network/src/protocol/notifications/upgrade/collec.rs index 33c090ae50e9d87b8976f78fc61e751b474b49ec..ab0f87215cca3e55040dc3ad280fddb29d53254f 100644 --- a/substrate/client/network/src/protocol/notifications/upgrade/collec.rs +++ b/substrate/client/network/src/protocol/notifications/upgrade/collec.rs @@ -17,7 +17,7 @@ // along with this program. If not, see . use futures::prelude::*; -use libp2p::core::upgrade::{InboundUpgrade, ProtocolName, UpgradeInfo}; +use libp2p::core::upgrade::{InboundUpgrade, UpgradeInfo}; use std::{ pin::Pin, task::{Context, Poll}, @@ -75,9 +75,9 @@ where #[derive(Debug, Clone, PartialEq)] pub struct ProtoNameWithUsize(T, usize); -impl ProtocolName for ProtoNameWithUsize { - fn protocol_name(&self) -> &[u8] { - self.0.protocol_name() +impl> AsRef for ProtoNameWithUsize { + fn as_ref(&self) -> &str { + self.0.as_ref() } } @@ -103,13 +103,13 @@ impl>, O, E> Future for FutWithUsize { mod tests { use super::*; use crate::types::ProtocolName as ProtoName; - use libp2p::core::upgrade::{ProtocolName, UpgradeInfo}; + use libp2p::core::upgrade::UpgradeInfo; // TODO: move to mocks mockall::mock! { pub ProtocolUpgrade {} - impl UpgradeInfo for ProtocolUpgrade { + impl> UpgradeInfo for ProtocolUpgrade { type Info = T; type InfoIter = vec::IntoIter; fn protocol_info(&self) -> vec::IntoIter; diff --git a/substrate/client/network/src/protocol/notifications/upgrade/notifications.rs b/substrate/client/network/src/protocol/notifications/upgrade/notifications.rs index c760b7a963fc156e29165792d7cf145240aa4506..a8a9e453a7bb0c313e95dc1ffee954fa144f4d11 100644 --- a/substrate/client/network/src/protocol/notifications/upgrade/notifications.rs +++ b/substrate/client/network/src/protocol/notifications/upgrade/notifications.rs @@ -513,45 +513,99 @@ pub enum NotificationsOutError { #[cfg(test)] mod tests { + use crate::ProtocolName; + use super::{ - NotificationsIn, NotificationsInOpen, NotificationsOut, NotificationsOutError, - NotificationsOutOpen, + NotificationsHandshakeError, NotificationsIn, NotificationsInOpen, + NotificationsInSubstream, NotificationsOut, NotificationsOutError, NotificationsOutOpen, + NotificationsOutSubstream, }; - use futures::{channel::oneshot, future, prelude::*}; - use libp2p::core::upgrade; + use futures::{channel::oneshot, future, prelude::*, SinkExt, StreamExt}; + use libp2p::core::{upgrade, InboundUpgrade, OutboundUpgrade, UpgradeInfo}; use std::{pin::Pin, task::Poll}; use tokio::net::{TcpListener, TcpStream}; use tokio_util::compat::TokioAsyncReadCompatExt; + /// Opens a substream to the given address, negotiates the protocol, and returns the substream + /// along with the handshake message. + async fn dial( + addr: std::net::SocketAddr, + handshake: impl Into>, + ) -> Result< + ( + Vec, + NotificationsOutSubstream< + multistream_select::Negotiated>, + >, + ), + NotificationsHandshakeError, + > { + let socket = TcpStream::connect(addr).await.unwrap(); + let notifs_out = NotificationsOut::new("/test/proto/1", Vec::new(), handshake, 1024 * 1024); + let (_, substream) = multistream_select::dialer_select_proto( + socket.compat(), + notifs_out.protocol_info(), + upgrade::Version::V1, + ) + .await + .unwrap(); + let NotificationsOutOpen { handshake, substream, .. } = + >::upgrade_outbound( + notifs_out, + substream, + "/test/proto/1".into(), + ) + .await?; + Ok((handshake, substream)) + } + + /// Listens on a localhost, negotiates the protocol, and returns the substream along with the + /// handshake message. + /// + /// Also sends the listener address through the given channel. + async fn listen_on_localhost( + listener_addr_tx: oneshot::Sender, + ) -> Result< + ( + Vec, + NotificationsInSubstream< + multistream_select::Negotiated>, + >, + ), + NotificationsHandshakeError, + > { + let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); + listener_addr_tx.send(listener.local_addr().unwrap()).unwrap(); + + let (socket, _) = listener.accept().await.unwrap(); + let notifs_in = NotificationsIn::new("/test/proto/1", Vec::new(), 1024 * 1024); + let (_, substream) = + multistream_select::listener_select_proto(socket.compat(), notifs_in.protocol_info()) + .await + .unwrap(); + let NotificationsInOpen { handshake, substream, .. } = + >::upgrade_inbound( + notifs_in, + substream, + "/test/proto/1".into(), + ) + .await?; + Ok((handshake, substream)) + } + #[tokio::test] async fn basic_works() { - const PROTO_NAME: &str = "/test/proto/1"; let (listener_addr_tx, listener_addr_rx) = oneshot::channel(); let client = tokio::spawn(async move { - let socket = TcpStream::connect(listener_addr_rx.await.unwrap()).await.unwrap(); - let NotificationsOutOpen { handshake, mut substream, .. } = upgrade::apply_outbound( - socket.compat(), - NotificationsOut::new(PROTO_NAME, Vec::new(), &b"initial message"[..], 1024 * 1024), - upgrade::Version::V1, - ) - .await - .unwrap(); + let (handshake, mut substream) = + dial(listener_addr_rx.await.unwrap(), &b"initial message"[..]).await.unwrap(); assert_eq!(handshake, b"hello world"); substream.send(b"test message".to_vec()).await.unwrap(); }); - let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - listener_addr_tx.send(listener.local_addr().unwrap()).unwrap(); - - let (socket, _) = listener.accept().await.unwrap(); - let NotificationsInOpen { handshake, mut substream, .. } = upgrade::apply_inbound( - socket.compat(), - NotificationsIn::new(PROTO_NAME, Vec::new(), 1024 * 1024), - ) - .await - .unwrap(); + let (handshake, mut substream) = listen_on_localhost(listener_addr_tx).await.unwrap(); assert_eq!(handshake, b"initial message"); substream.send_handshake(&b"hello world"[..]); @@ -566,33 +620,17 @@ mod tests { async fn empty_handshake() { // Check that everything still works when the handshake messages are empty. - const PROTO_NAME: &str = "/test/proto/1"; let (listener_addr_tx, listener_addr_rx) = oneshot::channel(); let client = tokio::spawn(async move { - let socket = TcpStream::connect(listener_addr_rx.await.unwrap()).await.unwrap(); - let NotificationsOutOpen { handshake, mut substream, .. } = upgrade::apply_outbound( - socket.compat(), - NotificationsOut::new(PROTO_NAME, Vec::new(), vec![], 1024 * 1024), - upgrade::Version::V1, - ) - .await - .unwrap(); + let (handshake, mut substream) = + dial(listener_addr_rx.await.unwrap(), vec![]).await.unwrap(); assert!(handshake.is_empty()); substream.send(Default::default()).await.unwrap(); }); - let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - listener_addr_tx.send(listener.local_addr().unwrap()).unwrap(); - - let (socket, _) = listener.accept().await.unwrap(); - let NotificationsInOpen { handshake, mut substream, .. } = upgrade::apply_inbound( - socket.compat(), - NotificationsIn::new(PROTO_NAME, Vec::new(), 1024 * 1024), - ) - .await - .unwrap(); + let (handshake, mut substream) = listen_on_localhost(listener_addr_tx).await.unwrap(); assert!(handshake.is_empty()); substream.send_handshake(vec![]); @@ -605,17 +643,10 @@ mod tests { #[tokio::test] async fn refused() { - const PROTO_NAME: &str = "/test/proto/1"; let (listener_addr_tx, listener_addr_rx) = oneshot::channel(); let client = tokio::spawn(async move { - let socket = TcpStream::connect(listener_addr_rx.await.unwrap()).await.unwrap(); - let outcome = upgrade::apply_outbound( - socket.compat(), - NotificationsOut::new(PROTO_NAME, Vec::new(), &b"hello"[..], 1024 * 1024), - upgrade::Version::V1, - ) - .await; + let outcome = dial(listener_addr_rx.await.unwrap(), &b"hello"[..]).await; // Despite the protocol negotiation being successfully conducted on the listener // side, we have to receive an error here because the listener didn't send the @@ -623,17 +654,7 @@ mod tests { assert!(outcome.is_err()); }); - let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - listener_addr_tx.send(listener.local_addr().unwrap()).unwrap(); - - let (socket, _) = listener.accept().await.unwrap(); - let NotificationsInOpen { handshake, substream, .. } = upgrade::apply_inbound( - socket.compat(), - NotificationsIn::new(PROTO_NAME, Vec::new(), 1024 * 1024), - ) - .await - .unwrap(); - + let (handshake, substream) = listen_on_localhost(listener_addr_tx).await.unwrap(); assert_eq!(handshake, b"hello"); // We successfully upgrade to the protocol, but then close the substream. @@ -644,66 +665,29 @@ mod tests { #[tokio::test] async fn large_initial_message_refused() { - const PROTO_NAME: &str = "/test/proto/1"; let (listener_addr_tx, listener_addr_rx) = oneshot::channel(); let client = tokio::spawn(async move { - let socket = TcpStream::connect(listener_addr_rx.await.unwrap()).await.unwrap(); - let ret = upgrade::apply_outbound( - socket.compat(), - // We check that an initial message that is too large gets refused. - NotificationsOut::new( - PROTO_NAME, - Vec::new(), - (0..32768).map(|_| 0).collect::>(), - 1024 * 1024, - ), - upgrade::Version::V1, - ) - .await; + let ret = + dial(listener_addr_rx.await.unwrap(), (0..32768).map(|_| 0).collect::>()) + .await; assert!(ret.is_err()); }); - let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - listener_addr_tx.send(listener.local_addr().unwrap()).unwrap(); - - let (socket, _) = listener.accept().await.unwrap(); - let ret = upgrade::apply_inbound( - socket.compat(), - NotificationsIn::new(PROTO_NAME, Vec::new(), 1024 * 1024), - ) - .await; - assert!(ret.is_err()); - + let _ret = listen_on_localhost(listener_addr_tx).await; client.await.unwrap(); } #[tokio::test] async fn large_handshake_refused() { - const PROTO_NAME: &str = "/test/proto/1"; let (listener_addr_tx, listener_addr_rx) = oneshot::channel(); let client = tokio::spawn(async move { - let socket = TcpStream::connect(listener_addr_rx.await.unwrap()).await.unwrap(); - let ret = upgrade::apply_outbound( - socket.compat(), - NotificationsOut::new(PROTO_NAME, Vec::new(), &b"initial message"[..], 1024 * 1024), - upgrade::Version::V1, - ) - .await; + let ret = dial(listener_addr_rx.await.unwrap(), &b"initial message"[..]).await; assert!(ret.is_err()); }); - let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); - listener_addr_tx.send(listener.local_addr().unwrap()).unwrap(); - - let (socket, _) = listener.accept().await.unwrap(); - let NotificationsInOpen { handshake, mut substream, .. } = upgrade::apply_inbound( - socket.compat(), - NotificationsIn::new(PROTO_NAME, Vec::new(), 1024 * 1024), - ) - .await - .unwrap(); + let (handshake, mut substream) = listen_on_localhost(listener_addr_tx).await.unwrap(); assert_eq!(handshake, b"initial message"); // We check that a handshake that is too large gets refused. @@ -720,10 +704,10 @@ mod tests { let client = tokio::spawn(async move { let socket = TcpStream::connect(listener_addr_rx.await.unwrap()).await.unwrap(); - let NotificationsOutOpen { handshake, .. } = upgrade::apply_outbound( - socket.compat(), + let NotificationsOutOpen { handshake, .. } = OutboundUpgrade::upgrade_outbound( NotificationsOut::new(PROTO_NAME, Vec::new(), &b"initial message"[..], 1024 * 1024), - upgrade::Version::V1, + socket.compat(), + ProtocolName::Static(PROTO_NAME), ) .await .unwrap(); @@ -735,9 +719,10 @@ mod tests { listener_addr_tx.send(listener.local_addr().unwrap()).unwrap(); let (socket, _) = listener.accept().await.unwrap(); - let NotificationsInOpen { handshake, mut substream, .. } = upgrade::apply_inbound( - socket.compat(), + let NotificationsInOpen { handshake, mut substream, .. } = InboundUpgrade::upgrade_inbound( NotificationsIn::new(PROTO_NAME, Vec::new(), 1024 * 1024), + socket.compat(), + ProtocolName::Static(PROTO_NAME), ) .await .unwrap(); @@ -758,13 +743,19 @@ mod tests { let client = tokio::spawn(async move { let socket = TcpStream::connect(listener_addr_rx.await.unwrap()).await.unwrap(); - let NotificationsOutOpen { handshake, mut substream, .. } = upgrade::apply_outbound( - socket.compat(), - NotificationsOut::new(PROTO_NAME, Vec::new(), &b"initial message"[..], 1024 * 1024), - upgrade::Version::V1, - ) - .await - .unwrap(); + let NotificationsOutOpen { handshake, mut substream, .. } = + OutboundUpgrade::upgrade_outbound( + NotificationsOut::new( + PROTO_NAME, + Vec::new(), + &b"initial message"[..], + 1024 * 1024, + ), + socket.compat(), + ProtocolName::Static(PROTO_NAME), + ) + .await + .unwrap(); assert_eq!(handshake, b"hello world"); @@ -786,9 +777,10 @@ mod tests { listener_addr_tx.send(listener.local_addr().unwrap()).unwrap(); let (socket, _) = listener.accept().await.unwrap(); - let NotificationsInOpen { handshake, mut substream, .. } = upgrade::apply_inbound( - socket.compat(), + let NotificationsInOpen { handshake, mut substream, .. } = InboundUpgrade::upgrade_inbound( NotificationsIn::new(PROTO_NAME, Vec::new(), 1024 * 1024), + socket.compat(), + ProtocolName::Static(PROTO_NAME), ) .await .unwrap(); diff --git a/substrate/client/network/src/request_responses.rs b/substrate/client/network/src/request_responses.rs index fbf050a65713d1d66c361a1cde4e4a698089473d..3671d76ea630b1a83808a2a1ce3b2fa5d3ce4152 100644 --- a/substrate/client/network/src/request_responses.rs +++ b/substrate/client/network/src/request_responses.rs @@ -318,7 +318,6 @@ impl RequestResponsesBehaviour { let mut protocols = HashMap::new(); for protocol in list { let mut cfg = Config::default(); - cfg.set_connection_keep_alive(Duration::from_secs(10)); cfg.set_request_timeout(protocol.request_timeout); let protocol_support = if protocol.inbound_queue.is_some() { @@ -327,13 +326,13 @@ impl RequestResponsesBehaviour { ProtocolSupport::Outbound }; - let rq_rp = Behaviour::new( + let rq_rp = Behaviour::with_codec( GenericCodec { max_request_size: protocol.max_request_size, max_response_size: protocol.max_response_size, }, - iter::once(protocol.name.as_bytes().to_vec()) - .chain(protocol.fallback_names.iter().map(|name| name.as_bytes().to_vec())) + iter::once(protocol.name.clone()) + .chain(protocol.fallback_names) .zip(iter::repeat(protocol_support)), cfg, ); @@ -427,7 +426,7 @@ impl RequestResponsesBehaviour { impl NetworkBehaviour for RequestResponsesBehaviour { type ConnectionHandler = MultiHandler as NetworkBehaviour>::ConnectionHandler>; - type OutEvent = Event; + type ToSwarm = Event; fn handle_pending_inbound_connection( &mut self, @@ -543,9 +542,9 @@ impl NetworkBehaviour for RequestResponsesBehaviour { for (p, _) in self.protocols.values_mut() { NetworkBehaviour::on_swarm_event(p, FromSwarm::ListenerError(e)); }, - FromSwarm::ExpiredExternalAddr(e) => + FromSwarm::ExternalAddrExpired(e) => for (p, _) in self.protocols.values_mut() { - NetworkBehaviour::on_swarm_event(p, FromSwarm::ExpiredExternalAddr(e)); + NetworkBehaviour::on_swarm_event(p, FromSwarm::ExternalAddrExpired(e)); }, FromSwarm::NewListener(e) => for (p, _) in self.protocols.values_mut() { @@ -555,9 +554,13 @@ impl NetworkBehaviour for RequestResponsesBehaviour { for (p, _) in self.protocols.values_mut() { NetworkBehaviour::on_swarm_event(p, FromSwarm::ExpiredListenAddr(e)); }, - FromSwarm::NewExternalAddr(e) => + FromSwarm::NewExternalAddrCandidate(e) => for (p, _) in self.protocols.values_mut() { - NetworkBehaviour::on_swarm_event(p, FromSwarm::NewExternalAddr(e)); + NetworkBehaviour::on_swarm_event(p, FromSwarm::NewExternalAddrCandidate(e)); + }, + FromSwarm::ExternalAddrConfirmed(e) => + for (p, _) in self.protocols.values_mut() { + NetworkBehaviour::on_swarm_event(p, FromSwarm::ExternalAddrConfirmed(e)); }, FromSwarm::AddressChange(e) => for (p, _) in self.protocols.values_mut() { @@ -592,7 +595,7 @@ impl NetworkBehaviour for RequestResponsesBehaviour { &mut self, cx: &mut Context, params: &mut impl PollParameters, - ) -> Poll>> { + ) -> Poll>> { 'poll_all: loop { // Poll to see if any response is ready to be sent back. while let Poll::Ready(Some(outcome)) = self.pending_responses.poll_next_unpin(cx) { @@ -663,10 +666,18 @@ impl NetworkBehaviour for RequestResponsesBehaviour { handler, event: ((*protocol).to_string(), event), }), - ToSwarm::ReportObservedAddr { address, score } => - return Poll::Ready(ToSwarm::ReportObservedAddr { address, score }), ToSwarm::CloseConnection { peer_id, connection } => return Poll::Ready(ToSwarm::CloseConnection { peer_id, connection }), + ToSwarm::NewExternalAddrCandidate(observed) => + return Poll::Ready(ToSwarm::NewExternalAddrCandidate(observed)), + ToSwarm::ExternalAddrConfirmed(addr) => + return Poll::Ready(ToSwarm::ExternalAddrConfirmed(addr)), + ToSwarm::ExternalAddrExpired(addr) => + return Poll::Ready(ToSwarm::ExternalAddrExpired(addr)), + ToSwarm::ListenOn { opts } => + return Poll::Ready(ToSwarm::ListenOn { opts }), + ToSwarm::RemoveListener { id } => + return Poll::Ready(ToSwarm::RemoveListener { id }), }; match ev { @@ -950,7 +961,7 @@ pub struct GenericCodec { #[async_trait::async_trait] impl Codec for GenericCodec { - type Protocol = Vec; + type Protocol = ProtocolName; type Request = Vec; type Response = Result, ()>; @@ -1078,7 +1089,7 @@ mod tests { }, identity::Keypair, noise, - swarm::{Executor, Swarm, SwarmBuilder, SwarmEvent}, + swarm::{Config as SwarmConfig, Executor, Swarm, SwarmEvent}, Multiaddr, }; use std::{iter, time::Duration}; @@ -1104,16 +1115,18 @@ mod tests { let behaviour = RequestResponsesBehaviour::new(list, Arc::new(MockPeerStore {})).unwrap(); let runtime = tokio::runtime::Runtime::new().unwrap(); - let mut swarm = SwarmBuilder::with_executor( + + let mut swarm = Swarm::new( transport, behaviour, keypair.public().to_peer_id(), - TokioExecutor(runtime), - ) - .build(); + SwarmConfig::with_executor(TokioExecutor(runtime)), + ); + let listen_addr: Multiaddr = format!("/memory/{}", rand::random::()).parse().unwrap(); swarm.listen_on(listen_addr.clone()).unwrap(); + (swarm, listen_addr) } diff --git a/substrate/client/network/src/service.rs b/substrate/client/network/src/service.rs index 2cf4564e312c689a83b3d4ace09059e6e21547db..3a685787c48e603074ae63323963bbe9ce36a02b 100644 --- a/substrate/client/network/src/service.rs +++ b/substrate/client/network/src/service.rs @@ -61,18 +61,18 @@ use crate::{ use codec::DecodeAll; use either::Either; use futures::{channel::oneshot, prelude::*}; -use libp2p::identity::ed25519; #[allow(deprecated)] +use libp2p::swarm::THandlerErr; use libp2p::{ - connection_limits::Exceeded, + connection_limits::{ConnectionLimits, Exceeded}, core::{upgrade, ConnectedPoint, Endpoint}, identify::Info as IdentifyInfo, + identity::ed25519, kad::record::Key as KademliaKey, multiaddr::{self, Multiaddr}, - ping::Failure as PingFailure, swarm::{ - AddressScore, ConnectionError, ConnectionId, ConnectionLimits, DialError, Executor, - ListenError, NetworkBehaviour, Swarm, SwarmBuilder, SwarmEvent, THandlerErr, + Config as SwarmConfig, ConnectionError, ConnectionId, DialError, Executor, ListenError, + NetworkBehaviour, Swarm, SwarmEvent, }, PeerId, }; @@ -274,10 +274,6 @@ where let local_identity: ed25519::Keypair = local_identity.into(); let local_public: ed25519::PublicKey = local_public.into(); let local_peer_id: PeerId = local_peer_id.into(); - let listen_addresses: Vec = - network_config.listen_addresses.iter().cloned().map(Into::into).collect(); - let public_addresses: Vec = - network_config.public_addresses.iter().cloned().map(Into::into).collect(); network_config.boot_nodes = network_config .boot_nodes @@ -559,6 +555,11 @@ where request_response_protocols, Arc::clone(&peer_store_handle), external_addresses.clone(), + ConnectionLimits::default() + .with_max_established_per_peer(Some(crate::MAX_CONNECTIONS_PER_PEER as u32)) + .with_max_established_incoming(Some( + crate::MAX_CONNECTIONS_ESTABLISHED_INCOMING, + )), ); match result { @@ -568,37 +569,27 @@ where } }; - let builder = { + let swarm = { struct SpawnImpl(F); impl + Send>>)> Executor for SpawnImpl { fn exec(&self, f: Pin + Send>>) { (self.0)(f) } } - SwarmBuilder::with_executor( - transport, - behaviour, - local_peer_id, - SpawnImpl(params.executor), - ) + + let config = SwarmConfig::with_executor(SpawnImpl(params.executor)) + .with_substream_upgrade_protocol_override(upgrade::Version::V1) + .with_notify_handler_buffer_size(NonZeroUsize::new(32).expect("32 != 0; qed")) + // NOTE: 24 is somewhat arbitrary and should be tuned in the future if + // necessary. See + .with_per_connection_event_buffer_size(24) + .with_max_negotiating_inbound_streams(2048) + .with_idle_connection_timeout(Duration::from_secs(10)); + + Swarm::new(transport, behaviour, local_peer_id, config) }; - #[allow(deprecated)] - let builder = builder - .connection_limits( - ConnectionLimits::default() - .with_max_established_per_peer(Some(crate::MAX_CONNECTIONS_PER_PEER as u32)) - .with_max_established_incoming(Some( - crate::MAX_CONNECTIONS_ESTABLISHED_INCOMING, - )), - ) - .substream_upgrade_protocol_override(upgrade::Version::V1) - .notify_handler_buffer_size(NonZeroUsize::new(32).expect("32 != 0; qed")) - // NOTE: 24 is somewhat arbitrary and should be tuned in the future if necessary. - // See - .per_connection_event_buffer_size(24) - .max_negotiating_inbound_streams(2048); - - (builder.build(), Arc::new(Libp2pBandwidthSink { sink: bandwidth })) + + (swarm, Arc::new(Libp2pBandwidthSink { sink: bandwidth })) }; // Initialize the metrics. @@ -614,19 +605,15 @@ where }; // Listen on multiaddresses. - for addr in &listen_addresses { - if let Err(err) = Swarm::>::listen_on(&mut swarm, addr.clone()) { + for addr in &network_config.listen_addresses { + if let Err(err) = Swarm::>::listen_on(&mut swarm, addr.clone().into()) { warn!(target: "sub-libp2p", "Can't listen on {} because: {:?}", addr, err) } } // Add external addresses. - for addr in &public_addresses { - Swarm::>::add_external_address( - &mut swarm, - addr.clone(), - AddressScore::Infinite, - ); + for addr in &network_config.public_addresses { + Swarm::>::add_external_address(&mut swarm, addr.clone().into()); } let listen_addresses_set = Arc::new(Mutex::new(HashSet::new())); @@ -807,7 +794,7 @@ where let peer_id = Swarm::>::local_peer_id(swarm).to_base58(); let listened_addresses = swarm.listeners().cloned().collect(); - let external_addresses = swarm.external_addresses().map(|r| &r.addr).cloned().collect(); + let external_addresses = swarm.external_addresses().cloned().collect(); NetworkState { peer_id, @@ -867,8 +854,7 @@ impl NetworkService { .into_iter() .map(|mut addr| { let peer = match addr.pop() { - Some(multiaddr::Protocol::P2p(key)) => PeerId::from_multihash(key) - .map_err(|_| "Invalid PeerId format".to_string())?, + Some(multiaddr::Protocol::P2p(peer_id)) => peer_id, _ => return Err("Missing PeerId from address".to_string()), }; @@ -1492,6 +1478,7 @@ where } /// Process the next event coming from `Swarm`. + #[allow(deprecated)] fn handle_swarm_event(&mut self, event: SwarmEvent>>) { match event { SwarmEvent::Behaviour(BehaviourOut::InboundRequest { protocol, result, .. }) => { @@ -1586,9 +1573,11 @@ where listen_addrs.truncate(30); } for addr in listen_addrs { - self.network_service - .behaviour_mut() - .add_self_reported_address_to_dht(&peer_id, &protocols, addr); + self.network_service.behaviour_mut().add_self_reported_address_to_dht( + &peer_id, + &protocols, + addr.clone(), + ); } self.peer_store_handle.add_known_peer(peer_id.into()); }, @@ -1705,8 +1694,14 @@ where } } }, - SwarmEvent::ConnectionClosed { peer_id, cause, endpoint, num_established } => { - debug!(target: "sub-libp2p", "Libp2p => Disconnected({:?}, {:?})", peer_id, cause); + SwarmEvent::ConnectionClosed { + connection_id, + peer_id, + cause, + endpoint, + num_established, + } => { + debug!(target: "sub-libp2p", "Libp2p => Disconnected({peer_id:?} via {connection_id:?}, {cause:?})"); if let Some(metrics) = self.metrics.as_ref() { let direction = match endpoint { ConnectedPoint::Dialer { .. } => "out", @@ -1715,11 +1710,13 @@ where let reason = match cause { Some(ConnectionError::IO(_)) => "transport-error", Some(ConnectionError::Handler(Either::Left(Either::Left( - Either::Right(Either::Left(PingFailure::Timeout)), - )))) => "ping-timeout", - Some(ConnectionError::Handler(Either::Left(Either::Left( - Either::Left(NotifsHandlerError::SyncNotificationsClogged), + Either::Left(Either::Right( + NotifsHandlerError::SyncNotificationsClogged, + )), )))) => "sync-notifications-clogged", + Some(ConnectionError::Handler(Either::Left(Either::Left( + Either::Right(Either::Left(_)), + )))) => "ping-timeout", Some(ConnectionError::Handler(_)) => "protocol-error", Some(ConnectionError::KeepAliveTimeout) => "keep-alive-timeout", None => "actively-closed", @@ -1746,12 +1743,11 @@ where } self.listen_addresses.lock().remove(&address); }, - SwarmEvent::OutgoingConnectionError { peer_id, error } => { + SwarmEvent::OutgoingConnectionError { connection_id, peer_id, error } => { if let Some(peer_id) = peer_id { trace!( target: "sub-libp2p", - "Libp2p => Failed to reach {:?}: {}", - peer_id, error, + "Libp2p => Failed to reach {peer_id:?} via {connection_id:?}: {error}", ); let not_reported = !self.reported_invalid_boot_nodes.contains(&peer_id); @@ -1789,12 +1785,9 @@ where } else { None }, - DialError::ConnectionLimit(_) => Some("limit-reached"), - DialError::InvalidPeerId(_) | - DialError::WrongPeerId { .. } | - DialError::LocalPeerId { .. } => Some("invalid-peer-id"), + DialError::LocalPeerId { .. } => Some("local-peer-id"), + DialError::WrongPeerId { .. } => Some("invalid-peer-id"), DialError::Transport(_) => Some("transport-error"), - DialError::Banned | DialError::NoAddresses | DialError::DialPeerConditionFalse(_) | DialError::Aborted => None, // ignore them @@ -1804,21 +1797,24 @@ where } } }, - SwarmEvent::Dialing(peer_id) => { - trace!(target: "sub-libp2p", "Libp2p => Dialing({:?})", peer_id) + SwarmEvent::Dialing { connection_id, peer_id } => { + trace!(target: "sub-libp2p", "Libp2p => Dialing({peer_id:?}) via {connection_id:?}") }, - SwarmEvent::IncomingConnection { local_addr, send_back_addr } => { - trace!(target: "sub-libp2p", "Libp2p => IncomingConnection({},{}))", - local_addr, send_back_addr); + SwarmEvent::IncomingConnection { connection_id, local_addr, send_back_addr } => { + trace!(target: "sub-libp2p", "Libp2p => IncomingConnection({local_addr},{send_back_addr} via {connection_id:?}))"); if let Some(metrics) = self.metrics.as_ref() { metrics.incoming_connections_total.inc(); } }, - SwarmEvent::IncomingConnectionError { local_addr, send_back_addr, error } => { + SwarmEvent::IncomingConnectionError { + connection_id, + local_addr, + send_back_addr, + error, + } => { debug!( target: "sub-libp2p", - "Libp2p => IncomingConnectionError({},{}): {}", - local_addr, send_back_addr, error, + "Libp2p => IncomingConnectionError({local_addr},{send_back_addr} via {connection_id:?}): {error}" ); if let Some(metrics) = self.metrics.as_ref() { #[allow(deprecated)] @@ -1829,7 +1825,6 @@ where } else { None }, - ListenError::ConnectionLimit(_) => Some("limit-reached"), ListenError::WrongPeerId { .. } | ListenError::LocalPeerId { .. } => Some("invalid-peer-id"), ListenError::Transport(_) => Some("transport-error"), @@ -1844,17 +1839,6 @@ where } } }, - #[allow(deprecated)] - SwarmEvent::BannedPeer { peer_id, endpoint } => { - debug!( - target: "sub-libp2p", - "Libp2p => BannedPeer({}). Connected via {:?}.", - peer_id, endpoint, - ); - if let Some(metrics) = self.metrics.as_ref() { - metrics.incoming_connections_errors_total.with_label_values(&["banned"]).inc(); - } - }, SwarmEvent::ListenerClosed { reason, addresses, .. } => { if let Some(metrics) = self.metrics.as_ref() { metrics.listeners_local_addresses.sub(addresses.len() as u64); diff --git a/substrate/client/network/src/transport.rs b/substrate/client/network/src/transport.rs index 4136b34fc0e8e728b4d1a96e3ad5d8517ee4b552..ed7e7c574e16f41ef51d85b41ac041486dde0efd 100644 --- a/substrate/client/network/src/transport.rs +++ b/substrate/client/network/src/transport.rs @@ -57,7 +57,7 @@ pub fn build_transport( // Main transport: DNS(TCP) let tcp_config = tcp::Config::new().nodelay(true); let tcp_trans = tcp::tokio::Transport::new(tcp_config.clone()); - let dns_init = dns::TokioDnsConfig::system(tcp_trans); + let dns_init = dns::tokio::Transport::system(tcp_trans); Either::Left(if let Ok(dns) = dns_init { // WS + WSS transport @@ -66,7 +66,7 @@ pub fn build_transport( // unresolved addresses (BUT WSS transport itself needs an instance of DNS transport to // resolve and dial addresses). let tcp_trans = tcp::tokio::Transport::new(tcp_config); - let dns_for_wss = dns::TokioDnsConfig::system(tcp_trans) + let dns_for_wss = dns::tokio::Transport::system(tcp_trans) .expect("same system_conf & resolver to work"); Either::Left(websocket::WsConfig::new(dns_for_wss).or_transport(dns)) } else { diff --git a/substrate/client/network/src/types.rs b/substrate/client/network/src/types.rs index 25517599469e66294563575f1fbe69cc21240ceb..0652bbcdddecf6b4833f5ae762b8602b2958a56c 100644 --- a/substrate/client/network/src/types.rs +++ b/substrate/client/network/src/types.rs @@ -18,8 +18,6 @@ //! `sc-network` type definitions -use libp2p::core::upgrade; - use std::{ borrow::Borrow, fmt, @@ -94,9 +92,9 @@ impl fmt::Display for ProtocolName { } } -impl upgrade::ProtocolName for ProtocolName { - fn protocol_name(&self) -> &[u8] { - (self as &str).as_bytes() +impl AsRef for ProtocolName { + fn as_ref(&self) -> &str { + self as &str } } diff --git a/substrate/client/network/statement/Cargo.toml b/substrate/client/network/statement/Cargo.toml index 0dfaa491b65c93acb50f44bb002d655043317d99..4cced49fee7913d3163a509e0e32de9d6c978dcf 100644 --- a/substrate/client/network/statement/Cargo.toml +++ b/substrate/client/network/statement/Cargo.toml @@ -16,17 +16,16 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -array-bytes = "6.2.2" -async-channel = "1.8.0" -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } -futures = "0.3.30" -libp2p = "0.51.4" +array-bytes = { workspace = true, default-features = true } +async-channel = { workspace = true } +codec = { features = ["derive"], workspace = true, default-features = true } +futures = { workspace = true } log = { workspace = true, default-features = true } -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../../utils/prometheus" } -sc-network-common = { path = "../common" } -sc-network-sync = { path = "../sync" } -sc-network-types = { path = "../types" } -sc-network = { path = ".." } -sp-consensus = { path = "../../../primitives/consensus/common" } -sp-runtime = { path = "../../../primitives/runtime" } -sp-statement-store = { path = "../../../primitives/statement-store" } +prometheus-endpoint = { workspace = true, default-features = true } +sc-network-common = { workspace = true, default-features = true } +sc-network-sync = { workspace = true, default-features = true } +sc-network-types = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-statement-store = { workspace = true, default-features = true } diff --git a/substrate/client/network/sync/Cargo.toml b/substrate/client/network/sync/Cargo.toml index 964090444b22afdeca073ebc25d0be71817f1248..17e3e2119d7e811926a139193c8228ebe2cba1fb 100644 --- a/substrate/client/network/sync/Cargo.toml +++ b/substrate/client/network/sync/Cargo.toml @@ -16,43 +16,43 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [build-dependencies] -prost-build = "0.12.4" +prost-build = { workspace = true } [dependencies] -array-bytes = "6.2.2" -async-channel = "1.8.0" -async-trait = "0.1.79" -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } -futures = "0.3.30" -futures-timer = "3.0.2" -libp2p = "0.51.4" +array-bytes = { workspace = true, default-features = true } +async-channel = { workspace = true } +async-trait = { workspace = true } +codec = { features = ["derive"], workspace = true, default-features = true } +futures = { workspace = true } +futures-timer = { workspace = true } +libp2p = { workspace = true } log = { workspace = true, default-features = true } -mockall = "0.11.3" -prost = "0.12.4" -schnellru = "0.2.1" -smallvec = "1.11.0" +mockall = { workspace = true } +prost = { workspace = true } +schnellru = { workspace = true } +smallvec = { workspace = true, default-features = true } thiserror = { workspace = true } -tokio-stream = "0.1.14" -tokio = { version = "1.32.0", features = ["macros", "time"] } -fork-tree = { path = "../../../utils/fork-tree" } -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../../utils/prometheus" } -sc-client-api = { path = "../../api" } -sc-consensus = { path = "../../consensus/common" } -sc-network = { path = ".." } -sc-network-common = { path = "../common" } -sc-network-types = { path = "../types" } -sc-utils = { path = "../../utils" } -sp-arithmetic = { path = "../../../primitives/arithmetic" } -sp-blockchain = { path = "../../../primitives/blockchain" } -sp-consensus = { path = "../../../primitives/consensus/common" } -sp-core = { path = "../../../primitives/core" } -sp-consensus-grandpa = { path = "../../../primitives/consensus/grandpa" } -sp-runtime = { path = "../../../primitives/runtime" } +tokio-stream = { workspace = true } +tokio = { features = ["macros", "time"], workspace = true, default-features = true } +fork-tree = { workspace = true, default-features = true } +prometheus-endpoint = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sc-network-common = { workspace = true, default-features = true } +sc-network-types = { workspace = true, default-features = true } +sc-utils = { workspace = true, default-features = true } +sp-arithmetic = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-consensus = { 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 } [dev-dependencies] -mockall = "0.11.3" -quickcheck = { version = "1.0.3", default-features = false } -sc-block-builder = { path = "../../block-builder" } -sp-test-primitives = { path = "../../../primitives/test-primitives" } -sp-tracing = { path = "../../../primitives/tracing" } -substrate-test-runtime-client = { path = "../../../test-utils/runtime/client" } +mockall = { workspace = true } +quickcheck = { workspace = true } +sc-block-builder = { workspace = true, default-features = true } +sp-test-primitives = { workspace = true } +sp-tracing = { workspace = true, default-features = true } +substrate-test-runtime-client = { workspace = true } diff --git a/substrate/client/network/test/Cargo.toml b/substrate/client/network/test/Cargo.toml index f70e4847f59f32ee7418b370cb60339d3ff12ef7..74b43173508be640a1d828539a71696120f8e2f7 100644 --- a/substrate/client/network/test/Cargo.toml +++ b/substrate/client/network/test/Cargo.toml @@ -16,28 +16,28 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -tokio = "1.37" -async-trait = "0.1.79" -futures = "0.3.30" -futures-timer = "3.0.1" -libp2p = "0.51.4" +tokio = { workspace = true, default-features = true } +async-trait = { workspace = true } +futures = { workspace = true } +futures-timer = { workspace = true } +libp2p = { workspace = true } log = { workspace = true, default-features = true } -parking_lot = "0.12.1" -rand = "0.8.5" -sc-block-builder = { path = "../../block-builder" } -sc-client-api = { path = "../../api" } -sc-consensus = { path = "../../consensus/common" } -sc-network = { path = ".." } -sc-network-common = { path = "../common" } -sc-network-types = { path = "../types" } -sc-utils = { path = "../../utils" } -sc-network-light = { path = "../light" } -sc-network-sync = { path = "../sync" } -sc-service = { path = "../../service", default-features = false, features = ["test-helpers"] } -sp-blockchain = { path = "../../../primitives/blockchain" } -sp-consensus = { path = "../../../primitives/consensus/common" } -sp-core = { path = "../../../primitives/core" } -sp-runtime = { path = "../../../primitives/runtime" } -sp-tracing = { path = "../../../primitives/tracing" } -substrate-test-runtime = { path = "../../../test-utils/runtime" } -substrate-test-runtime-client = { path = "../../../test-utils/runtime/client" } +parking_lot = { workspace = true, default-features = true } +rand = { workspace = true, default-features = true } +sc-block-builder = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sc-network-common = { workspace = true, default-features = true } +sc-network-types = { workspace = true, default-features = true } +sc-utils = { workspace = true, default-features = true } +sc-network-light = { workspace = true, default-features = true } +sc-network-sync = { workspace = true, default-features = true } +sc-service = { features = ["test-helpers"], workspace = true } +sp-blockchain = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +substrate-test-runtime = { workspace = true } +substrate-test-runtime-client = { workspace = true } diff --git a/substrate/client/network/test/src/lib.rs b/substrate/client/network/test/src/lib.rs index 8a8f9608051af0bcb523b405585ad7c0b81b4ae2..221c8515d6d416a691aaf59128299173064af295 100644 --- a/substrate/client/network/test/src/lib.rs +++ b/substrate/client/network/test/src/lib.rs @@ -114,7 +114,7 @@ impl PassThroughVerifier { #[async_trait::async_trait] impl Verifier for PassThroughVerifier { async fn verify( - &mut self, + &self, mut block: BlockImportParams, ) -> Result, String> { if block.fork_choice.is_none() { @@ -210,7 +210,7 @@ impl BlockImport for PeersClient { type Error = ConsensusError; async fn check_block( - &mut self, + &self, block: BlockCheckParams, ) -> Result { self.client.check_block(block).await @@ -600,7 +600,7 @@ where type Error = ConsensusError; async fn check_block( - &mut self, + &self, block: BlockCheckParams, ) -> Result { self.inner.check_block(block).await @@ -622,10 +622,7 @@ struct VerifierAdapter { #[async_trait::async_trait] impl Verifier for VerifierAdapter { - async fn verify( - &mut self, - block: BlockImportParams, - ) -> Result, String> { + async fn verify(&self, block: BlockImportParams) -> Result, String> { let hash = block.header.hash(); self.verifier.lock().await.verify(block).await.map_err(|e| { self.failed_verifications.lock().insert(hash, e.clone()); diff --git a/substrate/client/network/test/src/service.rs b/substrate/client/network/test/src/service.rs index 150c1db7560e6d589e21e9aecb2add06fc57a47c..c4a2b261081e6b101bf4620fd379996b3ae32a69 100644 --- a/substrate/client/network/test/src/service.rs +++ b/substrate/client/network/test/src/service.rs @@ -134,7 +134,7 @@ impl TestNetworkBuilder { #[async_trait::async_trait] impl sc_consensus::Verifier for PassThroughVerifier { async fn verify( - &mut self, + &self, mut block: sc_consensus::BlockImportParams, ) -> Result, String> { block.finalized = self.0; diff --git a/substrate/client/network/transactions/Cargo.toml b/substrate/client/network/transactions/Cargo.toml index d871b59b37bb120783aa2e27a23aa9ee814b3ddf..eb907b606d584bde259f083b63d37067476a5e5b 100644 --- a/substrate/client/network/transactions/Cargo.toml +++ b/substrate/client/network/transactions/Cargo.toml @@ -16,16 +16,15 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -array-bytes = "6.2.2" -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } -futures = "0.3.30" -libp2p = "0.51.4" +array-bytes = { workspace = true, default-features = true } +codec = { features = ["derive"], workspace = true, default-features = true } +futures = { workspace = true } log = { workspace = true, default-features = true } -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../../utils/prometheus" } -sc-network = { path = ".." } -sc-network-common = { path = "../common" } -sc-network-sync = { path = "../sync" } -sc-network-types = { path = "../types" } -sc-utils = { path = "../../utils" } -sp-runtime = { path = "../../../primitives/runtime" } -sp-consensus = { path = "../../../primitives/consensus/common" } +prometheus-endpoint = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sc-network-common = { workspace = true, default-features = true } +sc-network-sync = { workspace = true, default-features = true } +sc-network-types = { workspace = true, default-features = true } +sc-utils = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } diff --git a/substrate/client/network/types/Cargo.toml b/substrate/client/network/types/Cargo.toml index a9334aaa1705987a35322921616188113f011ed8..811ccddbef930d3264c7cc4a8d2310a92b6d714a 100644 --- a/substrate/client/network/types/Cargo.toml +++ b/substrate/client/network/types/Cargo.toml @@ -10,15 +10,16 @@ repository.workspace = true documentation = "https://docs.rs/sc-network-types" [dependencies] -bs58 = "0.5.0" -ed25519-dalek = "2.1" -libp2p-identity = { version = "0.1.3", features = ["ed25519", "peerid"] } -litep2p = "0.5.0" -multiaddr = "0.17.0" -multihash = { version = "0.17.0", default-features = false, features = ["identity", "multihash-impl", "sha2", "std"] } -rand = "0.8.5" -thiserror = "1.0.48" -zeroize = { version = "1.7.0", default-features = false } +bs58 = { workspace = true, default-features = true } +ed25519-dalek = { workspace = true, default-features = true } +libp2p-identity = { features = ["ed25519", "peerid", "rand"], workspace = true } +litep2p = { workspace = true } +log = { workspace = true, default-features = true } +multiaddr = { workspace = true } +multihash = { workspace = true } +rand = { workspace = true, default-features = true } +thiserror = { workspace = true } +zeroize = { workspace = true } [dev-dependencies] -quickcheck = "1.0.3" +quickcheck = { workspace = true, default-features = true } diff --git a/substrate/client/network/types/src/multiaddr.rs b/substrate/client/network/types/src/multiaddr.rs index 312bef9baab1254a963d5d886994d0812ea93382..925e24fe70d6d374e82dbee266a625875eecc78e 100644 --- a/substrate/client/network/types/src/multiaddr.rs +++ b/substrate/client/network/types/src/multiaddr.rs @@ -20,8 +20,10 @@ use litep2p::types::multiaddr::{ Error as LiteP2pError, Iter as LiteP2pIter, Multiaddr as LiteP2pMultiaddr, Protocol as LiteP2pProtocol, }; +use multiaddr::Multiaddr as LibP2pMultiaddr; use std::{ fmt::{self, Debug, Display}, + net::{IpAddr, Ipv4Addr, Ipv6Addr}, str::FromStr, }; @@ -102,6 +104,39 @@ impl From for LiteP2pMultiaddr { } } +impl From for Multiaddr { + fn from(multiaddr: LibP2pMultiaddr) -> Self { + multiaddr.into_iter().map(Into::into).collect() + } +} + +impl From for LibP2pMultiaddr { + fn from(multiaddr: Multiaddr) -> Self { + multiaddr.into_iter().map(Into::into).collect() + } +} + +impl From for Multiaddr { + fn from(v: IpAddr) -> Multiaddr { + match v { + IpAddr::V4(a) => a.into(), + IpAddr::V6(a) => a.into(), + } + } +} + +impl From for Multiaddr { + fn from(v: Ipv4Addr) -> Multiaddr { + Protocol::Ip4(v).into() + } +} + +impl From for Multiaddr { + fn from(v: Ipv6Addr) -> Multiaddr { + Protocol::Ip6(v).into() + } +} + impl TryFrom> for Multiaddr { type Error = ParseError; diff --git a/substrate/client/network/types/src/multiaddr/protocol.rs b/substrate/client/network/types/src/multiaddr/protocol.rs index 800d08fe36bd657b855869bcb69a808961e32a5a..aca3a31136860d56d5058301a85ced87fa5ab0f3 100644 --- a/substrate/client/network/types/src/multiaddr/protocol.rs +++ b/substrate/client/network/types/src/multiaddr/protocol.rs @@ -17,12 +17,18 @@ // along with this program. If not, see . use crate::multihash::Multihash; +use libp2p_identity::PeerId; use litep2p::types::multiaddr::Protocol as LiteP2pProtocol; +use multiaddr::Protocol as LibP2pProtocol; use std::{ borrow::Cow, - net::{Ipv4Addr, Ipv6Addr}, + fmt::{self, Debug, Display}, + net::{IpAddr, Ipv4Addr, Ipv6Addr}, }; +// Log target for this file. +const LOG_TARGET: &str = "sub-libp2p"; + /// [`Protocol`] describes all possible multiaddress protocols. #[derive(PartialEq, Eq, Clone, Debug)] pub enum Protocol<'a> { @@ -60,6 +66,37 @@ pub enum Protocol<'a> { Wss(Cow<'a, str>), } +impl<'a> Display for Protocol<'a> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let protocol = LiteP2pProtocol::from(self.clone()); + Display::fmt(&protocol, f) + } +} + +impl<'a> From for Protocol<'a> { + #[inline] + fn from(addr: IpAddr) -> Self { + match addr { + IpAddr::V4(addr) => Protocol::Ip4(addr), + IpAddr::V6(addr) => Protocol::Ip6(addr), + } + } +} + +impl<'a> From for Protocol<'a> { + #[inline] + fn from(addr: Ipv4Addr) -> Self { + Protocol::Ip4(addr) + } +} + +impl<'a> From for Protocol<'a> { + #[inline] + fn from(addr: Ipv6Addr) -> Self { + Protocol::Ip6(addr) + } +} + impl<'a> From> for Protocol<'a> { fn from(protocol: LiteP2pProtocol<'a>) -> Self { match protocol { @@ -136,3 +173,102 @@ impl<'a> From> for LiteP2pProtocol<'a> { } } } + +impl<'a> From> for Protocol<'a> { + fn from(protocol: LibP2pProtocol<'a>) -> Self { + match protocol { + LibP2pProtocol::Dccp(port) => Protocol::Dccp(port), + LibP2pProtocol::Dns(str) => Protocol::Dns(str), + LibP2pProtocol::Dns4(str) => Protocol::Dns4(str), + LibP2pProtocol::Dns6(str) => Protocol::Dns6(str), + LibP2pProtocol::Dnsaddr(str) => Protocol::Dnsaddr(str), + LibP2pProtocol::Http => Protocol::Http, + LibP2pProtocol::Https => Protocol::Https, + LibP2pProtocol::Ip4(ipv4_addr) => Protocol::Ip4(ipv4_addr), + LibP2pProtocol::Ip6(ipv6_addr) => Protocol::Ip6(ipv6_addr), + LibP2pProtocol::P2pWebRtcDirect => Protocol::P2pWebRtcDirect, + LibP2pProtocol::P2pWebRtcStar => Protocol::P2pWebRtcStar, + LibP2pProtocol::Certhash(multihash) => Protocol::Certhash(multihash.into()), + LibP2pProtocol::P2pWebSocketStar => Protocol::P2pWebSocketStar, + LibP2pProtocol::Memory(port) => Protocol::Memory(port), + LibP2pProtocol::Onion(str, port) => Protocol::Onion(str, port), + LibP2pProtocol::Onion3(addr) => Protocol::Onion3(Cow::Owned(*addr.hash()), addr.port()), + LibP2pProtocol::P2p(peer_id) => Protocol::P2p((*peer_id.as_ref()).into()), + LibP2pProtocol::P2pCircuit => Protocol::P2pCircuit, + LibP2pProtocol::Quic => Protocol::Quic, + LibP2pProtocol::QuicV1 => Protocol::QuicV1, + LibP2pProtocol::Sctp(port) => Protocol::Sctp(port), + LibP2pProtocol::Tcp(port) => Protocol::Tcp(port), + LibP2pProtocol::Tls => Protocol::Tls, + LibP2pProtocol::Noise => Protocol::Noise, + LibP2pProtocol::Udp(port) => Protocol::Udp(port), + LibP2pProtocol::Udt => Protocol::Udt, + LibP2pProtocol::Unix(str) => Protocol::Unix(str), + LibP2pProtocol::Utp => Protocol::Utp, + LibP2pProtocol::Ws(str) => Protocol::Ws(str), + LibP2pProtocol::Wss(str) => Protocol::Wss(str), + protocol => { + log::error!( + target: LOG_TARGET, + "Got unsupported multiaddr protocol '{}'", + protocol.tag(), + ); + // Strictly speaking, this conversion is incorrect. But making protocol conversion + // fallible would significantly complicate the client code. As DCCP transport is not + // used by substrate, this conversion should be safe. + // Also, as of `multiaddr-18.1`, all enum variants are actually covered. + Protocol::Dccp(0) + }, + } + } +} + +impl<'a> From> for LibP2pProtocol<'a> { + fn from(protocol: Protocol<'a>) -> Self { + match protocol { + Protocol::Dccp(port) => LibP2pProtocol::Dccp(port), + Protocol::Dns(str) => LibP2pProtocol::Dns(str), + Protocol::Dns4(str) => LibP2pProtocol::Dns4(str), + Protocol::Dns6(str) => LibP2pProtocol::Dns6(str), + Protocol::Dnsaddr(str) => LibP2pProtocol::Dnsaddr(str), + Protocol::Http => LibP2pProtocol::Http, + Protocol::Https => LibP2pProtocol::Https, + Protocol::Ip4(ipv4_addr) => LibP2pProtocol::Ip4(ipv4_addr), + Protocol::Ip6(ipv6_addr) => LibP2pProtocol::Ip6(ipv6_addr), + Protocol::P2pWebRtcDirect => LibP2pProtocol::P2pWebRtcDirect, + Protocol::P2pWebRtcStar => LibP2pProtocol::P2pWebRtcStar, + // Protocol #280 is called `WebRTC` in multiaddr-17.0 and `WebRTCDirect` in + // multiaddr-18.1. + Protocol::WebRTC => LibP2pProtocol::WebRTCDirect, + Protocol::Certhash(multihash) => LibP2pProtocol::Certhash(multihash.into()), + Protocol::P2pWebSocketStar => LibP2pProtocol::P2pWebSocketStar, + Protocol::Memory(port) => LibP2pProtocol::Memory(port), + Protocol::Onion(str, port) => LibP2pProtocol::Onion(str, port), + Protocol::Onion3(str, port) => LibP2pProtocol::Onion3((str.into_owned(), port).into()), + Protocol::P2p(multihash) => + LibP2pProtocol::P2p(PeerId::from_multihash(multihash.into()).unwrap_or_else(|_| { + // This is better than making conversion fallible and complicating the + // client code. + log::error!( + target: LOG_TARGET, + "Received multiaddr with p2p multihash which is not a valid \ + peer_id. Replacing with random peer_id." + ); + PeerId::random() + })), + Protocol::P2pCircuit => LibP2pProtocol::P2pCircuit, + Protocol::Quic => LibP2pProtocol::Quic, + Protocol::QuicV1 => LibP2pProtocol::QuicV1, + Protocol::Sctp(port) => LibP2pProtocol::Sctp(port), + Protocol::Tcp(port) => LibP2pProtocol::Tcp(port), + Protocol::Tls => LibP2pProtocol::Tls, + Protocol::Noise => LibP2pProtocol::Noise, + Protocol::Udp(port) => LibP2pProtocol::Udp(port), + Protocol::Udt => LibP2pProtocol::Udt, + Protocol::Unix(str) => LibP2pProtocol::Unix(str), + Protocol::Utp => LibP2pProtocol::Utp, + Protocol::Ws(str) => LibP2pProtocol::Ws(str), + Protocol::Wss(str) => LibP2pProtocol::Wss(str), + } + } +} diff --git a/substrate/client/network/types/src/multihash.rs b/substrate/client/network/types/src/multihash.rs index 91f5b6353a7187e72fb49b1731ed1be6d8319bff..321211c598d385a903f3e0b24baa9e6c5c3d2965 100644 --- a/substrate/client/network/types/src/multihash.rs +++ b/substrate/client/network/types/src/multihash.rs @@ -156,22 +156,20 @@ impl From for LiteP2pMultihash { } } -// TODO: uncomment this after upgrading `multihash` crate to v0.19.1. -// -// impl From> for Multihash { -// fn from(generic: multihash::MultihashGeneric<64>) -> Self { -// LiteP2pMultihash::wrap(generic.code(), generic.digest()) -// .expect("both have size 64; qed") -// .into() -// } -// } -// -// impl From for multihash::Multihash<64> { -// fn from(multihash: Multihash) -> Self { -// multihash::Multihash::<64>::wrap(multihash.code(), multihash.digest()) -// .expect("both have size 64; qed") -// } -// } +impl From> for Multihash { + fn from(generic: multihash::Multihash<64>) -> Self { + LiteP2pMultihash::wrap(generic.code(), generic.digest()) + .expect("both have size 64; qed") + .into() + } +} + +impl From for multihash::Multihash<64> { + fn from(multihash: Multihash) -> Self { + multihash::Multihash::<64>::wrap(multihash.code(), multihash.digest()) + .expect("both have size 64; qed") + } +} #[cfg(test)] mod tests { diff --git a/substrate/client/offchain/Cargo.toml b/substrate/client/offchain/Cargo.toml index 2944ff7f4f49dd879b35a1ba70b214824fbdd089..5046808f013d7d98668272b05dd32a978bfeb7e6 100644 --- a/substrate/client/offchain/Cargo.toml +++ b/substrate/client/offchain/Cargo.toml @@ -16,46 +16,45 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -array-bytes = "6.2.2" -bytes = "1.1" -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } -fnv = "1.0.6" -futures = "0.3.30" -futures-timer = "3.0.2" -hyper = { version = "0.14.16", features = ["http2", "stream"] } -hyper-rustls = { version = "0.24.0", features = ["http2"] } -libp2p = "0.51.4" -num_cpus = "1.13" -once_cell = "1.19" -parking_lot = "0.12.1" -rand = "0.8.5" -threadpool = "1.7" -tracing = "0.1.29" -sc-client-api = { path = "../api" } -sc-network = { path = "../network" } -sc-network-common = { path = "../network/common" } -sc-network-types = { path = "../network/types" } -sc-transaction-pool-api = { path = "../transaction-pool/api" } -sc-utils = { path = "../utils" } -sp-api = { path = "../../primitives/api" } -sp-core = { path = "../../primitives/core" } -sp-offchain = { path = "../../primitives/offchain" } -sp-runtime = { path = "../../primitives/runtime" } -sp-keystore = { path = "../../primitives/keystore" } -sp-externalities = { path = "../../primitives/externalities" } +array-bytes = { workspace = true, default-features = true } +bytes = { workspace = true, default-features = true } +codec = { features = ["derive"], workspace = true, default-features = true } +fnv = { workspace = true } +futures = { workspace = true } +futures-timer = { workspace = true } +hyper = { features = ["http2", "stream"], workspace = true, default-features = true } +hyper-rustls = { features = ["http2"], workspace = true } +num_cpus = { workspace = true } +once_cell = { workspace = true } +parking_lot = { workspace = true, default-features = true } +rand = { workspace = true, default-features = true } +threadpool = { workspace = true } +tracing = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sc-network-common = { workspace = true, default-features = true } +sc-network-types = { workspace = true, default-features = true } +sc-transaction-pool-api = { workspace = true, default-features = true } +sc-utils = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-offchain = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-externalities = { workspace = true, default-features = true } log = { workspace = true, default-features = true } [dev-dependencies] -async-trait = "0.1" -lazy_static = "1.4.0" -tokio = "1.37" -sc-block-builder = { path = "../block-builder" } -sc-client-db = { path = "../db", default-features = true } -sc-transaction-pool = { path = "../transaction-pool" } -sc-transaction-pool-api = { path = "../transaction-pool/api" } -sp-consensus = { path = "../../primitives/consensus/common" } -sp-tracing = { path = "../../primitives/tracing" } -substrate-test-runtime-client = { path = "../../test-utils/runtime/client" } +async-trait = { workspace = true } +lazy_static = { workspace = true } +tokio = { workspace = true, default-features = true } +sc-block-builder = { workspace = true, default-features = true } +sc-client-db = { default-features = true, workspace = true } +sc-transaction-pool = { workspace = true, default-features = true } +sc-transaction-pool-api = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +substrate-test-runtime-client = { workspace = true } [features] default = [] diff --git a/substrate/client/proposer-metrics/Cargo.toml b/substrate/client/proposer-metrics/Cargo.toml index f560ce2d65e6e6336c7fa372618c858616ca134e..98064049b297fe4039f09f7a525f8159cdb4ecf1 100644 --- a/substrate/client/proposer-metrics/Cargo.toml +++ b/substrate/client/proposer-metrics/Cargo.toml @@ -17,4 +17,4 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] log = { workspace = true, default-features = true } -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../utils/prometheus" } +prometheus-endpoint = { workspace = true, default-features = true } diff --git a/substrate/client/rpc-api/Cargo.toml b/substrate/client/rpc-api/Cargo.toml index d8f833e2b8d45eb217fe6f4f9d835038e6167705..fda81b31ee502f985dd9b0574b7231a2e6e83edb 100644 --- a/substrate/client/rpc-api/Cargo.toml +++ b/substrate/client/rpc-api/Cargo.toml @@ -16,16 +16,16 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12" } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { workspace = true, default-features = true } +scale-info = { features = ["derive"], workspace = true } serde = { features = ["derive"], workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } thiserror = { workspace = true } -sc-chain-spec = { path = "../chain-spec" } -sc-mixnet = { path = "../mixnet" } -sc-transaction-pool-api = { path = "../transaction-pool/api" } -sp-core = { path = "../../primitives/core" } -sp-rpc = { path = "../../primitives/rpc" } -sp-runtime = { path = "../../primitives/runtime" } -sp-version = { path = "../../primitives/version" } -jsonrpsee = { version = "0.22.5", features = ["client-core", "macros", "server-core"] } +sc-chain-spec = { workspace = true, default-features = true } +sc-mixnet = { workspace = true, default-features = true } +sc-transaction-pool-api = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-rpc = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-version = { workspace = true, default-features = true } +jsonrpsee = { features = ["client-core", "macros", "server-core"], workspace = true } diff --git a/substrate/client/rpc-servers/Cargo.toml b/substrate/client/rpc-servers/Cargo.toml index 7837c852a1c9b73992b9a24f911ce7bba937cdab..7986408d2b2f1765eb30af41ee11cf21f57e5521 100644 --- a/substrate/client/rpc-servers/Cargo.toml +++ b/substrate/client/rpc-servers/Cargo.toml @@ -16,16 +16,21 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -forwarded-header-value = "0.1.1" -futures = "0.3.30" -governor = "0.6.0" -http = "0.2.8" -hyper = "0.14.27" -ip_network = "0.4.1" -jsonrpsee = { version = "0.22", features = ["server"] } +forwarded-header-value = { workspace = true } +futures = { workspace = true } +governor = { workspace = true } +http-body-util = { workspace = true } +ip_network = { workspace = true } +jsonrpsee = { features = ["server"], workspace = true } log = { workspace = true, default-features = true } -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../utils/prometheus" } +prometheus-endpoint = { workspace = true, default-features = true } +serde = { workspace = true } serde_json = { workspace = true, default-features = true } -tokio = { version = "1.22.0", features = ["parking_lot"] } -tower = { version = "0.4.13", features = ["util"] } -tower-http = { version = "0.4.0", features = ["cors"] } +tokio = { features = ["parking_lot"], workspace = true, default-features = true } +tower = { workspace = true, features = ["util"] } +tower-http = { workspace = true, features = ["cors"] } + +# Dependencies outside of the polkadot-sdk workspace +# which requires hyper v1 and http v1 +http = "1.1" +hyper = "1.3" diff --git a/substrate/client/rpc-servers/src/lib.rs b/substrate/client/rpc-servers/src/lib.rs index ba1fcf5e36771008e139bc69ff492eb645e2bcae..619498b333365ff1fa54672bd6ad94507fcd6d27 100644 --- a/substrate/client/rpc-servers/src/lib.rs +++ b/substrate/client/rpc-servers/src/lib.rs @@ -23,21 +23,16 @@ pub mod middleware; pub mod utils; -use std::{ - convert::Infallible, error::Error as StdError, net::SocketAddr, num::NonZeroU32, time::Duration, -}; +use std::{error::Error as StdError, net::SocketAddr, num::NonZeroU32, sync::Arc, time::Duration}; -use hyper::{ - server::conn::AddrStream, - service::{make_service_fn, service_fn}, -}; use jsonrpsee::{ + core::BoxError, server::{ - middleware::http::ProxyGetRequestLayer, stop_channel, ws, PingConfig, StopHandle, - TowerServiceBuilder, + serve_with_graceful_shutdown, stop_channel, ws, PingConfig, StopHandle, TowerServiceBuilder, }, Methods, RpcModule, }; +use middleware::NodeHealthProxyLayer; use tokio::net::TcpListener; use tower::Service; use utils::{build_rpc_api, format_cors, get_proxy_ip, host_filtering, try_into_cors}; @@ -99,6 +94,7 @@ struct PerConnection { metrics: Option, tokio_handle: tokio::runtime::Handle, service_builder: TowerServiceBuilder, + rate_limit_whitelisted_ips: Arc>, } /// Start RPC server listening on given address. @@ -126,14 +122,14 @@ where rate_limit_trust_proxy_headers, } = config; - let std_listener = TcpListener::bind(addrs.as_slice()).await?.into_std()?; - let local_addr = std_listener.local_addr().ok(); + let listener = TcpListener::bind(addrs.as_slice()).await?; + let local_addr = listener.local_addr().ok(); let host_filter = host_filtering(cors.is_some(), local_addr); let http_middleware = tower::ServiceBuilder::new() .option_layer(host_filter) - // Proxy `GET /health` requests to internal `system_health` method. - .layer(ProxyGetRequestLayer::new("/health", "system_health")?) + // Proxy `GET /health, /health/readiness` requests to the internal `system_health` method. + .layer(NodeHealthProxyLayer::default()) .layer(try_into_cors(cors)?); let mut builder = jsonrpsee::server::Server::builder() @@ -163,20 +159,38 @@ where methods: build_rpc_api(rpc_api).into(), service_builder: builder.to_service_builder(), metrics, - tokio_handle, - stop_handle: stop_handle.clone(), + tokio_handle: tokio_handle.clone(), + stop_handle, + rate_limit_whitelisted_ips: Arc::new(rate_limit_whitelisted_ips), }; - let make_service = make_service_fn(move |addr: &AddrStream| { - let cfg = cfg.clone(); - let rate_limit_whitelisted_ips = rate_limit_whitelisted_ips.clone(); - let ip = addr.remote_addr().ip(); - - async move { - let cfg = cfg.clone(); - let rate_limit_whitelisted_ips = rate_limit_whitelisted_ips.clone(); + tokio_handle.spawn(async move { + loop { + let (sock, remote_addr) = tokio::select! { + res = listener.accept() => { + match res { + Ok(s) => s, + Err(e) => { + log::debug!(target: "rpc", "Failed to accept ipv4 connection: {:?}", e); + continue; + } + } + } + _ = cfg.stop_handle.clone().shutdown() => break, + }; + + let ip = remote_addr.ip(); + let cfg2 = cfg.clone(); + let svc = tower::service_fn(move |req: http::Request| { + let PerConnection { + methods, + service_builder, + metrics, + tokio_handle, + stop_handle, + rate_limit_whitelisted_ips, + } = cfg2.clone(); - Ok::<_, Infallible>(service_fn(move |req| { let proxy_ip = if rate_limit_trust_proxy_headers { get_proxy_ip(&req) } else { None }; @@ -193,9 +207,6 @@ where rate_limit }; - let PerConnection { service_builder, metrics, tokio_handle, stop_handle, methods } = - cfg.clone(); - let is_websocket = ws::is_upgrade_request(&req); let transport_label = if is_websocket { "ws" } else { "http" }; @@ -215,7 +226,6 @@ where let rpc_middleware = RpcServiceBuilder::new().option_layer(middleware_layer.clone()); - let mut svc = service_builder.set_rpc_middleware(rpc_middleware).build(methods, stop_handle); @@ -232,17 +242,19 @@ where }); } - svc.call(req).await + // https://github.com/rust-lang/rust/issues/102211 the error type can't be inferred + // to be `Box` so we need to convert it to + // a concrete type as workaround. + svc.call(req).await.map_err(|e| BoxError::from(e)) } - })) - } - }); - - let server = hyper::Server::from_tcp(std_listener)?.serve(make_service); + }); - tokio::spawn(async move { - let graceful = server.with_graceful_shutdown(async move { stop_handle.shutdown().await }); - let _ = graceful.await; + cfg.tokio_handle.spawn(serve_with_graceful_shutdown( + sock, + svc, + cfg.stop_handle.clone().shutdown(), + )); + } }); log::info!( diff --git a/substrate/client/rpc-servers/src/middleware/mod.rs b/substrate/client/rpc-servers/src/middleware/mod.rs index 88ed8b2f433580fa2d87f1a70eacc32019027f2a..0a14be4dacf59f2c3dcae90d64653461fe48eb37 100644 --- a/substrate/client/rpc-servers/src/middleware/mod.rs +++ b/substrate/client/rpc-servers/src/middleware/mod.rs @@ -32,9 +32,11 @@ use jsonrpsee::{ }; mod metrics; +mod node_health; mod rate_limit; pub use metrics::*; +pub use node_health::*; pub use rate_limit::*; const MAX_JITTER: Duration = Duration::from_millis(50); diff --git a/substrate/client/rpc-servers/src/middleware/node_health.rs b/substrate/client/rpc-servers/src/middleware/node_health.rs new file mode 100644 index 0000000000000000000000000000000000000000..69c9e0829ac98286e8ac4d5e6ddf55772862cd41 --- /dev/null +++ b/substrate/client/rpc-servers/src/middleware/node_health.rs @@ -0,0 +1,203 @@ +// This file is part of Substrate. + +// 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 . + +//! Middleware for handling `/health` and `/health/readiness` endpoints. + +use std::{ + error::Error, + future::Future, + pin::Pin, + task::{Context, Poll}, +}; + +use futures::future::FutureExt; +use http::{HeaderValue, Method, StatusCode, Uri}; +use jsonrpsee::{ + server::{HttpBody, HttpRequest, HttpResponse}, + types::{Response as RpcResponse, ResponseSuccess as RpcResponseSuccess}, +}; +use tower::Service; + +const RPC_SYSTEM_HEALTH_CALL: &str = r#"{"jsonrpc":"2.0","method":"system_health","id":0}"#; +const HEADER_VALUE_JSON: HeaderValue = HeaderValue::from_static("application/json; charset=utf-8"); + +/// Layer that applies [`NodeHealthProxy`] which +/// proxies `/health` and `/health/readiness` endpoints. +#[derive(Debug, Clone, Default)] +pub struct NodeHealthProxyLayer; + +impl tower::Layer for NodeHealthProxyLayer { + type Service = NodeHealthProxy; + + fn layer(&self, service: S) -> Self::Service { + NodeHealthProxy::new(service) + } +} + +/// Middleware that proxies `/health` and `/health/readiness` endpoints. +pub struct NodeHealthProxy(S); + +impl NodeHealthProxy { + /// Creates a new [`NodeHealthProxy`]. + pub fn new(service: S) -> Self { + Self(service) + } +} + +impl tower::Service> for NodeHealthProxy +where + S: Service, + S::Response: 'static, + S::Error: Into> + 'static, + S::Future: Send + 'static, +{ + type Response = S::Response; + type Error = Box; + type Future = + Pin> + Send + 'static>>; + + fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll> { + self.0.poll_ready(cx).map_err(Into::into) + } + + fn call(&mut self, req: http::Request) -> Self::Future { + let mut req = req.map(|body| HttpBody::new(body)); + let maybe_intercept = InterceptRequest::from_http(&req); + + // Modify the request and proxy it to `system_health` + if let InterceptRequest::Health | InterceptRequest::Readiness = maybe_intercept { + // RPC methods are accessed with `POST`. + *req.method_mut() = Method::POST; + // Precautionary remove the URI. + *req.uri_mut() = Uri::from_static("/"); + + // Requests must have the following headers: + req.headers_mut().insert(http::header::CONTENT_TYPE, HEADER_VALUE_JSON); + req.headers_mut().insert(http::header::ACCEPT, HEADER_VALUE_JSON); + + // Adjust the body to reflect the method call. + req = req.map(|_| HttpBody::from(RPC_SYSTEM_HEALTH_CALL)); + } + + // Call the inner service and get a future that resolves to the response. + let fut = self.0.call(req); + + async move { + let res = fut.await.map_err(|err| err.into())?; + + Ok(match maybe_intercept { + InterceptRequest::Deny => + http_response(StatusCode::METHOD_NOT_ALLOWED, HttpBody::empty()), + InterceptRequest::No => res, + InterceptRequest::Health => { + let health = parse_rpc_response(res.into_body()).await?; + http_ok_response(serde_json::to_string(&health)?) + }, + InterceptRequest::Readiness => { + let health = parse_rpc_response(res.into_body()).await?; + if (!health.is_syncing && health.peers > 0) || !health.should_have_peers { + http_ok_response(HttpBody::empty()) + } else { + http_internal_error() + } + }, + }) + } + .boxed() + } +} + +// NOTE: This is duplicated here to avoid dependency to the `RPC API`. +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(rename_all = "camelCase")] +struct Health { + /// Number of connected peers + pub peers: usize, + /// Is the node syncing + pub is_syncing: bool, + /// Should this node have any peers + /// + /// Might be false for local chains or when running without discovery. + pub should_have_peers: bool, +} + +fn http_ok_response>(body: S) -> HttpResponse { + http_response(StatusCode::OK, body) +} + +fn http_response>(status_code: StatusCode, body: S) -> HttpResponse { + HttpResponse::builder() + .status(status_code) + .header(http::header::CONTENT_TYPE, HEADER_VALUE_JSON) + .body(body.into()) + .expect("Header is valid; qed") +} + +fn http_internal_error() -> HttpResponse { + http_response(hyper::StatusCode::INTERNAL_SERVER_ERROR, HttpBody::empty()) +} + +async fn parse_rpc_response( + body: HttpBody, +) -> Result> { + use http_body_util::BodyExt; + + let bytes = body.collect().await?.to_bytes(); + + let raw_rp = serde_json::from_slice::>(&bytes)?; + let rp = RpcResponseSuccess::::try_from(raw_rp)?; + + Ok(rp.result) +} + +/// Whether the request should be treated as ordinary RPC call or be modified. +enum InterceptRequest { + /// Proxy `/health` to `system_health`. + Health, + /// Checks if node has at least one peer and is not doing major syncing. + /// + /// Returns HTTP status code 200 on success otherwise HTTP status code 500 is returned. + Readiness, + /// Treat as a ordinary RPC call and don't modify the request or response. + No, + /// Deny health or readiness calls that is not HTTP GET request. + /// + /// Returns HTTP status code 405. + Deny, +} + +impl InterceptRequest { + fn from_http(req: &HttpRequest) -> InterceptRequest { + match req.uri().path() { + "/health" => + if req.method() == http::Method::GET { + InterceptRequest::Health + } else { + InterceptRequest::Deny + }, + "/health/readiness" => + if req.method() == http::Method::GET { + InterceptRequest::Readiness + } else { + InterceptRequest::Deny + }, + // Forward all other requests to the RPC server. + _ => InterceptRequest::No, + } + } +} diff --git a/substrate/client/rpc-servers/src/utils.rs b/substrate/client/rpc-servers/src/utils.rs index d99b8e637d9df3f1322ee8083342f449f958a311..d9d943c7c1fb31fe09ed532cd219a537ebf01b52 100644 --- a/substrate/client/rpc-servers/src/utils.rs +++ b/substrate/client/rpc-servers/src/utils.rs @@ -25,10 +25,7 @@ use std::{ }; use forwarded_header_value::ForwardedHeaderValue; -use hyper::{ - header::{HeaderName, HeaderValue}, - Request, -}; +use http::header::{HeaderName, HeaderValue}; use jsonrpsee::{server::middleware::http::HostFilterLayer, RpcModule}; use tower_http::cors::{AllowOrigin, CorsLayer}; @@ -57,7 +54,7 @@ pub(crate) fn build_rpc_api(mut rpc_api: RpcModule) available_methods.sort(); rpc_api - .register_method("rpc_methods", move |_, _| { + .register_method("rpc_methods", move |_, _, _| { serde_json::json!({ "methods": available_methods, }) @@ -96,7 +93,7 @@ pub(crate) fn format_cors(maybe_cors: Option<&Vec>) -> String { /// 1. `Forwarded` header. /// 2. `X-Forwarded-For` header. /// 3. `X-Real-Ip`. -pub(crate) fn get_proxy_ip(req: &Request) -> Option { +pub(crate) fn get_proxy_ip(req: &http::Request) -> Option { if let Some(ip) = req .headers() .get(&FORWARDED) @@ -133,9 +130,10 @@ pub(crate) fn get_proxy_ip(req: &Request) -> Option { mod tests { use super::*; use hyper::header::HeaderValue; + use jsonrpsee::server::{HttpBody, HttpRequest}; - fn request() -> hyper::Request { - hyper::Request::builder().body(hyper::Body::empty()).unwrap() + fn request() -> http::Request { + HttpRequest::builder().body(HttpBody::empty()).unwrap() } #[test] diff --git a/substrate/client/rpc-spec-v2/Cargo.toml b/substrate/client/rpc-spec-v2/Cargo.toml index 8977c842d03806c50372fc58452d5c35206ae163..0fcf5fd34e82c674feaccefb99d95a077fc9dcbd 100644 --- a/substrate/client/rpc-spec-v2/Cargo.toml +++ b/substrate/client/rpc-spec-v2/Cargo.toml @@ -16,46 +16,46 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -jsonrpsee = { version = "0.22.5", features = ["client-core", "macros", "server-core"] } +jsonrpsee = { features = ["client-core", "macros", "server-core"], workspace = true } # Internal chain structures for "chain_spec". -sc-chain-spec = { path = "../chain-spec" } +sc-chain-spec = { workspace = true, default-features = true } # Pool for submitting extrinsics required by "transaction" -sc-transaction-pool-api = { path = "../transaction-pool/api" } -sp-core = { path = "../../primitives/core" } -sp-runtime = { path = "../../primitives/runtime" } -sp-api = { path = "../../primitives/api" } -sp-rpc = { path = "../../primitives/rpc" } -sp-blockchain = { path = "../../primitives/blockchain" } -sp-version = { path = "../../primitives/version" } -sc-client-api = { path = "../api" } -sc-utils = { path = "../utils" } -sc-rpc = { path = "../rpc" } -codec = { package = "parity-scale-codec", version = "3.6.12" } +sc-transaction-pool-api = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-rpc = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-version = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-utils = { workspace = true, default-features = true } +sc-rpc = { workspace = true, default-features = true } +codec = { workspace = true, default-features = true } thiserror = { workspace = true } serde = { workspace = true, default-features = true } -hex = "0.4" -futures = "0.3.30" -parking_lot = "0.12.1" -tokio-stream = { version = "0.1.14", features = ["sync"] } -tokio = { version = "1.22.0", features = ["sync"] } -array-bytes = "6.2.2" +hex = { workspace = true, default-features = true } +futures = { workspace = true } +parking_lot = { workspace = true, default-features = true } +tokio-stream = { features = ["sync"], workspace = true } +tokio = { features = ["sync"], workspace = true, default-features = true } +array-bytes = { workspace = true, default-features = true } log = { workspace = true, default-features = true } -futures-util = { version = "0.3.30", default-features = false } -rand = "0.8.5" -schnellru = "0.2.1" +futures-util = { workspace = true } +rand = { workspace = true, default-features = true } +schnellru = { workspace = true } [dev-dependencies] -jsonrpsee = { version = "0.22", features = ["server", "ws-client"] } +jsonrpsee = { features = ["server", "ws-client"], workspace = true } serde_json = { workspace = true, default-features = true } -tokio = { version = "1.22.0", features = ["macros"] } -substrate-test-runtime-client = { path = "../../test-utils/runtime/client" } -substrate-test-runtime = { path = "../../test-utils/runtime" } -substrate-test-runtime-transaction-pool = { path = "../../test-utils/runtime/transaction-pool" } -sp-consensus = { path = "../../primitives/consensus/common" } -sp-externalities = { path = "../../primitives/externalities" } -sp-maybe-compressed-blob = { path = "../../primitives/maybe-compressed-blob" } -sc-block-builder = { path = "../block-builder" } -sc-service = { path = "../service", features = ["test-helpers"] } -assert_matches = "1.3.0" -pretty_assertions = "1.2.1" -sc-transaction-pool = { path = "../transaction-pool" } +tokio = { features = ["macros"], workspace = true, default-features = true } +substrate-test-runtime-client = { workspace = true } +substrate-test-runtime = { workspace = true } +substrate-test-runtime-transaction-pool = { workspace = true } +sp-consensus = { workspace = true, default-features = true } +sp-externalities = { workspace = true, default-features = true } +sp-maybe-compressed-blob = { workspace = true, default-features = true } +sc-block-builder = { workspace = true, default-features = true } +sc-service = { features = ["test-helpers"], workspace = true, default-features = true } +assert_matches = { workspace = true } +pretty_assertions = { workspace = true } +sc-transaction-pool = { workspace = true, default-features = true } diff --git a/substrate/client/rpc-spec-v2/src/chain_head/api.rs b/substrate/client/rpc-spec-v2/src/chain_head/api.rs index 23cb0bbf54585383e797a452d9747cac36649ad1..128d803521f6bd9eb2d077d54b604b3269874e14 100644 --- a/substrate/client/rpc-spec-v2/src/chain_head/api.rs +++ b/substrate/client/rpc-spec-v2/src/chain_head/api.rs @@ -54,7 +54,7 @@ pub trait ChainHeadApi { /// # Unstable /// /// This method is unstable and subject to change in the future. - #[method(name = "chainHead_v1_body", raw_method)] + #[method(name = "chainHead_v1_body", with_extensions)] async fn chain_head_unstable_body( &self, follow_subscription: String, @@ -73,7 +73,7 @@ pub trait ChainHeadApi { /// # Unstable /// /// This method is unstable and subject to change in the future. - #[method(name = "chainHead_v1_header", raw_method)] + #[method(name = "chainHead_v1_header", with_extensions)] async fn chain_head_unstable_header( &self, follow_subscription: String, @@ -85,7 +85,7 @@ pub trait ChainHeadApi { /// # Unstable /// /// This method is unstable and subject to change in the future. - #[method(name = "chainHead_v1_storage", raw_method)] + #[method(name = "chainHead_v1_storage", with_extensions)] async fn chain_head_unstable_storage( &self, follow_subscription: String, @@ -99,7 +99,7 @@ pub trait ChainHeadApi { /// # Unstable /// /// This method is unstable and subject to change in the future. - #[method(name = "chainHead_v1_call", raw_method)] + #[method(name = "chainHead_v1_call", with_extensions)] async fn chain_head_unstable_call( &self, follow_subscription: String, @@ -118,7 +118,7 @@ pub trait ChainHeadApi { /// # Unstable /// /// This method is unstable and subject to change in the future. - #[method(name = "chainHead_v1_unpin", raw_method)] + #[method(name = "chainHead_v1_unpin", with_extensions)] async fn chain_head_unstable_unpin( &self, follow_subscription: String, @@ -131,7 +131,7 @@ pub trait ChainHeadApi { /// # Unstable /// /// This method is unstable and subject to change in the future. - #[method(name = "chainHead_v1_continue", raw_method)] + #[method(name = "chainHead_v1_continue", with_extensions)] async fn chain_head_unstable_continue( &self, follow_subscription: String, @@ -145,7 +145,7 @@ pub trait ChainHeadApi { /// # Unstable /// /// This method is unstable and subject to change in the future. - #[method(name = "chainHead_v1_stopOperation", raw_method)] + #[method(name = "chainHead_v1_stopOperation", with_extensions)] async fn chain_head_unstable_stop_operation( &self, follow_subscription: String, diff --git a/substrate/client/rpc-spec-v2/src/chain_head/chain_head.rs b/substrate/client/rpc-spec-v2/src/chain_head/chain_head.rs index 6779180a414661eac923afca9a3917b340bc5487..a056b4d437c8dffa491225af40677d12217f9a75 100644 --- a/substrate/client/rpc-spec-v2/src/chain_head/chain_head.rs +++ b/substrate/client/rpc-spec-v2/src/chain_head/chain_head.rs @@ -36,7 +36,7 @@ use crate::{ use codec::Encode; use futures::{channel::oneshot, future::FutureExt}; use jsonrpsee::{ - core::async_trait, server::ResponsePayload, types::SubscriptionId, ConnectionDetails, + core::async_trait, server::ResponsePayload, types::SubscriptionId, ConnectionId, Extensions, MethodResponseFuture, PendingSubscriptionSink, SubscriptionSink, }; use log::debug; @@ -251,14 +251,16 @@ where async fn chain_head_unstable_body( &self, - connection_details: ConnectionDetails, + ext: &Extensions, follow_subscription: String, hash: Block::Hash, ) -> ResponsePayload<'static, MethodResponse> { - if !self - .subscriptions - .contains_subscription(connection_details.id(), &follow_subscription) - { + let conn_id = ext + .get::() + .copied() + .expect("ConnectionId is always set by jsonrpsee; qed"); + + if !self.subscriptions.contains_subscription(conn_id, &follow_subscription) { // The spec says to return `LimitReached` if the follow subscription is invalid or // stale. return ResponsePayload::success(MethodResponse::LimitReached); @@ -335,14 +337,16 @@ where async fn chain_head_unstable_header( &self, - connection_details: ConnectionDetails, + ext: &Extensions, follow_subscription: String, hash: Block::Hash, ) -> Result, ChainHeadRpcError> { - if !self - .subscriptions - .contains_subscription(connection_details.id(), &follow_subscription) - { + let conn_id = ext + .get::() + .copied() + .expect("ConnectionId is always set by jsonrpsee; qed"); + + if !self.subscriptions.contains_subscription(conn_id, &follow_subscription) { return Ok(None); } @@ -371,16 +375,18 @@ where async fn chain_head_unstable_storage( &self, - connection_details: ConnectionDetails, + ext: &Extensions, follow_subscription: String, hash: Block::Hash, items: Vec>, child_trie: Option, ) -> ResponsePayload<'static, MethodResponse> { - if !self - .subscriptions - .contains_subscription(connection_details.id(), &follow_subscription) - { + let conn_id = ext + .get::() + .copied() + .expect("ConnectionId is always set by jsonrpsee; qed"); + + if !self.subscriptions.contains_subscription(conn_id, &follow_subscription) { // The spec says to return `LimitReached` if the follow subscription is invalid or // stale. return ResponsePayload::success(MethodResponse::LimitReached); @@ -452,7 +458,7 @@ where async fn chain_head_unstable_call( &self, - connection_details: ConnectionDetails, + ext: &Extensions, follow_subscription: String, hash: Block::Hash, function: String, @@ -463,10 +469,12 @@ where Err(err) => return ResponsePayload::error(err), }; - if !self - .subscriptions - .contains_subscription(connection_details.id(), &follow_subscription) - { + let conn_id = ext + .get::() + .copied() + .expect("ConnectionId is always set by jsonrpsee; qed"); + + if !self.subscriptions.contains_subscription(conn_id, &follow_subscription) { // The spec says to return `LimitReached` if the follow subscription is invalid or // stale. return ResponsePayload::success(MethodResponse::LimitReached); @@ -530,14 +538,16 @@ where async fn chain_head_unstable_unpin( &self, - connection_details: ConnectionDetails, + ext: &Extensions, follow_subscription: String, hash_or_hashes: ListOrValue, ) -> Result<(), ChainHeadRpcError> { - if !self - .subscriptions - .contains_subscription(connection_details.id(), &follow_subscription) - { + let conn_id = ext + .get::() + .copied() + .expect("ConnectionId is always set by jsonrpsee; qed"); + + if !self.subscriptions.contains_subscription(conn_id, &follow_subscription) { return Ok(()); } @@ -566,14 +576,16 @@ where async fn chain_head_unstable_continue( &self, - connection_details: ConnectionDetails, + ext: &Extensions, follow_subscription: String, operation_id: String, ) -> Result<(), ChainHeadRpcError> { - if !self - .subscriptions - .contains_subscription(connection_details.id(), &follow_subscription) - { + let conn_id = ext + .get::() + .copied() + .expect("ConnectionId is always set by jsonrpsee; qed"); + + if !self.subscriptions.contains_subscription(conn_id, &follow_subscription) { return Ok(()) } @@ -592,14 +604,16 @@ where async fn chain_head_unstable_stop_operation( &self, - connection_details: ConnectionDetails, + ext: &Extensions, follow_subscription: String, operation_id: String, ) -> Result<(), ChainHeadRpcError> { - if !self - .subscriptions - .contains_subscription(connection_details.id(), &follow_subscription) - { + let conn_id = ext + .get::() + .copied() + .expect("ConnectionId is always set by jsonrpsee; qed"); + + if !self.subscriptions.contains_subscription(conn_id, &follow_subscription) { return Ok(()) } diff --git a/substrate/client/rpc-spec-v2/src/chain_head/chain_head_follow.rs b/substrate/client/rpc-spec-v2/src/chain_head/chain_head_follow.rs index a753896b24c238f949a8f4698ea7b4c63e39746f..6dc3df76bdd79ea6ea5c7c0f8765aa8d0c8e9638 100644 --- a/substrate/client/rpc-spec-v2/src/chain_head/chain_head_follow.rs +++ b/substrate/client/rpc-spec-v2/src/chain_head/chain_head_follow.rs @@ -32,7 +32,7 @@ use futures::{ }; use futures_util::future::Either; use jsonrpsee::SubscriptionSink; -use log::{debug, error}; +use log::debug; use sc_client_api::{ Backend, BlockBackend, BlockImportNotification, BlockchainEvents, FinalityNotification, }; @@ -572,7 +572,7 @@ where // The information from `.info()` is updated from the DB as the last // step of the finalization and it should be up to date. // If the info is outdated, there is nothing the RPC can do for now. - error!( + debug!( target: LOG_TARGET, "[follow][id={:?}] Client does not contain different best block", self.sub_id, diff --git a/substrate/client/rpc-spec-v2/src/chain_head/subscription/inner.rs b/substrate/client/rpc-spec-v2/src/chain_head/subscription/inner.rs index a6edc344bc63fda4cb04caa21dfd20b2df8bd0ad..d4d616f54dc88c9909cb8bfadc720da01afd2030 100644 --- a/substrate/client/rpc-spec-v2/src/chain_head/subscription/inner.rs +++ b/substrate/client/rpc-spec-v2/src/chain_head/subscription/inner.rs @@ -846,6 +846,7 @@ impl> SubscriptionsInner { #[cfg(test)] mod tests { use super::*; + use jsonrpsee::ConnectionId; use sc_block_builder::BlockBuilderBuilder; use sc_service::client::new_in_mem; use sp_consensus::BlockOrigin; @@ -1420,17 +1421,20 @@ mod tests { rpc_connections.clone(), ); - let reserved_sub_first = subscription_management.reserve_subscription(1).unwrap(); - let mut reserved_sub_second = subscription_management.reserve_subscription(1).unwrap(); + let reserved_sub_first = + subscription_management.reserve_subscription(ConnectionId(1)).unwrap(); + let mut reserved_sub_second = + subscription_management.reserve_subscription(ConnectionId(1)).unwrap(); // Subscriptions reserved but not yet populated. assert_eq!(subs.read().subs.len(), 0); // Cannot reserve anymore. - assert!(subscription_management.reserve_subscription(1).is_none()); + assert!(subscription_management.reserve_subscription(ConnectionId(1)).is_none()); // Drop the first subscription. drop(reserved_sub_first); // Space is freed-up for the rpc connections. - let mut reserved_sub_first = subscription_management.reserve_subscription(1).unwrap(); + let mut reserved_sub_first = + subscription_management.reserve_subscription(ConnectionId(1)).unwrap(); // Insert subscriptions. let _sub_data_first = @@ -1445,7 +1449,8 @@ mod tests { // Check that the subscription is removed. assert_eq!(subs.read().subs.len(), 1); // Space is freed-up for the rpc connections. - let reserved_sub_first = subscription_management.reserve_subscription(1).unwrap(); + let reserved_sub_first = + subscription_management.reserve_subscription(ConnectionId(1)).unwrap(); // Drop all subscriptions. drop(reserved_sub_first); diff --git a/substrate/client/rpc-spec-v2/src/common/connections.rs b/substrate/client/rpc-spec-v2/src/common/connections.rs index c16a80bf49db93853ca223ab632dbc544082ae44..f0c31d612ebdb1a55b6bf97f8cda7f8fdccffd87 100644 --- a/substrate/client/rpc-spec-v2/src/common/connections.rs +++ b/substrate/client/rpc-spec-v2/src/common/connections.rs @@ -195,68 +195,71 @@ mod tests { #[test] fn reserve_space() { let rpc_connections = RpcConnections::new(2); - let reserved = rpc_connections.reserve_space(1); + let conn_id = ConnectionId(1); + let reserved = rpc_connections.reserve_space(conn_id); + assert!(reserved.is_some()); - assert_eq!(1, rpc_connections.data.lock().get(&1).unwrap().num_identifiers); + assert_eq!(1, rpc_connections.data.lock().get(&conn_id).unwrap().num_identifiers); assert_eq!(rpc_connections.data.lock().len(), 1); let reserved = reserved.unwrap(); let registered = reserved.register("identifier1".to_string()).unwrap(); - assert!(rpc_connections.contains_identifier(1, "identifier1")); - assert_eq!(1, rpc_connections.data.lock().get(&1).unwrap().num_identifiers); + assert!(rpc_connections.contains_identifier(conn_id, "identifier1")); + assert_eq!(1, rpc_connections.data.lock().get(&conn_id).unwrap().num_identifiers); drop(registered); // Data is dropped. - assert!(rpc_connections.data.lock().get(&1).is_none()); + assert!(rpc_connections.data.lock().get(&conn_id).is_none()); assert!(rpc_connections.data.lock().is_empty()); // Checks can still happen. - assert!(!rpc_connections.contains_identifier(1, "identifier1")); + assert!(!rpc_connections.contains_identifier(conn_id, "identifier1")); } #[test] fn reserve_space_capacity_reached() { let rpc_connections = RpcConnections::new(2); + let conn_id = ConnectionId(1); // Reserve identifier for connection 1. - let reserved = rpc_connections.reserve_space(1); + let reserved = rpc_connections.reserve_space(conn_id); assert!(reserved.is_some()); - assert_eq!(1, rpc_connections.data.lock().get(&1).unwrap().num_identifiers); + assert_eq!(1, rpc_connections.data.lock().get(&conn_id).unwrap().num_identifiers); // Add identifier for connection 1. let reserved = reserved.unwrap(); let registered = reserved.register("identifier1".to_string()).unwrap(); - assert!(rpc_connections.contains_identifier(1, "identifier1")); - assert_eq!(1, rpc_connections.data.lock().get(&1).unwrap().num_identifiers); + assert!(rpc_connections.contains_identifier(conn_id, "identifier1")); + assert_eq!(1, rpc_connections.data.lock().get(&conn_id).unwrap().num_identifiers); // Reserve identifier for connection 1 again. - let reserved = rpc_connections.reserve_space(1); + let reserved = rpc_connections.reserve_space(conn_id); assert!(reserved.is_some()); - assert_eq!(2, rpc_connections.data.lock().get(&1).unwrap().num_identifiers); + assert_eq!(2, rpc_connections.data.lock().get(&conn_id).unwrap().num_identifiers); // Add identifier for connection 1 again. let reserved = reserved.unwrap(); let registered_second = reserved.register("identifier2".to_string()).unwrap(); - assert!(rpc_connections.contains_identifier(1, "identifier2")); - assert_eq!(2, rpc_connections.data.lock().get(&1).unwrap().num_identifiers); + assert!(rpc_connections.contains_identifier(conn_id, "identifier2")); + assert_eq!(2, rpc_connections.data.lock().get(&conn_id).unwrap().num_identifiers); // Cannot reserve more identifiers. - let reserved = rpc_connections.reserve_space(1); + let reserved = rpc_connections.reserve_space(conn_id); assert!(reserved.is_none()); // Drop the first identifier. drop(registered); - assert_eq!(1, rpc_connections.data.lock().get(&1).unwrap().num_identifiers); - assert!(rpc_connections.contains_identifier(1, "identifier2")); - assert!(!rpc_connections.contains_identifier(1, "identifier1")); + assert_eq!(1, rpc_connections.data.lock().get(&conn_id).unwrap().num_identifiers); + assert!(rpc_connections.contains_identifier(conn_id, "identifier2")); + assert!(!rpc_connections.contains_identifier(conn_id, "identifier1")); // Can reserve again after clearing the space. - let reserved = rpc_connections.reserve_space(1); + let reserved = rpc_connections.reserve_space(conn_id); assert!(reserved.is_some()); - assert_eq!(2, rpc_connections.data.lock().get(&1).unwrap().num_identifiers); + assert_eq!(2, rpc_connections.data.lock().get(&conn_id).unwrap().num_identifiers); // Ensure data is cleared. drop(reserved); drop(registered_second); - assert!(rpc_connections.data.lock().get(&1).is_none()); + assert!(rpc_connections.data.lock().get(&conn_id).is_none()); } } diff --git a/substrate/client/rpc-spec-v2/src/transaction/api.rs b/substrate/client/rpc-spec-v2/src/transaction/api.rs index ed358922d53ed0d087a2693b55a9b4f51635c1c0..6af6f1678440afe6bf01805971903cdf5ffe8e45 100644 --- a/substrate/client/rpc-spec-v2/src/transaction/api.rs +++ b/substrate/client/rpc-spec-v2/src/transaction/api.rs @@ -48,7 +48,7 @@ pub trait TransactionBroadcastApi { /// /// This method is unstable and subject to change in the future. - #[method(name = "transaction_v1_broadcast", raw_method)] + #[method(name = "transaction_v1_broadcast", with_extensions)] async fn broadcast(&self, bytes: Bytes) -> RpcResult>; /// Broadcast an extrinsic to the chain. @@ -56,6 +56,6 @@ pub trait TransactionBroadcastApi { /// # Unstable /// /// This method is unstable and subject to change in the future. - #[method(name = "transaction_v1_stop", raw_method)] + #[method(name = "transaction_v1_stop", with_extensions)] async fn stop_broadcast(&self, operation_id: String) -> Result<(), ErrorBroadcast>; } diff --git a/substrate/client/rpc-spec-v2/src/transaction/transaction_broadcast.rs b/substrate/client/rpc-spec-v2/src/transaction/transaction_broadcast.rs index 68c19010e31c5653509c380f6be69c072e6fe9bb..2fd4ce2454565dfaa4f25c607b1fed83650a7f45 100644 --- a/substrate/client/rpc-spec-v2/src/transaction/transaction_broadcast.rs +++ b/substrate/client/rpc-spec-v2/src/transaction/transaction_broadcast.rs @@ -27,7 +27,7 @@ use futures::{FutureExt, Stream, StreamExt}; use futures_util::stream::AbortHandle; use jsonrpsee::{ core::{async_trait, RpcResult}, - ConnectionDetails, + ConnectionId, Extensions, }; use parking_lot::RwLock; use rand::{distributions::Alphanumeric, Rng}; @@ -121,19 +121,18 @@ where ::Hash: Unpin, Client: HeaderBackend + BlockchainEvents + Send + Sync + 'static, { - async fn broadcast( - &self, - connection_details: ConnectionDetails, - bytes: Bytes, - ) -> RpcResult> { + async fn broadcast(&self, ext: &Extensions, bytes: Bytes) -> RpcResult> { let pool = self.pool.clone(); + let conn_id = ext + .get::() + .copied() + .expect("ConnectionId is always set by jsonrpsee; qed"); // The unique ID of this operation. let id = self.generate_unique_id(); // Ensure that the connection has not reached the maximum number of active operations. - let Some(reserved_connection) = self.rpc_connections.reserve_space(connection_details.id()) - else { + let Some(reserved_connection) = self.rpc_connections.reserve_space(conn_id) else { return Ok(None) }; let Some(reserved_identifier) = reserved_connection.register(id.clone()) else { @@ -245,11 +244,16 @@ where async fn stop_broadcast( &self, - connection_details: ConnectionDetails, + ext: &Extensions, operation_id: String, ) -> Result<(), ErrorBroadcast> { + let conn_id = ext + .get::() + .copied() + .expect("ConnectionId is always set by jsonrpsee; qed"); + // The operation ID must correlate to the same connection ID. - if !self.rpc_connections.contains_identifier(connection_details.id(), &operation_id) { + if !self.rpc_connections.contains_identifier(conn_id, &operation_id) { return Err(ErrorBroadcast::InvalidOperationID) } diff --git a/substrate/client/rpc/Cargo.toml b/substrate/client/rpc/Cargo.toml index 7dd46b2ab4c31e7be4168e588a8c95e900cb213a..545d02bb3043868addece16ad24549aa9c1f8a1d 100644 --- a/substrate/client/rpc/Cargo.toml +++ b/substrate/client/rpc/Cargo.toml @@ -16,46 +16,46 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12" } -futures = "0.3.30" -jsonrpsee = { version = "0.22", features = ["server"] } +codec = { workspace = true, default-features = true } +futures = { workspace = true } +jsonrpsee = { features = ["server"], workspace = true } log = { workspace = true, default-features = true } -parking_lot = "0.12.1" +parking_lot = { workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } -sc-block-builder = { path = "../block-builder" } -sc-chain-spec = { path = "../chain-spec" } -sc-client-api = { path = "../api" } -sc-mixnet = { path = "../mixnet" } -sc-rpc-api = { path = "../rpc-api" } -sc-tracing = { path = "../tracing" } -sc-transaction-pool-api = { path = "../transaction-pool/api" } -sc-utils = { path = "../utils" } -sp-api = { path = "../../primitives/api" } -sp-blockchain = { path = "../../primitives/blockchain" } -sp-core = { path = "../../primitives/core" } -sp-keystore = { path = "../../primitives/keystore" } -sp-offchain = { path = "../../primitives/offchain" } -sp-rpc = { path = "../../primitives/rpc" } -sp-runtime = { path = "../../primitives/runtime" } -sp-session = { path = "../../primitives/session" } -sp-version = { path = "../../primitives/version" } -sp-statement-store = { path = "../../primitives/statement-store" } -tokio = "1.37" +sc-block-builder = { workspace = true, default-features = true } +sc-chain-spec = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-mixnet = { workspace = true, default-features = true } +sc-rpc-api = { workspace = true, default-features = true } +sc-tracing = { workspace = true, default-features = true } +sc-transaction-pool-api = { workspace = true, default-features = true } +sc-utils = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-offchain = { workspace = true, default-features = true } +sp-rpc = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-session = { workspace = true, default-features = true } +sp-version = { workspace = true, default-features = true } +sp-statement-store = { workspace = true, default-features = true } +tokio = { workspace = true, default-features = true } [dev-dependencies] -env_logger = "0.11" -assert_matches = "1.3.0" -sc-block-builder = { path = "../block-builder" } -sc-network = { path = "../network" } -sc-network-common = { path = "../network/common" } -sc-transaction-pool = { path = "../transaction-pool" } -sp-consensus = { path = "../../primitives/consensus/common" } -sp-crypto-hashing = { path = "../../primitives/crypto/hashing" } -tokio = "1.37" -sp-io = { path = "../../primitives/io" } -substrate-test-runtime-client = { path = "../../test-utils/runtime/client" } -pretty_assertions = "1.2.1" -tracing-subscriber = { version = "0.3", features = ["env-filter"] } +env_logger = { workspace = true } +assert_matches = { workspace = true } +sc-block-builder = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sc-network-common = { workspace = true, default-features = true } +sc-transaction-pool = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-crypto-hashing = { workspace = true, default-features = true } +tokio = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +substrate-test-runtime-client = { workspace = true } +pretty_assertions = { workspace = true } +tracing-subscriber = { features = ["env-filter"], workspace = true } [features] test-helpers = [] diff --git a/substrate/client/rpc/src/utils.rs b/substrate/client/rpc/src/utils.rs index 3b5372615e733dba860faa453063548189fc6354..bc566ed37f2301c4a077f4918a2d4e521153a83f 100644 --- a/substrate/client/rpc/src/utils.rs +++ b/substrate/client/rpc/src/utils.rs @@ -130,7 +130,7 @@ async fn inner_pipe_from_stream( "Subscription buffer limit={} exceeded for subscription={} conn_id={}; dropping subscription", buf.max_cap, sink.method_name(), - sink.connection_id() + sink.connection_id().0 ); return } @@ -189,7 +189,7 @@ mod tests { async fn subscribe() -> Subscription { let mut module = RpcModule::new(()); module - .register_subscription("sub", "my_sub", "unsub", |_, pending, _| async move { + .register_subscription("sub", "my_sub", "unsub", |_, pending, _, _| async move { let stream = futures::stream::iter([0; 16]); pipe_from_stream(pending, stream).await; Ok(()) @@ -217,7 +217,7 @@ mod tests { let mut module = RpcModule::new(tx); module - .register_subscription("sub", "my_sub", "unsub", |_, pending, ctx| async move { + .register_subscription("sub", "my_sub", "unsub", |_, pending, ctx, _| async move { let stream = futures::stream::iter([0; 32]); pipe_from_stream(pending, stream).await; _ = ctx.unbounded_send(()); @@ -239,16 +239,21 @@ mod tests { let mut module = RpcModule::new(notify_tx); module - .register_subscription("sub", "my_sub", "unsub", |_, pending, notify_tx| async move { - // emulate empty stream for simplicity: otherwise we need some mechanism - // to sync buffer and channel send operations - let stream = futures::stream::empty::<()>(); - // this should exit immediately - pipe_from_stream(pending, stream).await; - // notify that the `pipe_from_stream` has returned - notify_tx.notify_one(); - Ok(()) - }) + .register_subscription( + "sub", + "my_sub", + "unsub", + |_, pending, notify_tx, _| async move { + // emulate empty stream for simplicity: otherwise we need some mechanism + // to sync buffer and channel send operations + let stream = futures::stream::empty::<()>(); + // this should exit immediately + pipe_from_stream(pending, stream).await; + // notify that the `pipe_from_stream` has returned + notify_tx.notify_one(); + Ok(()) + }, + ) .unwrap(); module.subscribe("sub", EmptyServerParams::new(), 1).await.unwrap(); diff --git a/substrate/client/service/Cargo.toml b/substrate/client/service/Cargo.toml index dfdd485f15c00550119d9aebf8594b33cdba4df1..724e2ddfe56a539c0263e4bcf555777d1e81802e 100644 --- a/substrate/client/service/Cargo.toml +++ b/substrate/client/service/Cargo.toml @@ -28,64 +28,64 @@ runtime-benchmarks = [ ] [dependencies] -jsonrpsee = { version = "0.22", features = ["server"] } +jsonrpsee = { features = ["server"], workspace = true } thiserror = { workspace = true } -futures = "0.3.30" -rand = "0.8.5" -parking_lot = "0.12.1" +futures = { workspace = true } +rand = { workspace = true, default-features = true } +parking_lot = { workspace = true, default-features = true } log = { workspace = true, default-features = true } -futures-timer = "3.0.1" -exit-future = "0.2.0" -pin-project = "1.0.12" +futures-timer = { workspace = true } +exit-future = { workspace = true } +pin-project = { workspace = true } serde = { workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } -sc-keystore = { path = "../keystore" } -sp-runtime = { path = "../../primitives/runtime" } -sp-trie = { path = "../../primitives/trie" } -sp-externalities = { path = "../../primitives/externalities" } -sc-utils = { path = "../utils" } -sp-version = { path = "../../primitives/version" } -sp-blockchain = { path = "../../primitives/blockchain" } -sp-core = { path = "../../primitives/core" } -sp-keystore = { path = "../../primitives/keystore" } -sp-session = { path = "../../primitives/session" } -sp-state-machine = { path = "../../primitives/state-machine" } -sp-consensus = { path = "../../primitives/consensus/common" } -sc-consensus = { path = "../consensus/common" } -sp-storage = { path = "../../primitives/storage" } -sc-network = { path = "../network" } -sc-network-common = { path = "../network/common" } -sc-network-light = { path = "../network/light" } -sc-network-sync = { path = "../network/sync" } -sc-network-types = { path = "../network/types" } -sc-network-transactions = { path = "../network/transactions" } -sc-chain-spec = { path = "../chain-spec" } -sc-client-api = { path = "../api" } -sp-api = { path = "../../primitives/api" } -sc-client-db = { path = "../db", default-features = false } -codec = { package = "parity-scale-codec", version = "3.6.12" } -sc-executor = { path = "../executor" } -sc-transaction-pool = { path = "../transaction-pool" } -sp-transaction-pool = { path = "../../primitives/transaction-pool" } -sc-transaction-pool-api = { path = "../transaction-pool/api" } -sp-transaction-storage-proof = { path = "../../primitives/transaction-storage-proof" } -sc-rpc-server = { path = "../rpc-servers" } -sc-rpc = { path = "../rpc" } -sc-rpc-spec-v2 = { path = "../rpc-spec-v2" } -sc-informant = { path = "../informant" } -sc-telemetry = { path = "../telemetry" } -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../utils/prometheus" } -sc-tracing = { path = "../tracing" } -sc-sysinfo = { path = "../sysinfo" } -tracing = "0.1.29" -tracing-futures = { version = "0.2.4" } -async-trait = "0.1.79" -tokio = { version = "1.22.0", features = ["parking_lot", "rt-multi-thread", "time"] } -tempfile = "3.1.0" -directories = "5.0.1" -static_init = "1.0.3" -schnellru = "0.2.1" +sc-keystore = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-trie = { workspace = true, default-features = true } +sp-externalities = { workspace = true, default-features = true } +sc-utils = { workspace = true, default-features = true } +sp-version = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-session = { workspace = true, default-features = true } +sp-state-machine = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } +sp-storage = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sc-network-common = { workspace = true, default-features = true } +sc-network-light = { workspace = true, default-features = true } +sc-network-sync = { workspace = true, default-features = true } +sc-network-types = { workspace = true, default-features = true } +sc-network-transactions = { workspace = true, default-features = true } +sc-chain-spec = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sc-client-db = { workspace = true } +codec = { workspace = true, default-features = true } +sc-executor = { workspace = true, default-features = true } +sc-transaction-pool = { workspace = true, default-features = true } +sp-transaction-pool = { workspace = true, default-features = true } +sc-transaction-pool-api = { workspace = true, default-features = true } +sp-transaction-storage-proof = { workspace = true, default-features = true } +sc-rpc-server = { workspace = true, default-features = true } +sc-rpc = { workspace = true, default-features = true } +sc-rpc-spec-v2 = { workspace = true, default-features = true } +sc-informant = { workspace = true, default-features = true } +sc-telemetry = { workspace = true, default-features = true } +prometheus-endpoint = { workspace = true, default-features = true } +sc-tracing = { workspace = true, default-features = true } +sc-sysinfo = { workspace = true, default-features = true } +tracing = { workspace = true, default-features = true } +tracing-futures = { workspace = true } +async-trait = { workspace = true } +tokio = { features = ["parking_lot", "rt-multi-thread", "time"], workspace = true, default-features = true } +tempfile = { workspace = true } +directories = { workspace = true } +static_init = { workspace = true } +schnellru = { workspace = true } [dev-dependencies] -substrate-test-runtime-client = { path = "../../test-utils/runtime/client" } -substrate-test-runtime = { path = "../../test-utils/runtime" } +substrate-test-runtime-client = { workspace = true } +substrate-test-runtime = { workspace = true } diff --git a/substrate/client/service/src/client/call_executor.rs b/substrate/client/service/src/client/call_executor.rs index 9da4d2192576909f95428933623a1e3160e1f9ad..1341aa0e72051f89bcd51d2feab3c24051fc124e 100644 --- a/substrate/client/service/src/client/call_executor.rs +++ b/substrate/client/service/src/client/call_executor.rs @@ -16,19 +16,19 @@ // You should have received a copy of the GNU General Public License // along with this program. If not, see . -use super::{client::ClientConfig, wasm_override::WasmOverride, wasm_substitutes::WasmSubstitutes}; +use super::{code_provider::CodeProvider, ClientConfig}; use sc_client_api::{ backend, call_executor::CallExecutor, execution_extensions::ExecutionExtensions, HeaderBackend, }; use sc_executor::{RuntimeVersion, RuntimeVersionOf}; use sp_api::ProofRecorder; -use sp_core::traits::{CallContext, CodeExecutor, RuntimeCode}; +use sp_core::traits::{CallContext, CodeExecutor}; use sp_externalities::Extensions; use sp_runtime::{ generic::BlockId, traits::{Block as BlockT, HashingFor}, }; -use sp_state_machine::{backend::AsTrieBackend, Ext, OverlayedChanges, StateMachine, StorageProof}; +use sp_state_machine::{backend::AsTrieBackend, OverlayedChanges, StateMachine, StorageProof}; use std::{cell::RefCell, sync::Arc}; /// Call executor that executes methods locally, querying all required @@ -36,8 +36,7 @@ use std::{cell::RefCell, sync::Arc}; pub struct LocalCallExecutor { backend: Arc, executor: E, - wasm_override: Arc>, - wasm_substitutes: WasmSubstitutes, + code_provider: CodeProvider, execution_extensions: Arc>, } @@ -53,81 +52,15 @@ where client_config: ClientConfig, execution_extensions: ExecutionExtensions, ) -> sp_blockchain::Result { - let wasm_override = client_config - .wasm_runtime_overrides - .as_ref() - .map(|p| WasmOverride::new(p.clone(), &executor)) - .transpose()?; - - let wasm_substitutes = WasmSubstitutes::new( - client_config.wasm_runtime_substitutes, - executor.clone(), - backend.clone(), - )?; + let code_provider = CodeProvider::new(&client_config, executor.clone(), backend.clone())?; Ok(LocalCallExecutor { backend, executor, - wasm_override: Arc::new(wasm_override), - wasm_substitutes, + code_provider, execution_extensions: Arc::new(execution_extensions), }) } - - /// Check if local runtime code overrides are enabled and one is available - /// for the given `BlockId`. If yes, return it; otherwise return the same - /// `RuntimeCode` instance that was passed. - fn check_override<'a>( - &'a self, - onchain_code: RuntimeCode<'a>, - state: &B::State, - hash: Block::Hash, - ) -> sp_blockchain::Result<(RuntimeCode<'a>, RuntimeVersion)> - where - Block: BlockT, - B: backend::Backend, - { - let on_chain_version = self.on_chain_runtime_version(&onchain_code, state)?; - let code_and_version = if let Some(d) = self.wasm_override.as_ref().as_ref().and_then(|o| { - o.get( - &on_chain_version.spec_version, - onchain_code.heap_pages, - &on_chain_version.spec_name, - ) - }) { - log::debug!(target: "wasm_overrides", "using WASM override for block {}", hash); - d - } else if let Some(s) = - self.wasm_substitutes - .get(on_chain_version.spec_version, onchain_code.heap_pages, hash) - { - log::debug!(target: "wasm_substitutes", "Using WASM substitute for block {:?}", hash); - s - } else { - log::debug!( - target: "wasm_overrides", - "Neither WASM override nor substitute available for block {hash}, using onchain code", - ); - (onchain_code, on_chain_version) - }; - - Ok(code_and_version) - } - - /// Returns the on chain runtime version. - fn on_chain_runtime_version( - &self, - code: &RuntimeCode, - state: &B::State, - ) -> sp_blockchain::Result { - let mut overlay = OverlayedChanges::default(); - - let mut ext = Ext::new(&mut overlay, state, None); - - self.executor - .runtime_version(&mut ext, code) - .map_err(|e| sp_blockchain::Error::VersionInvalid(e.to_string())) - } } impl Clone for LocalCallExecutor @@ -138,8 +71,7 @@ where LocalCallExecutor { backend: self.backend.clone(), executor: self.executor.clone(), - wasm_override: self.wasm_override.clone(), - wasm_substitutes: self.wasm_substitutes.clone(), + code_provider: self.code_provider.clone(), execution_extensions: self.execution_extensions.clone(), } } @@ -175,7 +107,7 @@ where let runtime_code = state_runtime_code.runtime_code().map_err(sp_blockchain::Error::RuntimeCode)?; - let runtime_code = self.check_override(runtime_code, &state, at_hash)?.0; + let runtime_code = self.code_provider.maybe_override_code(runtime_code, &state, at_hash)?.0; let mut extensions = self.execution_extensions.extensions(at_hash, at_number); @@ -215,7 +147,7 @@ where let runtime_code = state_runtime_code.runtime_code().map_err(sp_blockchain::Error::RuntimeCode)?; - let runtime_code = self.check_override(runtime_code, &state, at_hash)?.0; + let runtime_code = self.code_provider.maybe_override_code(runtime_code, &state, at_hash)?.0; let mut extensions = extensions.borrow_mut(); match recorder { @@ -263,7 +195,9 @@ where let runtime_code = state_runtime_code.runtime_code().map_err(sp_blockchain::Error::RuntimeCode)?; - self.check_override(runtime_code, &state, at_hash).map(|(_, v)| v) + self.code_provider + .maybe_override_code(runtime_code, &state, at_hash) + .map(|(_, v)| v) } fn prove_execution( @@ -281,7 +215,7 @@ where let state_runtime_code = sp_state_machine::backend::BackendRuntimeCode::new(trie_backend); let runtime_code = state_runtime_code.runtime_code().map_err(sp_blockchain::Error::RuntimeCode)?; - let runtime_code = self.check_override(runtime_code, &state, at_hash)?.0; + let runtime_code = self.code_provider.maybe_override_code(runtime_code, &state, at_hash)?.0; sp_state_machine::prove_execution_on_trie_backend( trie_backend, @@ -331,133 +265,3 @@ where self.executor.native_version() } } - -#[cfg(test)] -mod tests { - use super::*; - use backend::Backend; - use sc_client_api::in_mem; - use sc_executor::WasmExecutor; - use sp_core::{ - testing::TaskExecutor, - traits::{FetchRuntimeCode, WrappedRuntimeCode}, - }; - use std::collections::HashMap; - use substrate_test_runtime_client::{runtime, GenesisInit}; - - #[test] - fn should_get_override_if_exists() { - let executor = WasmExecutor::default(); - - let overrides = crate::client::wasm_override::dummy_overrides(); - let onchain_code = WrappedRuntimeCode(substrate_test_runtime::wasm_binary_unwrap().into()); - let onchain_code = RuntimeCode { - code_fetcher: &onchain_code, - heap_pages: Some(128), - hash: vec![0, 0, 0, 0], - }; - - let backend = Arc::new(in_mem::Backend::::new()); - - // wasm_runtime_overrides is `None` here because we construct the - // LocalCallExecutor directly later on - let client_config = ClientConfig::default(); - - let genesis_block_builder = crate::GenesisBlockBuilder::new( - &substrate_test_runtime_client::GenesisParameters::default().genesis_storage(), - !client_config.no_genesis, - backend.clone(), - executor.clone(), - ) - .expect("Creates genesis block builder"); - - // client is used for the convenience of creating and inserting the genesis block. - let _client = - crate::client::new_with_backend::<_, _, runtime::Block, _, runtime::RuntimeApi>( - backend.clone(), - executor.clone(), - genesis_block_builder, - Box::new(TaskExecutor::new()), - None, - None, - client_config, - ) - .expect("Creates a client"); - - let call_executor = LocalCallExecutor { - backend: backend.clone(), - executor: executor.clone(), - wasm_override: Arc::new(Some(overrides)), - wasm_substitutes: WasmSubstitutes::new( - Default::default(), - executor.clone(), - backend.clone(), - ) - .unwrap(), - execution_extensions: Arc::new(ExecutionExtensions::new( - None, - Arc::new(executor.clone()), - )), - }; - - let check = call_executor - .check_override( - onchain_code, - &backend.state_at(backend.blockchain().info().genesis_hash).unwrap(), - backend.blockchain().info().genesis_hash, - ) - .expect("RuntimeCode override") - .0; - - assert_eq!(Some(vec![2, 2, 2, 2, 2, 2, 2, 2]), check.fetch_runtime_code().map(Into::into)); - } - - #[test] - fn returns_runtime_version_from_substitute() { - const SUBSTITUTE_SPEC_NAME: &str = "substitute-spec-name-cool"; - - let executor = WasmExecutor::default(); - - let backend = Arc::new(in_mem::Backend::::new()); - - // Let's only override the `spec_name` for our testing purposes. - let substitute = sp_version::embed::embed_runtime_version( - &substrate_test_runtime::WASM_BINARY_BLOATY.unwrap(), - sp_version::RuntimeVersion { - spec_name: SUBSTITUTE_SPEC_NAME.into(), - ..substrate_test_runtime::VERSION - }, - ) - .unwrap(); - - let client_config = crate::client::ClientConfig { - wasm_runtime_substitutes: vec![(0, substitute)].into_iter().collect::>(), - ..Default::default() - }; - - let genesis_block_builder = crate::GenesisBlockBuilder::new( - &substrate_test_runtime_client::GenesisParameters::default().genesis_storage(), - !client_config.no_genesis, - backend.clone(), - executor.clone(), - ) - .expect("Creates genesis block builder"); - - // client is used for the convenience of creating and inserting the genesis block. - let client = - crate::client::new_with_backend::<_, _, runtime::Block, _, runtime::RuntimeApi>( - backend.clone(), - executor.clone(), - genesis_block_builder, - Box::new(TaskExecutor::new()), - None, - None, - client_config, - ) - .expect("Creates a client"); - - let version = client.runtime_version_at(client.chain_info().genesis_hash).unwrap(); - - assert_eq!(SUBSTITUTE_SPEC_NAME, &*version.spec_name); - } -} diff --git a/substrate/client/service/src/client/client.rs b/substrate/client/service/src/client/client.rs index 3c25c233775bea6ed8297d144bcadf823b918e7e..a2c9212f7b9c9ce80860aa9ca9f3b9e8b0a844d5 100644 --- a/substrate/client/service/src/client/client.rs +++ b/substrate/client/service/src/client/client.rs @@ -18,7 +18,10 @@ //! Substrate Client -use super::block_rules::{BlockRules, LookupResult as BlockLookupResult}; +use super::{ + block_rules::{BlockRules, LookupResult as BlockLookupResult}, + CodeProvider, +}; use crate::client::notification_pinning::NotificationPinningWorker; use log::{debug, info, trace, warn}; use parking_lot::{Mutex, RwLock}; @@ -57,10 +60,7 @@ use sp_consensus::{BlockOrigin, BlockStatus, Error as ConsensusError}; use sc_utils::mpsc::{tracing_unbounded, TracingUnboundedSender}; use sp_core::{ - storage::{ - well_known_keys, ChildInfo, ChildType, PrefixedStorageKey, StorageChild, StorageData, - StorageKey, - }, + storage::{ChildInfo, ChildType, PrefixedStorageKey, StorageChild, StorageData, StorageKey}, traits::{CallContext, SpawnNamed}, }; use sp_runtime::{ @@ -115,6 +115,7 @@ where config: ClientConfig, telemetry: Option, unpin_worker_sender: TracingUnboundedSender>, + code_provider: CodeProvider, _phantom: PhantomData, } @@ -410,6 +411,7 @@ where Block, BlockImportOperation = >::BlockImportOperation, >, + E: Clone, B: 'static, { let info = backend.blockchain().info(); @@ -438,6 +440,7 @@ where ); let unpin_worker = NotificationPinningWorker::new(rx, backend.clone()); spawn_handle.spawn("notification-pinning-worker", None, Box::pin(unpin_worker.run())); + let code_provider = CodeProvider::new(&config, executor.clone(), backend.clone())?; Ok(Client { backend, @@ -453,6 +456,7 @@ where config, telemetry, unpin_worker_sender, + code_provider, _phantom: Default::default(), }) } @@ -475,13 +479,10 @@ where } /// Get the code at a given block. + /// + /// This takes any potential substitutes into account, but ignores overrides. pub fn code_at(&self, hash: Block::Hash) -> sp_blockchain::Result> { - Ok(StorageProvider::storage(self, hash, &StorageKey(well_known_keys::CODE.to_vec()))? - .expect( - "None is returned if there's no value stored for the given key;\ - ':code' key is always defined; qed", - ) - .0) + self.code_provider.code_at_ignoring_overrides(hash) } /// Get the RuntimeVersion at a given block. @@ -1779,7 +1780,7 @@ where /// Check block preconditions. async fn check_block( - &mut self, + &self, block: BlockCheckParams, ) -> Result { let BlockCheckParams { @@ -1861,10 +1862,10 @@ where } async fn check_block( - &mut self, + &self, block: BlockCheckParams, ) -> Result { - (&*self).check_block(block).await + (&self).check_block(block).await } } diff --git a/substrate/client/service/src/client/code_provider.rs b/substrate/client/service/src/client/code_provider.rs new file mode 100644 index 0000000000000000000000000000000000000000..8ba7766ea65b5ba0a723aaa151d7121e2bbc4c53 --- /dev/null +++ b/substrate/client/service/src/client/code_provider.rs @@ -0,0 +1,348 @@ +// This file is part of Substrate. + +// 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 super::{client::ClientConfig, wasm_override::WasmOverride, wasm_substitutes::WasmSubstitutes}; +use sc_client_api::backend; +use sc_executor::{RuntimeVersion, RuntimeVersionOf}; +use sp_core::traits::{FetchRuntimeCode, RuntimeCode}; +use sp_runtime::traits::Block as BlockT; +use sp_state_machine::{Ext, OverlayedChanges}; +use std::sync::Arc; + +/// Provider for fetching `:code` of a block. +/// +/// As a node can run with code overrides or substitutes, this will ensure that these are taken into +/// account before returning the actual `code` for a block. +pub struct CodeProvider { + backend: Arc, + executor: Arc, + wasm_override: Arc>, + wasm_substitutes: WasmSubstitutes, +} + +impl Clone for CodeProvider { + fn clone(&self) -> Self { + Self { + backend: self.backend.clone(), + executor: self.executor.clone(), + wasm_override: self.wasm_override.clone(), + wasm_substitutes: self.wasm_substitutes.clone(), + } + } +} + +impl CodeProvider +where + Block: BlockT, + Backend: backend::Backend, + Executor: RuntimeVersionOf, +{ + /// Create a new instance. + pub fn new( + client_config: &ClientConfig, + executor: Executor, + backend: Arc, + ) -> sp_blockchain::Result { + let wasm_override = client_config + .wasm_runtime_overrides + .as_ref() + .map(|p| WasmOverride::new(p.clone(), &executor)) + .transpose()?; + + let executor = Arc::new(executor); + + let wasm_substitutes = WasmSubstitutes::new( + client_config.wasm_runtime_substitutes.clone(), + executor.clone(), + backend.clone(), + )?; + + Ok(Self { backend, executor, wasm_override: Arc::new(wasm_override), wasm_substitutes }) + } + + /// Returns the `:code` for the given `block`. + /// + /// This takes into account potential overrides/substitutes. + pub fn code_at_ignoring_overrides(&self, block: Block::Hash) -> sp_blockchain::Result> { + let state = self.backend.state_at(block)?; + + let state_runtime_code = sp_state_machine::backend::BackendRuntimeCode::new(&state); + let runtime_code = + state_runtime_code.runtime_code().map_err(sp_blockchain::Error::RuntimeCode)?; + + self.maybe_override_code_internal(runtime_code, &state, block, true) + .and_then(|r| { + r.0.fetch_runtime_code().map(Into::into).ok_or_else(|| { + sp_blockchain::Error::Backend("Could not find `:code` in backend.".into()) + }) + }) + } + + /// Maybe override the given `onchain_code`. + /// + /// This takes into account potential overrides/substitutes. + pub fn maybe_override_code<'a>( + &'a self, + onchain_code: RuntimeCode<'a>, + state: &Backend::State, + hash: Block::Hash, + ) -> sp_blockchain::Result<(RuntimeCode<'a>, RuntimeVersion)> { + self.maybe_override_code_internal(onchain_code, state, hash, false) + } + + /// Maybe override the given `onchain_code`. + /// + /// This takes into account potential overrides(depending on `ignore_overrides`)/substitutes. + fn maybe_override_code_internal<'a>( + &'a self, + onchain_code: RuntimeCode<'a>, + state: &Backend::State, + hash: Block::Hash, + ignore_overrides: bool, + ) -> sp_blockchain::Result<(RuntimeCode<'a>, RuntimeVersion)> { + let on_chain_version = self.on_chain_runtime_version(&onchain_code, state)?; + let code_and_version = if let Some(d) = self.wasm_override.as_ref().as_ref().and_then(|o| { + if ignore_overrides { + return None + } + + o.get( + &on_chain_version.spec_version, + onchain_code.heap_pages, + &on_chain_version.spec_name, + ) + }) { + tracing::debug!(target: "code-provider::overrides", block = ?hash, "using WASM override"); + d + } else if let Some(s) = + self.wasm_substitutes + .get(on_chain_version.spec_version, onchain_code.heap_pages, hash) + { + tracing::debug!(target: "code-provider::substitutes", block = ?hash, "Using WASM substitute"); + s + } else { + tracing::debug!( + target: "code-provider", + block = ?hash, + "Neither WASM override nor substitute available, using onchain code", + ); + (onchain_code, on_chain_version) + }; + + Ok(code_and_version) + } + + /// Returns the on chain runtime version. + fn on_chain_runtime_version( + &self, + code: &RuntimeCode, + state: &Backend::State, + ) -> sp_blockchain::Result { + let mut overlay = OverlayedChanges::default(); + + let mut ext = Ext::new(&mut overlay, state, None); + + self.executor + .runtime_version(&mut ext, code) + .map_err(|e| sp_blockchain::Error::VersionInvalid(e.to_string())) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use backend::Backend; + use sc_client_api::{in_mem, HeaderBackend}; + use sc_executor::WasmExecutor; + use sp_core::{ + testing::TaskExecutor, + traits::{FetchRuntimeCode, WrappedRuntimeCode}, + }; + use std::collections::HashMap; + use substrate_test_runtime_client::{runtime, GenesisInit}; + + #[test] + fn no_override_no_substitutes_work() { + let executor = WasmExecutor::default(); + + let code_fetcher = WrappedRuntimeCode(substrate_test_runtime::wasm_binary_unwrap().into()); + let onchain_code = RuntimeCode { + code_fetcher: &code_fetcher, + heap_pages: Some(128), + hash: vec![0, 0, 0, 0], + }; + + let backend = Arc::new(in_mem::Backend::::new()); + + // wasm_runtime_overrides is `None` here because we construct the + // LocalCallExecutor directly later on + let client_config = ClientConfig::default(); + + let genesis_block_builder = crate::GenesisBlockBuilder::new( + &substrate_test_runtime_client::GenesisParameters::default().genesis_storage(), + !client_config.no_genesis, + backend.clone(), + executor.clone(), + ) + .expect("Creates genesis block builder"); + + // client is used for the convenience of creating and inserting the genesis block. + let _client = + crate::client::new_with_backend::<_, _, runtime::Block, _, runtime::RuntimeApi>( + backend.clone(), + executor.clone(), + genesis_block_builder, + Box::new(TaskExecutor::new()), + None, + None, + client_config.clone(), + ) + .expect("Creates a client"); + + let executor = Arc::new(executor); + + let code_provider = CodeProvider { + backend: backend.clone(), + executor: executor.clone(), + wasm_override: Arc::new(None), + wasm_substitutes: WasmSubstitutes::new(Default::default(), executor, backend.clone()) + .unwrap(), + }; + + let check = code_provider + .maybe_override_code( + onchain_code, + &backend.state_at(backend.blockchain().info().genesis_hash).unwrap(), + backend.blockchain().info().genesis_hash, + ) + .expect("RuntimeCode override") + .0; + + assert_eq!(code_fetcher.fetch_runtime_code(), check.fetch_runtime_code()); + } + + #[test] + fn should_get_override_if_exists() { + let executor = WasmExecutor::default(); + + let overrides = crate::client::wasm_override::dummy_overrides(); + let onchain_code = WrappedRuntimeCode(substrate_test_runtime::wasm_binary_unwrap().into()); + let onchain_code = RuntimeCode { + code_fetcher: &onchain_code, + heap_pages: Some(128), + hash: vec![0, 0, 0, 0], + }; + + let backend = Arc::new(in_mem::Backend::::new()); + + // wasm_runtime_overrides is `None` here because we construct the + // LocalCallExecutor directly later on + let client_config = ClientConfig::default(); + + let genesis_block_builder = crate::GenesisBlockBuilder::new( + &substrate_test_runtime_client::GenesisParameters::default().genesis_storage(), + !client_config.no_genesis, + backend.clone(), + executor.clone(), + ) + .expect("Creates genesis block builder"); + + // client is used for the convenience of creating and inserting the genesis block. + let _client = + crate::client::new_with_backend::<_, _, runtime::Block, _, runtime::RuntimeApi>( + backend.clone(), + executor.clone(), + genesis_block_builder, + Box::new(TaskExecutor::new()), + None, + None, + client_config.clone(), + ) + .expect("Creates a client"); + + let executor = Arc::new(executor); + + let code_provider = CodeProvider { + backend: backend.clone(), + executor: executor.clone(), + wasm_override: Arc::new(Some(overrides)), + wasm_substitutes: WasmSubstitutes::new(Default::default(), executor, backend.clone()) + .unwrap(), + }; + + let check = code_provider + .maybe_override_code( + onchain_code, + &backend.state_at(backend.blockchain().info().genesis_hash).unwrap(), + backend.blockchain().info().genesis_hash, + ) + .expect("RuntimeCode override") + .0; + + assert_eq!(Some(vec![2, 2, 2, 2, 2, 2, 2, 2]), check.fetch_runtime_code().map(Into::into)); + } + + #[test] + fn returns_runtime_version_from_substitute() { + const SUBSTITUTE_SPEC_NAME: &str = "substitute-spec-name-cool"; + + let executor = WasmExecutor::default(); + + let backend = Arc::new(in_mem::Backend::::new()); + + // Let's only override the `spec_name` for our testing purposes. + let substitute = sp_version::embed::embed_runtime_version( + &substrate_test_runtime::WASM_BINARY_BLOATY.unwrap(), + sp_version::RuntimeVersion { + spec_name: SUBSTITUTE_SPEC_NAME.into(), + ..substrate_test_runtime::VERSION + }, + ) + .unwrap(); + + let client_config = crate::client::ClientConfig { + wasm_runtime_substitutes: vec![(0, substitute)].into_iter().collect::>(), + ..Default::default() + }; + + let genesis_block_builder = crate::GenesisBlockBuilder::new( + &substrate_test_runtime_client::GenesisParameters::default().genesis_storage(), + !client_config.no_genesis, + backend.clone(), + executor.clone(), + ) + .expect("Creates genesis block builder"); + + // client is used for the convenience of creating and inserting the genesis block. + let client = + crate::client::new_with_backend::<_, _, runtime::Block, _, runtime::RuntimeApi>( + backend.clone(), + executor.clone(), + genesis_block_builder, + Box::new(TaskExecutor::new()), + None, + None, + client_config, + ) + .expect("Creates a client"); + + let version = client.runtime_version_at(client.chain_info().genesis_hash).unwrap(); + + assert_eq!(SUBSTITUTE_SPEC_NAME, &*version.spec_name); + } +} diff --git a/substrate/client/service/src/client/mod.rs b/substrate/client/service/src/client/mod.rs index 0703cc2b47d144d4e67418cfb9966cd1cd209392..ec77a92f162f0c2927a8d5fb6537e4e2ebb861a8 100644 --- a/substrate/client/service/src/client/mod.rs +++ b/substrate/client/service/src/client/mod.rs @@ -47,14 +47,14 @@ mod block_rules; mod call_executor; mod client; +mod code_provider; mod notification_pinning; mod wasm_override; mod wasm_substitutes; -pub use self::{ - call_executor::LocalCallExecutor, - client::{Client, ClientConfig}, -}; +pub use call_executor::LocalCallExecutor; +pub use client::{Client, ClientConfig}; +pub(crate) use code_provider::CodeProvider; #[cfg(feature = "test-helpers")] pub use self::client::{new_in_mem, new_with_backend}; diff --git a/substrate/client/service/src/client/wasm_substitutes.rs b/substrate/client/service/src/client/wasm_substitutes.rs index 70db0ef20f5a83907536f67d8ef36500a8065b48..07ca6c96062831f37ecf35ef70847f47ec9b20d8 100644 --- a/substrate/client/service/src/client/wasm_substitutes.rs +++ b/substrate/client/service/src/client/wasm_substitutes.rs @@ -94,7 +94,7 @@ impl From for sp_blockchain::Error { pub struct WasmSubstitutes { /// spec_version -> WasmSubstitute substitutes: Arc>>, - executor: Executor, + executor: Arc, backend: Arc, } @@ -110,14 +110,14 @@ impl Clone for WasmSubstitutes WasmSubstitutes where - Executor: RuntimeVersionOf + Clone + 'static, + Executor: RuntimeVersionOf, Backend: backend::Backend, Block: BlockT, { /// Create a new instance. pub fn new( substitutes: HashMap, Vec>, - executor: Executor, + executor: Arc, backend: Arc, ) -> Result { let substitutes = substitutes diff --git a/substrate/client/service/src/config.rs b/substrate/client/service/src/config.rs index 187e18aa3cace20c9fe9ffe2e9f3fdcbb6658bbd..e4788f1f3376cc24d2436fd0282bd9b2c1a28844 100644 --- a/substrate/client/service/src/config.rs +++ b/substrate/client/service/src/config.rs @@ -280,7 +280,7 @@ impl Default for RpcMethods { static mut BASE_PATH_TEMP: Option = None; /// The base path that is used for everything that needs to be written on disk to run a node. -#[derive(Debug)] +#[derive(Clone, Debug)] pub struct BasePath { path: PathBuf, } diff --git a/substrate/client/service/test/Cargo.toml b/substrate/client/service/test/Cargo.toml index 3c754231395273838b02f8020d646aebd9ea54a2..ade7b3b4e6a0be6be4fd3f697e8cdcfc5ccc308d 100644 --- a/substrate/client/service/test/Cargo.toml +++ b/substrate/client/service/test/Cargo.toml @@ -15,33 +15,33 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -async-channel = "1.8.0" -array-bytes = "6.2.2" -fdlimit = "0.3.0" -futures = "0.3.30" +async-channel = { workspace = true } +array-bytes = { workspace = true, default-features = true } +fdlimit = { workspace = true } +futures = { workspace = true } log = { workspace = true, default-features = true } -codec = { package = "parity-scale-codec", version = "3.6.12" } -parking_lot = "0.12.1" -tempfile = "3.1.0" -tokio = { version = "1.22.0", features = ["time"] } -sc-block-builder = { path = "../../block-builder" } -sc-client-api = { path = "../../api" } -sc-client-db = { path = "../../db", default-features = false } -sc-consensus = { path = "../../consensus/common" } -sc-executor = { path = "../../executor" } -sc-network = { path = "../../network" } -sc-network-sync = { path = "../../network/sync" } -sc-service = { path = "..", features = ["test-helpers"] } -sc-transaction-pool-api = { path = "../../transaction-pool/api" } -sp-api = { path = "../../../primitives/api" } -sp-blockchain = { path = "../../../primitives/blockchain" } -sp-consensus = { path = "../../../primitives/consensus/common" } -sp-core = { path = "../../../primitives/core" } -sp-runtime = { path = "../../../primitives/runtime" } -sp-state-machine = { path = "../../../primitives/state-machine" } -sp-storage = { path = "../../../primitives/storage" } -sp-tracing = { path = "../../../primitives/tracing" } -sp-trie = { path = "../../../primitives/trie" } -sp-io = { path = "../../../primitives/io" } -substrate-test-runtime = { path = "../../../test-utils/runtime" } -substrate-test-runtime-client = { path = "../../../test-utils/runtime/client" } +codec = { workspace = true, default-features = true } +parking_lot = { workspace = true, default-features = true } +tempfile = { workspace = true } +tokio = { features = ["time"], workspace = true, default-features = true } +sc-block-builder = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-client-db = { workspace = true } +sc-consensus = { workspace = true, default-features = true } +sc-executor = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sc-network-sync = { workspace = true, default-features = true } +sc-service = { features = ["test-helpers"], workspace = true, default-features = true } +sc-transaction-pool-api = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-state-machine = { workspace = true, default-features = true } +sp-storage = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +sp-trie = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +substrate-test-runtime = { workspace = true } +substrate-test-runtime-client = { workspace = true } diff --git a/substrate/client/state-db/Cargo.toml b/substrate/client/state-db/Cargo.toml index e203eb5a3282fa1ed73c75426b6039f046bef7d7..be4f1ef973c98da80f206b98a38abf375fbefb36 100644 --- a/substrate/client/state-db/Cargo.toml +++ b/substrate/client/state-db/Cargo.toml @@ -16,7 +16,7 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } +codec = { features = ["derive"], workspace = true, default-features = true } log = { workspace = true, default-features = true } -parking_lot = "0.12.1" -sp-core = { path = "../../primitives/core" } +parking_lot = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } diff --git a/substrate/client/statement-store/Cargo.toml b/substrate/client/statement-store/Cargo.toml index 8ca6d11dbe0dc786929925a90a40b5035f2607be..1cb682f054d72409b2a77b84f2b4cbc63eeaf728 100644 --- a/substrate/client/statement-store/Cargo.toml +++ b/substrate/client/statement-store/Cargo.toml @@ -17,18 +17,18 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] log = { workspace = true, default-features = true } -parking_lot = "0.12.1" -parity-db = "0.4.12" -tokio = { version = "1.22.0", features = ["time"] } -sp-statement-store = { path = "../../primitives/statement-store" } -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../utils/prometheus" } -sp-api = { path = "../../primitives/api" } -sp-blockchain = { path = "../../primitives/blockchain" } -sp-core = { path = "../../primitives/core" } -sp-runtime = { path = "../../primitives/runtime" } -sc-client-api = { path = "../api" } -sc-keystore = { path = "../keystore" } +parking_lot = { workspace = true, default-features = true } +parity-db = { workspace = true } +tokio = { features = ["time"], workspace = true, default-features = true } +sp-statement-store = { workspace = true, default-features = true } +prometheus-endpoint = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-keystore = { workspace = true, default-features = true } [dev-dependencies] -tempfile = "3.1.0" -env_logger = "0.11" +tempfile = { workspace = true } +env_logger = { workspace = true } diff --git a/substrate/client/storage-monitor/Cargo.toml b/substrate/client/storage-monitor/Cargo.toml index 5248ebdf9a650ba2e1fd1a34f18dbbc0b16781fe..8c490284dccc6baae71a678702187c84cfb3b7a4 100644 --- a/substrate/client/storage-monitor/Cargo.toml +++ b/substrate/client/storage-monitor/Cargo.toml @@ -12,9 +12,9 @@ homepage = "https://substrate.io" workspace = true [dependencies] -clap = { version = "4.5.3", features = ["derive", "string"] } +clap = { features = ["derive", "string"], workspace = true } log = { workspace = true, default-features = true } -fs4 = "0.7.0" -sp-core = { path = "../../primitives/core" } -tokio = { version = "1.22.0", features = ["time"] } +fs4 = { workspace = true } +sp-core = { workspace = true, default-features = true } +tokio = { features = ["time"], workspace = true, default-features = true } thiserror = { workspace = true } diff --git a/substrate/client/sync-state-rpc/Cargo.toml b/substrate/client/sync-state-rpc/Cargo.toml index d5bdc920f7c9b48991354f5df917a3b3d72c86fa..1cbaadb70fff99d8242d6930a2857d1918a6f3ed 100644 --- a/substrate/client/sync-state-rpc/Cargo.toml +++ b/substrate/client/sync-state-rpc/Cargo.toml @@ -15,15 +15,15 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12" } -jsonrpsee = { version = "0.22.5", features = ["client-core", "macros", "server-core"] } +codec = { workspace = true, default-features = true } +jsonrpsee = { features = ["client-core", "macros", "server-core"], workspace = true } serde = { features = ["derive"], workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } thiserror = { workspace = true } -sc-chain-spec = { path = "../chain-spec" } -sc-client-api = { path = "../api" } -sc-consensus-babe = { path = "../consensus/babe" } -sc-consensus-epochs = { path = "../consensus/epochs" } -sc-consensus-grandpa = { path = "../consensus/grandpa" } -sp-blockchain = { path = "../../primitives/blockchain" } -sp-runtime = { path = "../../primitives/runtime" } +sc-chain-spec = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-consensus-babe = { workspace = true, default-features = true } +sc-consensus-epochs = { workspace = true, default-features = true } +sc-consensus-grandpa = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } diff --git a/substrate/client/sysinfo/Cargo.toml b/substrate/client/sysinfo/Cargo.toml index 32b7755c64b5046fcd31cb6e0d9ff2c1061ed57a..f79345d67242901381a42470a851f509c3a910f5 100644 --- a/substrate/client/sysinfo/Cargo.toml +++ b/substrate/client/sysinfo/Cargo.toml @@ -17,20 +17,20 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -futures = "0.3.30" -libc = "0.2" +futures = { workspace = true } +libc = { workspace = true } log = { workspace = true, default-features = true } -rand = "0.8.5" -rand_pcg = "0.3.1" -derive_more = "0.99" -regex = "1" +rand = { workspace = true, default-features = true } +rand_pcg = { workspace = true } +derive_more = { workspace = true, default-features = true } +regex = { workspace = true } serde = { features = ["derive"], workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } -sc-telemetry = { path = "../telemetry" } -sp-core = { path = "../../primitives/core" } -sp-crypto-hashing = { path = "../../primitives/crypto/hashing" } -sp-io = { path = "../../primitives/io" } -sp-std = { path = "../../primitives/std" } +sc-telemetry = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-crypto-hashing = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-std = { workspace = true, default-features = true } [dev-dependencies] -sp-runtime = { path = "../../primitives/runtime" } +sp-runtime = { workspace = true, default-features = true } diff --git a/substrate/client/telemetry/Cargo.toml b/substrate/client/telemetry/Cargo.toml index 0cce2acf6409c1a1a179d60d31b997469e8fd87e..a789ebc5f1afd569e6b1ea66b0b2ff7227335d4b 100644 --- a/substrate/client/telemetry/Cargo.toml +++ b/substrate/client/telemetry/Cargo.toml @@ -17,16 +17,16 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -chrono = "0.4.31" -futures = "0.3.30" -libp2p = { version = "0.51.4", features = ["dns", "tcp", "tokio", "wasm-ext", "websocket"] } +chrono = { workspace = true } +futures = { workspace = true } +libp2p = { features = ["dns", "tcp", "tokio", "wasm-ext", "websocket"], workspace = true } log = { workspace = true, default-features = true } -parking_lot = "0.12.1" -pin-project = "1.0.12" -sc-utils = { path = "../utils" } -sc-network = { path = "../network" } -rand = "0.8.5" +parking_lot = { workspace = true, default-features = true } +pin-project = { workspace = true } +sc-utils = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +rand = { workspace = true, default-features = true } serde = { features = ["derive"], workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } thiserror = { workspace = true } -wasm-timer = "0.2.5" +wasm-timer = { workspace = true } diff --git a/substrate/client/telemetry/src/transport.rs b/substrate/client/telemetry/src/transport.rs index a82626caac2d340bfcee90dd7c1f06ac4a6edccd..ca6ceecbed63b1574c09971250ea5ea247349ef2 100644 --- a/substrate/client/telemetry/src/transport.rs +++ b/substrate/client/telemetry/src/transport.rs @@ -31,7 +31,7 @@ const CONNECT_TIMEOUT: Duration = Duration::from_secs(20); pub(crate) fn initialize_transport() -> Result { let transport = { let tcp_transport = libp2p::tcp::tokio::Transport::new(libp2p::tcp::Config::new()); - let inner = libp2p::dns::TokioDnsConfig::system(tcp_transport)?; + let inner = libp2p::dns::tokio::Transport::system(tcp_transport)?; libp2p::websocket::framed::WsConfig::new(inner).and_then(|connec, _| { let connec = connec .with(|item| { diff --git a/substrate/client/tracing/Cargo.toml b/substrate/client/tracing/Cargo.toml index df674d24c6dd79b36ef7aa7aa36d389a7702678d..cacb1351416a9f4087d7f7db2a6b0ebbea21c447 100644 --- a/substrate/client/tracing/Cargo.toml +++ b/substrate/client/tracing/Cargo.toml @@ -16,32 +16,32 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -ansi_term = "0.12.1" -is-terminal = "0.4.9" -chrono = "0.4.31" -codec = { package = "parity-scale-codec", version = "3.6.12" } -lazy_static = "1.4.0" -libc = "0.2.152" +ansi_term = { workspace = true } +is-terminal = { workspace = true } +chrono = { workspace = true } +codec = { workspace = true, default-features = true } +lazy_static = { workspace = true } +libc = { workspace = true } log = { workspace = true, default-features = true } -parking_lot = "0.12.1" -regex = "1.6.0" -rustc-hash = "1.1.0" +parking_lot = { workspace = true, default-features = true } +regex = { workspace = true } +rustc-hash = { workspace = true } serde = { workspace = true, default-features = true } thiserror = { workspace = true } -tracing = "0.1.29" -tracing-log = "0.2.0" +tracing = { workspace = true, default-features = true } +tracing-log = { workspace = true } tracing-subscriber = { workspace = true, features = ["env-filter", "parking_lot"] } -sc-client-api = { path = "../api" } -sc-tracing-proc-macro = { path = "proc-macro" } -sp-api = { path = "../../primitives/api" } -sp-blockchain = { path = "../../primitives/blockchain" } -sp-core = { path = "../../primitives/core" } -sp-rpc = { path = "../../primitives/rpc" } -sp-runtime = { path = "../../primitives/runtime" } -sp-tracing = { path = "../../primitives/tracing" } +sc-client-api = { workspace = true, default-features = true } +sc-tracing-proc-macro = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-rpc = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } [dev-dependencies] -criterion = "0.5.1" +criterion = { workspace = true, default-features = true } tracing-subscriber = { workspace = true, features = ["chrono", "parking_lot"] } [[bench]] diff --git a/substrate/client/tracing/proc-macro/Cargo.toml b/substrate/client/tracing/proc-macro/Cargo.toml index fec34aa0bca935e22f0f7d7faea17cac5d8f10bb..9162bdc1ad8ab2d2de1938180b26cb6cb0426ab0 100644 --- a/substrate/client/tracing/proc-macro/Cargo.toml +++ b/substrate/client/tracing/proc-macro/Cargo.toml @@ -18,7 +18,7 @@ targets = ["x86_64-unknown-linux-gnu"] proc-macro = true [dependencies] -proc-macro-crate = "3.0.0" -proc-macro2 = "1.0.56" +proc-macro-crate = { workspace = true } +proc-macro2 = { workspace = true } quote = { features = ["proc-macro"], workspace = true } syn = { features = ["extra-traits", "full", "parsing", "proc-macro"], workspace = true } diff --git a/substrate/client/transaction-pool/Cargo.toml b/substrate/client/transaction-pool/Cargo.toml index 351650297ffc599a0081dff9cf0514dc6c6fc810..95b391faf169ea5fd8b431d504f0addcc2798798 100644 --- a/substrate/client/transaction-pool/Cargo.toml +++ b/substrate/client/transaction-pool/Cargo.toml @@ -16,36 +16,36 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -async-trait = "0.1.79" -codec = { package = "parity-scale-codec", version = "3.6.12" } -futures = "0.3.30" -futures-timer = "3.0.2" -linked-hash-map = "0.5.4" +async-trait = { workspace = true } +codec = { workspace = true, default-features = true } +futures = { workspace = true } +futures-timer = { workspace = true } +linked-hash-map = { workspace = true } log = { workspace = true, default-features = true } -parking_lot = "0.12.1" +parking_lot = { workspace = true, default-features = true } serde = { features = ["derive"], workspace = true, default-features = true } thiserror = { workspace = true } -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../utils/prometheus" } -sc-client-api = { path = "../api" } -sc-transaction-pool-api = { path = "api" } -sc-utils = { path = "../utils" } -sp-api = { path = "../../primitives/api" } -sp-blockchain = { path = "../../primitives/blockchain" } -sp-core = { path = "../../primitives/core" } -sp-crypto-hashing = { path = "../../primitives/crypto/hashing" } -sp-runtime = { path = "../../primitives/runtime" } -sp-tracing = { path = "../../primitives/tracing" } -sp-transaction-pool = { path = "../../primitives/transaction-pool" } +prometheus-endpoint = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-transaction-pool-api = { workspace = true, default-features = true } +sc-utils = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-crypto-hashing = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +sp-transaction-pool = { workspace = true, default-features = true } [dev-dependencies] -array-bytes = "6.2.2" -assert_matches = "1.3.0" -criterion = "0.5.1" -sc-block-builder = { path = "../block-builder" } -sp-consensus = { path = "../../primitives/consensus/common" } -substrate-test-runtime = { path = "../../test-utils/runtime" } -substrate-test-runtime-client = { path = "../../test-utils/runtime/client" } -substrate-test-runtime-transaction-pool = { path = "../../test-utils/runtime/transaction-pool" } +array-bytes = { workspace = true, default-features = true } +assert_matches = { workspace = true } +criterion = { workspace = true, default-features = true } +sc-block-builder = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +substrate-test-runtime = { workspace = true } +substrate-test-runtime-client = { workspace = true } +substrate-test-runtime-transaction-pool = { workspace = true } [[bench]] name = "basics" diff --git a/substrate/client/transaction-pool/api/Cargo.toml b/substrate/client/transaction-pool/api/Cargo.toml index be80a7706b3efe653ceaf071f42a4e017bc428db..6fec613c1114d36c2dbc7ebd50314a2feb288b12 100644 --- a/substrate/client/transaction-pool/api/Cargo.toml +++ b/substrate/client/transaction-pool/api/Cargo.toml @@ -12,15 +12,15 @@ description = "Transaction pool client facing API." workspace = true [dependencies] -async-trait = "0.1.79" -codec = { package = "parity-scale-codec", version = "3.6.12" } -futures = "0.3.30" +async-trait = { workspace = true } +codec = { workspace = true, default-features = true } +futures = { workspace = true } log = { workspace = true, default-features = true } serde = { features = ["derive"], workspace = true, default-features = true } thiserror = { workspace = true } -sp-blockchain = { path = "../../../primitives/blockchain" } -sp-core = { path = "../../../primitives/core", default-features = false } -sp-runtime = { path = "../../../primitives/runtime", default-features = false } +sp-blockchain = { workspace = true, default-features = true } +sp-core = { workspace = true } +sp-runtime = { workspace = true } [dev-dependencies] serde_json = { workspace = true, default-features = true } diff --git a/substrate/client/utils/Cargo.toml b/substrate/client/utils/Cargo.toml index a101f4b3f3ad009a35c1cc061e4c9515b98e1419..4053d77a13ebfcf587848c67d6af848f12af7084 100644 --- a/substrate/client/utils/Cargo.toml +++ b/substrate/client/utils/Cargo.toml @@ -13,18 +13,18 @@ readme = "README.md" workspace = true [dependencies] -async-channel = "1.8.0" -futures = "0.3.30" -futures-timer = "3.0.2" -lazy_static = "1.4.0" +async-channel = { workspace = true } +futures = { workspace = true } +futures-timer = { workspace = true } +lazy_static = { workspace = true } log = { workspace = true, default-features = true } -parking_lot = "0.12.1" -prometheus = { version = "0.13.0", default-features = false } -sp-arithmetic = { path = "../../primitives/arithmetic", default-features = false } +parking_lot = { workspace = true, default-features = true } +prometheus = { workspace = true } +sp-arithmetic = { workspace = true } [features] default = ["metered"] metered = [] [dev-dependencies] -tokio-test = "0.4.2" +tokio-test = { workspace = true } diff --git a/substrate/deprecated/hashing/Cargo.toml b/substrate/deprecated/hashing/Cargo.toml index 8695ccc8fca2241b3947e7f2ac6a070174a158a3..9db6cb64050d64988e5926ef4c985732c5a10e1d 100644 --- a/substrate/deprecated/hashing/Cargo.toml +++ b/substrate/deprecated/hashing/Cargo.toml @@ -16,7 +16,7 @@ maintenance = { status = "deprecated" } targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-crypto-hashing = { path = "../../primitives/crypto/hashing" } +sp-crypto-hashing = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/deprecated/hashing/proc-macro/Cargo.toml b/substrate/deprecated/hashing/proc-macro/Cargo.toml index aa78809241f0394e5f984c5a41a151a9ba247595..ec5188bc53bd9b293dccef00a2b4dcea98e9e584 100644 --- a/substrate/deprecated/hashing/proc-macro/Cargo.toml +++ b/substrate/deprecated/hashing/proc-macro/Cargo.toml @@ -16,4 +16,4 @@ maintenance = { status = "deprecated" } targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-crypto-hashing-proc-macro = { path = "../../../primitives/crypto/hashing/proc-macro" } +sp-crypto-hashing-proc-macro = { workspace = true, default-features = true } diff --git a/substrate/frame/Cargo.toml b/substrate/frame/Cargo.toml index a3b3d1900e6e6b536a876705a443d810fbe09f4d..594cb505cd60ff97b8247f4a9d284c3b3b82139f 100644 --- a/substrate/frame/Cargo.toml +++ b/substrate/frame/Cargo.toml @@ -18,51 +18,51 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] # external deps -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", -] } -scale-info = { version = "2.11.1", default-features = false, features = [ +], workspace = true } +scale-info = { features = [ "derive", -] } +], workspace = true } # primitive deps, used for developing FRAME pallets. -sp-runtime = { default-features = false, path = "../primitives/runtime" } -sp-std = { default-features = false, path = "../primitives/std" } -sp-io = { default-features = false, path = "../primitives/io" } -sp-core = { default-features = false, path = "../primitives/core" } -sp-arithmetic = { default-features = false, path = "../primitives/arithmetic" } +sp-runtime = { workspace = true } +sp-std = { workspace = true } +sp-io = { workspace = true } +sp-core = { workspace = true } +sp-arithmetic = { workspace = true } # frame deps, for developing FRAME pallets. -frame-support = { default-features = false, path = "support" } -frame-system = { default-features = false, path = "system" } +frame-support = { workspace = true } +frame-system = { workspace = true } # primitive types used for developing FRAME runtimes. -sp-version = { default-features = false, path = "../primitives/version", optional = true } -sp-api = { default-features = false, path = "../primitives/api", optional = true } -sp-block-builder = { default-features = false, path = "../primitives/block-builder", optional = true } -sp-transaction-pool = { default-features = false, path = "../primitives/transaction-pool", optional = true } -sp-offchain = { default-features = false, path = "../primitives/offchain", optional = true } -sp-session = { default-features = false, path = "../primitives/session", optional = true } -sp-consensus-aura = { default-features = false, path = "../primitives/consensus/aura", optional = true } -sp-consensus-grandpa = { default-features = false, path = "../primitives/consensus/grandpa", optional = true } -sp-inherents = { default-features = false, path = "../primitives/inherents", optional = true } -sp-storage = { default-features = false, path = "../primitives/storage", optional = true } +sp-version = { optional = true, workspace = true } +sp-api = { optional = true, workspace = true } +sp-block-builder = { optional = true, workspace = true } +sp-transaction-pool = { optional = true, workspace = true } +sp-offchain = { optional = true, workspace = true } +sp-session = { optional = true, workspace = true } +sp-consensus-aura = { optional = true, workspace = true } +sp-consensus-grandpa = { optional = true, workspace = true } +sp-inherents = { optional = true, workspace = true } +sp-storage = { optional = true, workspace = true } -frame-executive = { default-features = false, path = "../frame/executive", optional = true } -frame-system-rpc-runtime-api = { default-features = false, path = "../frame/system/rpc/runtime-api", optional = true } +frame-executive = { optional = true, workspace = true } +frame-system-rpc-runtime-api = { optional = true, workspace = true } # Used for runtime benchmarking -frame-benchmarking = { default-features = false, path = "../frame/benchmarking", optional = true } -frame-system-benchmarking = { default-features = false, path = "../frame/system/benchmarking", optional = true } +frame-benchmarking = { optional = true, workspace = true } +frame-system-benchmarking = { optional = true, workspace = true } # Used for try-runtime -frame-try-runtime = { default-features = false, path = "../frame/try-runtime", optional = true } +frame-try-runtime = { optional = true, workspace = true } -docify = "0.2.8" +docify = { workspace = true } log = { workspace = true } [dev-dependencies] -pallet-examples = { path = "./examples" } +pallet-examples = { workspace = true } [features] default = ["runtime", "std"] diff --git a/substrate/frame/alliance/Cargo.toml b/substrate/frame/alliance/Cargo.toml index 10e2feba62376d9cd8346f44531dbd3e6bc47870..7ad9961d9b89cfd28023e70934a2697cadaa6984 100644 --- a/substrate/frame/alliance/Cargo.toml +++ b/substrate/frame/alliance/Cargo.toml @@ -16,30 +16,30 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -array-bytes = { version = "6.2.2", optional = true } +array-bytes = { optional = true, workspace = true, default-features = true } log = { workspace = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } -sp-std = { path = "../../primitives/std", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-crypto-hashing = { path = "../../primitives/crypto/hashing", default-features = false, optional = true } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } +sp-std = { workspace = true } +sp-core = { workspace = true } +sp-crypto-hashing = { optional = true, workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } -pallet-identity = { path = "../identity", default-features = false } -pallet-collective = { path = "../collective", default-features = false, optional = true } +pallet-identity = { workspace = true } +pallet-collective = { optional = true, workspace = true } [dev-dependencies] -array-bytes = "6.2.2" -sp-crypto-hashing = { path = "../../primitives/crypto/hashing", default-features = false } -pallet-balances = { path = "../balances" } -pallet-collective = { path = "../collective" } +array-bytes = { workspace = true, default-features = true } +sp-crypto-hashing = { workspace = true } +pallet-balances = { workspace = true, default-features = true } +pallet-collective = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/alliance/src/mock.rs b/substrate/frame/alliance/src/mock.rs index a9cfd6d0fde0eb149e4f33db86823e7e711426cd..1a0a899bcccb4b8a7f194f0770de03bf7fab7451 100644 --- a/substrate/frame/alliance/src/mock.rs +++ b/substrate/frame/alliance/src/mock.rs @@ -52,24 +52,9 @@ impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; } -parameter_types! { - pub const ExistentialDeposit: u64 = 1; - pub const MaxLocks: u32 = 10; -} +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type Balance = u64; - type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; - type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type WeightInfo = (); - type MaxLocks = MaxLocks; - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } const MOTION_DURATION_IN_BLOCKS: BlockNumber = 3; diff --git a/substrate/frame/asset-conversion/Cargo.toml b/substrate/frame/asset-conversion/Cargo.toml index bfcda2299d5a116eca62a5870a84823876bc89f5..27d86bf6710b0c343e72f8c0b01494020bb4b0d3 100644 --- a/substrate/frame/asset-conversion/Cargo.toml +++ b/substrate/frame/asset-conversion/Cargo.toml @@ -16,23 +16,23 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -log = { version = "0.4.20", default-features = false } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -sp-api = { path = "../../primitives/api", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-arithmetic = { path = "../../primitives/arithmetic", default-features = false } +codec = { workspace = true } +log = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +frame-benchmarking = { optional = true, workspace = true } +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 } [dev-dependencies] -pallet-balances = { path = "../balances" } -pallet-assets = { path = "../assets" } -primitive-types = { version = "0.12.0", default-features = false, features = ["codec", "num-traits", "scale-info"] } +pallet-balances = { workspace = true, default-features = true } +pallet-assets = { workspace = true, default-features = true } +primitive-types = { features = ["codec", "num-traits", "scale-info"], workspace = true } [features] default = ["std"] diff --git a/substrate/frame/asset-conversion/ops/Cargo.toml b/substrate/frame/asset-conversion/ops/Cargo.toml index c5efbf9f6f442b0430cecab10badb4ca13e49d0a..0dc6cd5b1672ae02fcaf8b9a08fd51618bf981c5 100644 --- a/substrate/frame/asset-conversion/ops/Cargo.toml +++ b/substrate/frame/asset-conversion/ops/Cargo.toml @@ -15,23 +15,23 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -log = { version = "0.4.20", default-features = false } -frame-support = { path = "../../support", default-features = false } -frame-system = { path = "../../system", default-features = false } -frame-benchmarking = { path = "../../benchmarking", default-features = false, optional = true } -pallet-asset-conversion = { path = "..", default-features = false } -scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -sp-core = { path = "../../../primitives/core", default-features = false } -sp-io = { path = "../../../primitives/io", default-features = false } -sp-std = { path = "../../../primitives/std", default-features = false } -sp-runtime = { path = "../../../primitives/runtime", default-features = false } -sp-arithmetic = { path = "../../../primitives/arithmetic", default-features = false } +codec = { workspace = true } +log = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +frame-benchmarking = { optional = true, workspace = true } +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 } [dev-dependencies] -pallet-balances = { path = "../../balances" } -pallet-assets = { path = "../../assets" } -primitive-types = { version = "0.12.0", default-features = false, features = ["codec", "num-traits", "scale-info"] } +pallet-balances = { workspace = true, default-features = true } +pallet-assets = { workspace = true, default-features = true } +primitive-types = { features = ["codec", "num-traits", "scale-info"], workspace = true } [features] default = ["std"] diff --git a/substrate/frame/asset-conversion/ops/src/mock.rs b/substrate/frame/asset-conversion/ops/src/mock.rs index 9454b3a9ad448af4b47d9fd974e6ec8ad5ed4e59..91c18b2e79494eb39812c0aca9f33dfdf6710d60 100644 --- a/substrate/frame/asset-conversion/ops/src/mock.rs +++ b/substrate/frame/asset-conversion/ops/src/mock.rs @@ -52,7 +52,7 @@ construct_runtime!( } ); -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +#[derive_impl(frame_system::config_preludes::TestDefaultConfig)] impl frame_system::Config for Test { type Block = Block; type AccountData = pallet_balances::AccountData; @@ -60,7 +60,6 @@ impl frame_system::Config for Test { #[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type ReserveIdentifier = [u8; 8]; type AccountStore = System; } diff --git a/substrate/frame/asset-conversion/src/mock.rs b/substrate/frame/asset-conversion/src/mock.rs index 477866e0051bc43207d1fb728380e5f84258964f..d8832d70488af7d38507c83a964bc1c2c07815d0 100644 --- a/substrate/frame/asset-conversion/src/mock.rs +++ b/substrate/frame/asset-conversion/src/mock.rs @@ -61,20 +61,11 @@ impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { type Balance = u128; - type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; type ExistentialDeposit = ConstU128<100>; type AccountStore = System; - type WeightInfo = (); - type MaxLocks = (); - type MaxReserves = ConstU32<50>; - type ReserveIdentifier = [u8; 8]; - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } impl pallet_assets::Config for Test { diff --git a/substrate/frame/asset-rate/Cargo.toml b/substrate/frame/asset-rate/Cargo.toml index 4662469e46ce423edaab234041a852a42b0711bb..96c87020684fbf195b8d2cac1976c4884ea6d7cc 100644 --- a/substrate/frame/asset-rate/Cargo.toml +++ b/substrate/frame/asset-rate/Cargo.toml @@ -15,21 +15,21 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", -] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false, optional = true } +], workspace = true } +scale-info = { features = ["derive"], workspace = true } +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] -pallet-balances = { path = "../balances" } -sp-io = { path = "../../primitives/io" } -sp-core = { path = "../../primitives/core", default-features = false } +pallet-balances = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-core = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/asset-rate/src/mock.rs b/substrate/frame/asset-rate/src/mock.rs index d01996dab193d6d6e21a14efed7f14ff2ef8c931..c829d78afa886ad50546196322e37921c7240ed7 100644 --- a/substrate/frame/asset-rate/src/mock.rs +++ b/substrate/frame/asset-rate/src/mock.rs @@ -18,7 +18,7 @@ //! The crate's mock. use crate as pallet_asset_rate; -use frame_support::{derive_impl, traits::ConstU64}; +use frame_support::derive_impl; use sp_runtime::BuildStorage; type Block = frame_system::mocking::MockBlock; @@ -38,20 +38,9 @@ impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type Balance = u64; - type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; - type ExistentialDeposit = ConstU64<1>; type AccountStore = System; - type WeightInfo = (); - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeFreezeReason; - type FreezeIdentifier = (); - type MaxFreezes = (); } impl pallet_asset_rate::Config for Test { diff --git a/substrate/frame/assets-freezer/Cargo.toml b/substrate/frame/assets-freezer/Cargo.toml new file mode 100644 index 0000000000000000000000000000000000000000..97eadd8465a70d5d356a91c92f5169597ded9b40 --- /dev/null +++ b/substrate/frame/assets-freezer/Cargo.toml @@ -0,0 +1,61 @@ +[package] +name = "pallet-assets-freezer" +version = "0.1.0" +authors.workspace = true +edition.workspace = true +license = "MIT-0" +homepage = "https://substrate.io" +repository.workspace = true +description = "Provides freezing features to `pallet-assets`" + +[lints] +workspace = true + +[package.metadata.docs.rs] +targets = ["x86_64-unknown-linux-gnu"] + +[dependencies] +codec = { workspace = true } +log = { workspace = true } +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-assets = { workspace = true } +sp-runtime = { workspace = true } + +[dev-dependencies] +sp-io = { workspace = true } +sp-core = { workspace = true } +pallet-balances = { workspace = true } + +[features] +default = ["std"] +std = [ + "codec/std", + "frame-benchmarking?/std", + "frame-support/std", + "frame-system/std", + "log/std", + "pallet-assets/std", + "pallet-balances/std", + "scale-info/std", + "sp-core/std", + "sp-io/std", + "sp-runtime/std", +] +runtime-benchmarks = [ + "frame-benchmarking/runtime-benchmarks", + "frame-support/runtime-benchmarks", + "frame-system/runtime-benchmarks", + "pallet-assets/runtime-benchmarks", + "pallet-balances/runtime-benchmarks", + "sp-runtime/runtime-benchmarks", +] +try-runtime = [ + "frame-support/try-runtime", + "frame-system/try-runtime", + "pallet-assets/try-runtime", + "pallet-balances/try-runtime", + "sp-runtime/try-runtime", +] diff --git a/substrate/frame/assets-freezer/src/impls.rs b/substrate/frame/assets-freezer/src/impls.rs new file mode 100644 index 0000000000000000000000000000000000000000..cd383f1c3cd1e68f7cc0bcf0bb2841f0acf52119 --- /dev/null +++ b/substrate/frame/assets-freezer/src/impls.rs @@ -0,0 +1,158 @@ +// 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. + +use super::*; + +use frame_support::traits::{ + fungibles::{Inspect, InspectFreeze, MutateFreeze}, + tokens::{DepositConsequence, Fortitude, Preservation, Provenance, WithdrawConsequence}, +}; +use pallet_assets::FrozenBalance; +use sp_runtime::traits::Zero; + +// Implements [`FrozenBalance`] from [`pallet-assets`], so it can understand how much of an +// account balance is frozen, and is able to signal to this pallet when to clear the state of an +// account. +impl, I: 'static> FrozenBalance + for Pallet +{ + fn frozen_balance(asset: T::AssetId, who: &T::AccountId) -> Option { + FrozenBalances::::get(asset, who) + } + + fn died(asset: T::AssetId, who: &T::AccountId) { + FrozenBalances::::remove(asset.clone(), who); + Freezes::::remove(asset, who); + } +} + +// Implement [`fungibles::Inspect`](frame_support::traits::fungibles::Inspect) as it is bound by +// [`fungibles::InspectFreeze`](frame_support::traits::fungibles::InspectFreeze) and +// [`fungibles::MutateFreeze`](frame_support::traits::fungibles::MutateFreeze). To do so, we'll +// re-export all of `pallet-assets` implementation of the same trait. +impl, I: 'static> Inspect for Pallet { + type AssetId = T::AssetId; + type Balance = T::Balance; + + fn total_issuance(asset: Self::AssetId) -> Self::Balance { + pallet_assets::Pallet::::total_issuance(asset) + } + + fn minimum_balance(asset: Self::AssetId) -> Self::Balance { + pallet_assets::Pallet::::minimum_balance(asset) + } + + fn total_balance(asset: Self::AssetId, who: &T::AccountId) -> Self::Balance { + pallet_assets::Pallet::::total_balance(asset, who) + } + + fn balance(asset: Self::AssetId, who: &T::AccountId) -> Self::Balance { + pallet_assets::Pallet::::balance(asset, who) + } + + fn reducible_balance( + asset: Self::AssetId, + who: &T::AccountId, + preservation: Preservation, + force: Fortitude, + ) -> Self::Balance { + pallet_assets::Pallet::::reducible_balance(asset, who, preservation, force) + } + + fn can_deposit( + asset: Self::AssetId, + who: &T::AccountId, + amount: Self::Balance, + provenance: Provenance, + ) -> DepositConsequence { + pallet_assets::Pallet::::can_deposit(asset, who, amount, provenance) + } + + fn can_withdraw( + asset: Self::AssetId, + who: &T::AccountId, + amount: Self::Balance, + ) -> WithdrawConsequence { + pallet_assets::Pallet::::can_withdraw(asset, who, amount) + } + + fn asset_exists(asset: Self::AssetId) -> bool { + pallet_assets::Pallet::::asset_exists(asset) + } +} + +impl, I: 'static> InspectFreeze for Pallet { + type Id = T::RuntimeFreezeReason; + + fn balance_frozen(asset: Self::AssetId, id: &Self::Id, who: &T::AccountId) -> Self::Balance { + let freezes = Freezes::::get(asset, who); + freezes.into_iter().find(|l| &l.id == id).map_or(Zero::zero(), |l| l.amount) + } + + fn can_freeze(asset: Self::AssetId, id: &Self::Id, who: &T::AccountId) -> bool { + let freezes = Freezes::::get(asset, who); + !freezes.is_full() || freezes.into_iter().any(|i| i.id == *id) + } +} + +impl, I: 'static> MutateFreeze for Pallet { + fn set_freeze( + asset: Self::AssetId, + id: &Self::Id, + who: &T::AccountId, + amount: Self::Balance, + ) -> sp_runtime::DispatchResult { + if amount.is_zero() { + return Self::thaw(asset, id, who); + } + let mut freezes = Freezes::::get(asset.clone(), who); + if let Some(i) = freezes.iter_mut().find(|i| &i.id == id) { + i.amount = amount; + } else { + freezes + .try_push(IdAmount { id: *id, amount }) + .map_err(|_| Error::::TooManyFreezes)?; + } + Self::update_freezes(asset, who, freezes.as_bounded_slice()) + } + + fn extend_freeze( + asset: Self::AssetId, + id: &Self::Id, + who: &T::AccountId, + amount: Self::Balance, + ) -> sp_runtime::DispatchResult { + if amount.is_zero() { + return Ok(()); + } + let mut freezes = Freezes::::get(asset.clone(), who); + if let Some(i) = freezes.iter_mut().find(|x| &x.id == id) { + i.amount = i.amount.max(amount); + } else { + freezes + .try_push(IdAmount { id: *id, amount }) + .map_err(|_| Error::::TooManyFreezes)?; + } + Self::update_freezes(asset, who, freezes.as_bounded_slice()) + } + + fn thaw(asset: Self::AssetId, id: &Self::Id, who: &T::AccountId) -> sp_runtime::DispatchResult { + let mut freezes = Freezes::::get(asset.clone(), who); + freezes.retain(|f| &f.id != id); + Self::update_freezes(asset, who, freezes.as_bounded_slice()) + } +} diff --git a/substrate/frame/assets-freezer/src/lib.rs b/substrate/frame/assets-freezer/src/lib.rs new file mode 100644 index 0000000000000000000000000000000000000000..b42d41ac1d9255c0046de37ddf5cf1222173be7f --- /dev/null +++ b/substrate/frame/assets-freezer/src/lib.rs @@ -0,0 +1,176 @@ +// 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. + +//! # Assets Freezer Pallet +//! +//! A pallet capable of freezing fungibles from `pallet-assets`. This is an extension of +//! `pallet-assets`, wrapping [`fungibles::Inspect`](`frame_support::traits::fungibles::Inspect`). +//! It implements both +//! [`fungibles::freeze::Inspect`](frame_support::traits::fungibles::freeze::Inspect) and +//! [`fungibles::freeze::Mutate`](frame_support::traits::fungibles::freeze::Mutate). The complexity +//! of the operations is `O(n)`. where `n` is the variant count of `RuntimeFreezeReason`. +//! +//! ## Pallet API +//! +//! See the [`pallet`] module for more information about the interfaces this pallet exposes, +//! including its configuration trait, dispatchables, storage items, events and errors. +//! +//! ## Overview +//! +//! This pallet provides the following functionality: +//! +//! - Pallet hooks allowing [`pallet-assets`] to know the frozen balance for an account on a given +//! asset (see [`pallet_assets::FrozenBalance`]). +//! - An implementation of +//! [`fungibles::freeze::Inspect`](frame_support::traits::fungibles::freeze::Inspect) and +//! [`fungibles::freeze::Mutate`](frame_support::traits::fungibles::freeze::Mutate), allowing +//! other pallets to manage freezes for the `pallet-assets` assets. + +#![cfg_attr(not(feature = "std"), no_std)] + +use frame_support::{ + pallet_prelude::*, + traits::{tokens::IdAmount, VariantCount, VariantCountOf}, + BoundedVec, +}; +use frame_system::pallet_prelude::BlockNumberFor; +use sp_runtime::{ + traits::{Saturating, Zero}, + BoundedSlice, +}; + +pub use pallet::*; + +#[cfg(test)] +mod mock; +#[cfg(test)] +mod tests; + +mod impls; + +#[frame_support::pallet] +pub mod pallet { + use super::*; + + #[pallet::config(with_default)] + pub trait Config: frame_system::Config + pallet_assets::Config { + /// The overarching freeze reason. + #[pallet::no_default_bounds] + type RuntimeFreezeReason: Parameter + Member + MaxEncodedLen + Copy + VariantCount; + + /// The overarching event type. + #[pallet::no_default_bounds] + type RuntimeEvent: From> + + IsType<::RuntimeEvent>; + } + + #[pallet::error] + pub enum Error { + /// Number of freezes on an account would exceed `MaxFreezes`. + TooManyFreezes, + } + + #[pallet::pallet] + pub struct Pallet(_); + + #[pallet::event] + #[pallet::generate_deposit(pub(super) fn deposit_event)] + pub enum Event, I: 'static = ()> { + // `who`s frozen balance was increased by `amount`. + Frozen { who: T::AccountId, asset_id: T::AssetId, amount: T::Balance }, + // `who`s frozen balance was decreased by `amount`. + Thawed { who: T::AccountId, asset_id: T::AssetId, amount: T::Balance }, + } + + /// A map that stores freezes applied on an account for a given AssetId. + #[pallet::storage] + pub(super) type Freezes, I: 'static = ()> = StorageDoubleMap< + _, + Blake2_128Concat, + T::AssetId, + Blake2_128Concat, + T::AccountId, + BoundedVec< + IdAmount, + VariantCountOf, + >, + ValueQuery, + >; + + /// A map that stores the current total frozen balance for every account on a given AssetId. + #[pallet::storage] + pub(super) type FrozenBalances, I: 'static = ()> = StorageDoubleMap< + _, + Blake2_128Concat, + T::AssetId, + Blake2_128Concat, + T::AccountId, + T::Balance, + >; + + #[pallet::hooks] + impl, I: 'static> Hooks> for Pallet { + #[cfg(feature = "try-runtime")] + fn try_state(_: BlockNumberFor) -> Result<(), sp_runtime::TryRuntimeError> { + Self::do_try_state() + } + } +} + +impl, I: 'static> Pallet { + fn update_freezes( + asset: T::AssetId, + who: &T::AccountId, + freezes: BoundedSlice< + IdAmount, + VariantCountOf, + >, + ) -> DispatchResult { + let prev_frozen = FrozenBalances::::get(asset.clone(), who).unwrap_or_default(); + let after_frozen = freezes.into_iter().map(|f| f.amount).max().unwrap_or_else(Zero::zero); + FrozenBalances::::set(asset.clone(), who, Some(after_frozen)); + if freezes.is_empty() { + Freezes::::remove(asset.clone(), who); + FrozenBalances::::remove(asset.clone(), who); + } else { + Freezes::::insert(asset.clone(), who, freezes); + } + if prev_frozen > after_frozen { + let amount = prev_frozen.saturating_sub(after_frozen); + Self::deposit_event(Event::Thawed { asset_id: asset, who: who.clone(), amount }); + } else if after_frozen > prev_frozen { + let amount = after_frozen.saturating_sub(prev_frozen); + Self::deposit_event(Event::Frozen { asset_id: asset, who: who.clone(), amount }); + } + Ok(()) + } + + #[cfg(any(test, feature = "try-runtime"))] + fn do_try_state() -> Result<(), sp_runtime::TryRuntimeError> { + for (asset, who, _) in FrozenBalances::::iter() { + let max_frozen_amount = + Freezes::::get(asset.clone(), who.clone()).iter().map(|l| l.amount).max(); + + frame_support::ensure!( + FrozenBalances::::get(asset, who) == max_frozen_amount, + "The `FrozenAmount` is not equal to the maximum amount in `Freezes` for (`asset`, `who`)" + ); + } + + Ok(()) + } +} diff --git a/substrate/frame/assets-freezer/src/mock.rs b/substrate/frame/assets-freezer/src/mock.rs new file mode 100644 index 0000000000000000000000000000000000000000..b4e8c857fba49cf5dd9b6fc194d9a06d596dcae3 --- /dev/null +++ b/substrate/frame/assets-freezer/src/mock.rs @@ -0,0 +1,154 @@ +// 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. + +//! Tests mock for `pallet-assets-freezer`. + +use crate as pallet_assets_freezer; +pub use crate::*; +use codec::{Compact, Decode, Encode, MaxEncodedLen}; +use frame_support::{ + derive_impl, + traits::{AsEnsureOriginWithArg, ConstU64}, +}; +use scale_info::TypeInfo; +use sp_core::{ConstU32, H256}; +use sp_runtime::{ + traits::{BlakeTwo256, IdentityLookup}, + BuildStorage, +}; + +pub type AccountId = u64; +pub type Balance = u64; +pub type AssetId = u32; +type Block = frame_system::mocking::MockBlock; + +frame_support::construct_runtime!( + pub enum Test + { + System: frame_system, + Assets: pallet_assets, + AssetsFreezer: pallet_assets_freezer, + Balances: pallet_balances, + } +); + +#[derive_impl(frame_system::config_preludes::TestDefaultConfig)] +impl frame_system::Config for Test { + type BaseCallFilter = frame_support::traits::Everything; + type BlockWeights = (); + type BlockLength = (); + type DbWeight = (); + type RuntimeOrigin = RuntimeOrigin; + type Nonce = u64; + type Hash = H256; + type RuntimeCall = RuntimeCall; + type Hashing = BlakeTwo256; + type AccountId = AccountId; + type Lookup = IdentityLookup; + type Block = Block; + type RuntimeEvent = RuntimeEvent; + type BlockHashCount = ConstU64<250>; + type Version = (); + type PalletInfo = PalletInfo; + type AccountData = pallet_balances::AccountData; + type OnNewAccount = (); + type OnKilledAccount = (); + type SystemWeightInfo = (); + type SS58Prefix = (); + type OnSetCode = (); + type MaxConsumers = frame_support::traits::ConstU32<16>; +} + +impl pallet_balances::Config for Test { + type MaxLocks = (); + type MaxReserves = (); + type ReserveIdentifier = [u8; 8]; + type Balance = Balance; + type DustRemoval = (); + type RuntimeEvent = RuntimeEvent; + type ExistentialDeposit = ConstU64<1>; + type AccountStore = System; + type WeightInfo = (); + type FreezeIdentifier = (); + type MaxFreezes = (); + type RuntimeHoldReason = (); + type RuntimeFreezeReason = (); +} + +impl pallet_assets::Config for Test { + type AssetId = AssetId; + type AssetIdParameter = Compact; + type AssetDeposit = ConstU64<1>; + type Balance = Balance; + type AssetAccountDeposit = ConstU64<1>; + type MetadataDepositBase = (); + type MetadataDepositPerByte = (); + type ApprovalDeposit = (); + type CreateOrigin = AsEnsureOriginWithArg>; + type ForceOrigin = frame_system::EnsureRoot; + type StringLimit = ConstU32<32>; + type Extra = (); + type RemoveItemsLimit = ConstU32<10>; + type CallbackHandle = (); + type Currency = Balances; + type Freezer = AssetsFreezer; + type RuntimeEvent = RuntimeEvent; + type WeightInfo = (); + #[cfg(feature = "runtime-benchmarks")] + type BenchmarkHelper = (); +} + +#[derive( + Decode, Encode, MaxEncodedLen, PartialEq, Eq, Ord, PartialOrd, TypeInfo, Debug, Clone, Copy, +)] +pub enum DummyFreezeReason { + Governance, + Staking, + Other, +} + +impl VariantCount for DummyFreezeReason { + // Intentionally set below the actual count of variants, to allow testing for `can_freeze` + const VARIANT_COUNT: u32 = 2; +} + +impl Config for Test { + type RuntimeFreezeReason = DummyFreezeReason; + type RuntimeEvent = RuntimeEvent; +} + +pub fn new_test_ext(execute: impl FnOnce()) -> sp_io::TestExternalities { + let t = RuntimeGenesisConfig { + assets: pallet_assets::GenesisConfig { + assets: vec![(1, 0, true, 1)], + metadata: vec![], + accounts: vec![(1, 1, 100)], + }, + system: Default::default(), + balances: Default::default(), + } + .build_storage() + .unwrap(); + let mut ext: sp_io::TestExternalities = t.into(); + ext.execute_with(|| { + System::set_block_number(1); + execute(); + frame_support::assert_ok!(AssetsFreezer::do_try_state()); + }); + + ext +} diff --git a/substrate/frame/assets-freezer/src/tests.rs b/substrate/frame/assets-freezer/src/tests.rs new file mode 100644 index 0000000000000000000000000000000000000000..4f2dea79c705a9ecacba4ec427f2f8553920f9a1 --- /dev/null +++ b/substrate/frame/assets-freezer/src/tests.rs @@ -0,0 +1,304 @@ +// 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. + +//! Tests for pallet-assets-freezer. + +use crate::mock::*; + +use codec::Compact; +use frame_support::{ + assert_ok, assert_storage_noop, + traits::{ + fungibles::{Inspect, InspectFreeze, MutateFreeze}, + tokens::{Fortitude, Preservation}, + }, +}; +use pallet_assets::FrozenBalance; + +const WHO: AccountId = 1; +const ASSET_ID: AssetId = 1; + +fn test_set_freeze(id: DummyFreezeReason, amount: Balance) { + let mut freezes = Freezes::::get(ASSET_ID, WHO); + + if let Some(i) = freezes.iter_mut().find(|l| l.id == id) { + i.amount = amount; + } else { + freezes + .try_push(IdAmount { id, amount }) + .expect("freeze is added without exceeding bounds; qed"); + } + + assert_ok!(AssetsFreezer::update_freezes(ASSET_ID, &WHO, freezes.as_bounded_slice())); +} + +fn test_thaw(id: DummyFreezeReason) { + let mut freezes = Freezes::::get(ASSET_ID, WHO); + freezes.retain(|l| l.id != id); + + assert_ok!(AssetsFreezer::update_freezes(ASSET_ID, &WHO, freezes.as_bounded_slice())); +} + +mod impl_frozen_balance { + use super::*; + + #[test] + fn frozen_balance_works() { + new_test_ext(|| { + assert_eq!(AssetsFreezer::frozen_balance(ASSET_ID, &WHO), None); + test_set_freeze(DummyFreezeReason::Governance, 1); + assert_eq!(AssetsFreezer::frozen_balance(ASSET_ID, &WHO), Some(1u64)); + test_set_freeze(DummyFreezeReason::Staking, 3); + assert_eq!(AssetsFreezer::frozen_balance(ASSET_ID, &WHO), Some(3u64)); + test_set_freeze(DummyFreezeReason::Governance, 2); + assert_eq!(AssetsFreezer::frozen_balance(ASSET_ID, &WHO), Some(3u64)); + // also test thawing works to reduce a balance, and finally thawing everything resets to + // None + test_thaw(DummyFreezeReason::Governance); + assert_eq!(AssetsFreezer::frozen_balance(ASSET_ID, &WHO), Some(3u64)); + test_thaw(DummyFreezeReason::Staking); + assert_eq!(AssetsFreezer::frozen_balance(ASSET_ID, &WHO), None); + }); + } + + #[test] + fn died_works() { + new_test_ext(|| { + test_set_freeze(DummyFreezeReason::Governance, 1); + AssetsFreezer::died(ASSET_ID, &WHO); + assert!(FrozenBalances::::get(ASSET_ID, WHO).is_none()); + assert!(Freezes::::get(ASSET_ID, WHO).is_empty()); + }); + } +} + +mod impl_inspect_freeze { + use super::*; + + #[test] + fn balance_frozen_works() { + new_test_ext(|| { + assert_eq!( + AssetsFreezer::balance_frozen(ASSET_ID, &DummyFreezeReason::Governance, &WHO), + 0u64 + ); + test_set_freeze(DummyFreezeReason::Governance, 1); + assert_eq!( + AssetsFreezer::balance_frozen(ASSET_ID, &DummyFreezeReason::Governance, &WHO), + 1u64 + ); + test_set_freeze(DummyFreezeReason::Staking, 3); + assert_eq!( + AssetsFreezer::balance_frozen(ASSET_ID, &DummyFreezeReason::Staking, &WHO), + 3u64 + ); + test_set_freeze(DummyFreezeReason::Staking, 2); + assert_eq!( + AssetsFreezer::balance_frozen(ASSET_ID, &DummyFreezeReason::Staking, &WHO), + 2u64 + ); + // also test thawing works to reduce a balance, and finally thawing everything resets to + // 0 + test_thaw(DummyFreezeReason::Governance); + assert_eq!( + AssetsFreezer::balance_frozen(ASSET_ID, &DummyFreezeReason::Governance, &WHO), + 0u64 + ); + test_thaw(DummyFreezeReason::Staking); + assert_eq!( + AssetsFreezer::balance_frozen(ASSET_ID, &DummyFreezeReason::Staking, &WHO), + 0u64 + ); + }); + } + + /// This tests it's not possible to freeze once the freezes [`BoundedVec`] is full. This is, + /// the lenght of the vec is equal to [`Config::MaxFreezes`]. + /// This test assumes a mock configuration where this parameter is set to `2`. + #[test] + fn can_freeze_works() { + new_test_ext(|| { + test_set_freeze(DummyFreezeReason::Governance, 1); + assert!(AssetsFreezer::can_freeze(ASSET_ID, &DummyFreezeReason::Staking, &WHO)); + test_set_freeze(DummyFreezeReason::Staking, 1); + assert!(!AssetsFreezer::can_freeze(ASSET_ID, &DummyFreezeReason::Other, &WHO)); + }); + } +} + +mod impl_mutate_freeze { + use super::*; + + #[test] + fn set_freeze_works() { + new_test_ext(|| { + assert_eq!( + Assets::reducible_balance( + ASSET_ID, + &WHO, + Preservation::Preserve, + Fortitude::Polite, + ), + 99 + ); + assert_ok!(AssetsFreezer::set_freeze( + ASSET_ID, + &DummyFreezeReason::Governance, + &WHO, + 10 + )); + assert_eq!( + Assets::reducible_balance( + ASSET_ID, + &WHO, + Preservation::Preserve, + Fortitude::Polite, + ), + 89 + ); + System::assert_last_event( + Event::::Frozen { asset_id: ASSET_ID, who: WHO, amount: 10 }.into(), + ); + assert_ok!(AssetsFreezer::set_freeze( + ASSET_ID, + &DummyFreezeReason::Governance, + &WHO, + 8 + )); + assert_eq!( + Assets::reducible_balance( + ASSET_ID, + &WHO, + Preservation::Preserve, + Fortitude::Polite, + ), + 91 + ); + System::assert_last_event( + Event::::Thawed { asset_id: ASSET_ID, who: WHO, amount: 2 }.into(), + ); + }); + } + + #[test] + fn extend_freeze_works() { + new_test_ext(|| { + assert_ok!(AssetsFreezer::set_freeze( + ASSET_ID, + &DummyFreezeReason::Governance, + &WHO, + 10 + )); + assert_storage_noop!(assert_ok!(AssetsFreezer::extend_freeze( + ASSET_ID, + &DummyFreezeReason::Governance, + &WHO, + 8 + ))); + System::assert_last_event( + Event::::Frozen { asset_id: ASSET_ID, who: WHO, amount: 10 }.into(), + ); + assert_eq!( + Assets::reducible_balance( + ASSET_ID, + &WHO, + Preservation::Preserve, + Fortitude::Polite, + ), + 89 + ); + assert_ok!(AssetsFreezer::extend_freeze( + ASSET_ID, + &DummyFreezeReason::Governance, + &WHO, + 11 + )); + System::assert_last_event( + Event::::Frozen { asset_id: ASSET_ID, who: WHO, amount: 1 }.into(), + ); + assert_eq!( + Assets::reducible_balance( + ASSET_ID, + &WHO, + Preservation::Preserve, + Fortitude::Polite, + ), + 88 + ); + }); + } + + #[test] + fn thaw_works() { + new_test_ext(|| { + assert_ok!(AssetsFreezer::set_freeze( + ASSET_ID, + &DummyFreezeReason::Governance, + &WHO, + 10 + )); + System::assert_has_event( + Event::::Frozen { asset_id: ASSET_ID, who: WHO, amount: 10 }.into(), + ); + assert_eq!( + Assets::reducible_balance( + ASSET_ID, + &WHO, + Preservation::Preserve, + Fortitude::Polite, + ), + 89 + ); + assert_ok!(AssetsFreezer::thaw(ASSET_ID, &DummyFreezeReason::Governance, &WHO)); + System::assert_has_event( + Event::::Thawed { asset_id: ASSET_ID, who: WHO, amount: 10 }.into(), + ); + assert_eq!( + Assets::reducible_balance( + ASSET_ID, + &WHO, + Preservation::Preserve, + Fortitude::Polite, + ), + 99 + ); + }); + } +} + +mod with_pallet_assets { + use frame_support::assert_noop; + + use super::*; + + #[test] + fn frozen_balance_affects_balance_transferring() { + new_test_ext(|| { + assert_ok!(AssetsFreezer::set_freeze( + ASSET_ID, + &DummyFreezeReason::Governance, + &WHO, + 20 + )); + assert_noop!( + Assets::transfer(RuntimeOrigin::signed(WHO), Compact(ASSET_ID), 2, 80), + pallet_assets::Error::::BalanceLow, + ); + assert_ok!(Assets::transfer(RuntimeOrigin::signed(WHO), Compact(ASSET_ID), 2, 79)); + }); + } +} diff --git a/substrate/frame/assets/Cargo.toml b/substrate/frame/assets/Cargo.toml index 9647ae4db6baa6ada63350153b8a10993e940401..412524f0b351c7c92a1a98491388962e344f6a5a 100644 --- a/substrate/frame/assets/Cargo.toml +++ b/substrate/frame/assets/Cargo.toml @@ -16,23 +16,23 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } +codec = { workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -sp-std = { path = "../../primitives/std", default-features = false } +scale-info = { features = ["derive"], workspace = true } +sp-std = { workspace = true } # Needed for various traits. In our case, `OnFinalize`. -sp-runtime = { path = "../../primitives/runtime", default-features = false } +sp-runtime = { workspace = true } # Needed for type-safe access to storage DB. -frame-support = { path = "../support", default-features = false } +frame-support = { workspace = true } # `system` module provides us with all sorts of useful stuff and macros depend on it being around. -frame-system = { path = "../system", default-features = false } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -sp-core = { path = "../../primitives/core", default-features = false } +frame-system = { workspace = true } +frame-benchmarking = { optional = true, workspace = true } +sp-core = { workspace = true } [dev-dependencies] -sp-std = { path = "../../primitives/std" } -sp-io = { path = "../../primitives/io" } -pallet-balances = { path = "../balances" } +sp-std = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/assets/src/mock.rs b/substrate/frame/assets/src/mock.rs index f6173a451fffaee41f66dc6f697a40cd68e3648b..694ef234dffb4e3e9ec79560f351b1462fa0afc0 100644 --- a/substrate/frame/assets/src/mock.rs +++ b/substrate/frame/assets/src/mock.rs @@ -23,7 +23,7 @@ use crate as pallet_assets; use codec::Encode; use frame_support::{ construct_runtime, derive_impl, parameter_types, - traits::{AsEnsureOriginWithArg, ConstU32, ConstU64}, + traits::{AsEnsureOriginWithArg, ConstU32}, }; use sp_io::storage; use sp_runtime::BuildStorage; @@ -49,20 +49,9 @@ impl frame_system::Config for Test { type MaxConsumers = ConstU32<3>; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type Balance = u64; - type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; - type ExistentialDeposit = ConstU64<1>; type AccountStore = System; - type WeightInfo = (); - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); - type FreezeIdentifier = (); - type MaxFreezes = (); } pub struct AssetsCallbackHandle; diff --git a/substrate/frame/atomic-swap/Cargo.toml b/substrate/frame/atomic-swap/Cargo.toml index 8083c12d4b39fb0b860a738f700168bcad0bc2f3..7e2f5fc74ab22cebf835c1924478067f8a2abc3b 100644 --- a/substrate/frame/atomic-swap/Cargo.toml +++ b/substrate/frame/atomic-swap/Cargo.toml @@ -16,17 +16,17 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +codec = { workspace = true } +scale-info = { features = ["derive"], workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-core = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -pallet-balances = { path = "../balances" } +pallet-balances = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/atomic-swap/src/tests.rs b/substrate/frame/atomic-swap/src/tests.rs index 9f51f04208aaccca281398b0382718f2165d8a0e..47ebe6a8f0acf26021a84f37bf76d703aeba1374 100644 --- a/substrate/frame/atomic-swap/src/tests.rs +++ b/substrate/frame/atomic-swap/src/tests.rs @@ -20,10 +20,7 @@ use super::*; use crate as pallet_atomic_swap; -use frame_support::{ - derive_impl, - traits::{ConstU32, ConstU64}, -}; +use frame_support::{derive_impl, traits::ConstU32}; use sp_runtime::BuildStorage; type Block = frame_system::mocking::MockBlock; @@ -43,20 +40,9 @@ impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type Balance = u64; - type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; - type ExistentialDeposit = ConstU64<1>; type AccountStore = System; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } impl Config for Test { diff --git a/substrate/frame/aura/Cargo.toml b/substrate/frame/aura/Cargo.toml index 9264d2f4a643cdedd02fa17f81f90d949c2c0729..97582e7d2e9dbf110a1c22b5de6ad5e592acb980 100644 --- a/substrate/frame/aura/Cargo.toml +++ b/substrate/frame/aura/Cargo.toml @@ -16,20 +16,20 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive", "max-encoded-len"] } +codec = { features = ["derive", "max-encoded-len"], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -pallet-timestamp = { path = "../timestamp", default-features = false } -sp-application-crypto = { path = "../../primitives/application-crypto", default-features = false } -sp-consensus-aura = { path = "../../primitives/consensus/aura", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +scale-info = { features = ["derive"], workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +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 = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io" } +sp-core = { workspace = true } +sp-io = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/authority-discovery/Cargo.toml b/substrate/frame/authority-discovery/Cargo.toml index c21f9b5c904556f8a0c01a0e5f1e468e32685ee5..79057d94107be2485c6bfb48ec9a20373b83e143 100644 --- a/substrate/frame/authority-discovery/Cargo.toml +++ b/substrate/frame/authority-discovery/Cargo.toml @@ -16,23 +16,23 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", -] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -pallet-session = { path = "../session", default-features = false, features = [ +], workspace = true } +scale-info = { features = ["derive"], workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-session = { features = [ "historical", -] } -sp-application-crypto = { path = "../../primitives/application-crypto", default-features = false } -sp-authority-discovery = { path = "../../primitives/authority-discovery", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +], workspace = true } +sp-application-crypto = { workspace = true } +sp-authority-discovery = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -sp-core = { path = "../../primitives/core" } -sp-io = { path = "../../primitives/io" } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/authorship/Cargo.toml b/substrate/frame/authorship/Cargo.toml index dd78e3404ef0b3c30adfa5b24bd4444c2fec10d1..58292c0eba393d482740a7cd59a748b17658f8c4 100644 --- a/substrate/frame/authorship/Cargo.toml +++ b/substrate/frame/authorship/Cargo.toml @@ -16,19 +16,19 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", -] } -impl-trait-for-tuples = "0.2.2" -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +], workspace = true } +impl-trait-for-tuples = { workspace = true } +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 = { path = "../../primitives/core" } -sp-io = { path = "../../primitives/io" } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/babe/Cargo.toml b/substrate/frame/babe/Cargo.toml index d06b7f7454648ea529595aa91e1e3a0f9e2b5486..68638798e796a0a0cf67fd428216fb5b8114e95d 100644 --- a/substrate/frame/babe/Cargo.toml +++ b/substrate/frame/babe/Cargo.toml @@ -16,31 +16,31 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive", "serde"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -pallet-authorship = { path = "../authorship", default-features = false } -pallet-session = { path = "../session", default-features = false } -pallet-timestamp = { path = "../timestamp", default-features = false } -sp-application-crypto = { path = "../../primitives/application-crypto", default-features = false, features = ["serde"] } -sp-consensus-babe = { path = "../../primitives/consensus/babe", default-features = false, features = ["serde"] } -sp-core = { path = "../../primitives/core", default-features = false, features = ["serde"] } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false, features = ["serde"] } -sp-session = { path = "../../primitives/session", default-features = false } -sp-staking = { path = "../../primitives/staking", default-features = false, features = ["serde"] } -sp-std = { path = "../../primitives/std", default-features = false } +scale-info = { features = ["derive", "serde"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-authorship = { workspace = true } +pallet-session = { workspace = true } +pallet-timestamp = { workspace = true } +sp-application-crypto = { features = ["serde"], workspace = true } +sp-consensus-babe = { features = ["serde"], workspace = true } +sp-core = { features = ["serde"], workspace = true } +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 = { path = "../election-provider-support" } -pallet-balances = { path = "../balances" } -pallet-offences = { path = "../offences" } -pallet-staking = { path = "../staking" } -pallet-staking-reward-curve = { path = "../staking/reward-curve" } -sp-core = { path = "../../primitives/core" } +frame-election-provider-support = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +pallet-offences = { workspace = true, default-features = true } +pallet-staking = { workspace = true, default-features = true } +pallet-staking-reward-curve = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/babe/src/mock.rs b/substrate/frame/babe/src/mock.rs index 395a86e6528807ff21ee2667d1446016b6826a1e..be38e3e7e5db5c0438688c584a81cc7ad3dc1913 100644 --- a/substrate/frame/babe/src/mock.rs +++ b/substrate/frame/babe/src/mock.rs @@ -28,7 +28,6 @@ use frame_support::{ traits::{ConstU128, ConstU32, ConstU64, KeyOwnerProofSystem, OnInitialize}, }; use pallet_session::historical as pallet_session_historical; -use pallet_staking::FixedNominationsQuota; use sp_consensus_babe::{AuthorityId, AuthorityPair, Randomness, Slot, VrfSignature}; use sp_core::{ crypto::{KeyTypeId, Pair, VrfSecret}, @@ -112,20 +111,11 @@ impl pallet_timestamp::Config for Test { type WeightInfo = (); } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; type Balance = u128; - type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; type ExistentialDeposit = ConstU128<1>; type AccountStore = System; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } pallet_staking_reward_curve::build! { @@ -142,7 +132,6 @@ pallet_staking_reward_curve::build! { parameter_types! { pub const SessionsPerEra: SessionIndex = 3; pub const BondingDuration: EraIndex = 3; - pub const SlashDeferDuration: EraIndex = 0; pub const RewardCurve: &'static PiecewiseLinear<'static> = &REWARD_CURVE; pub static ElectionsBounds: ElectionBounds = ElectionBoundsBuilder::default().build(); } @@ -157,35 +146,20 @@ impl onchain::Config for OnChainSeqPhragmen { type Bounds = ElectionsBounds; } +#[derive_impl(pallet_staking::config_preludes::TestDefaultConfig)] impl pallet_staking::Config for Test { - type RewardRemainder = (); - type CurrencyToVote = (); - type RuntimeEvent = RuntimeEvent; type Currency = Balances; - type CurrencyBalance = ::Balance; - type Slash = (); - type Reward = (); type SessionsPerEra = SessionsPerEra; type BondingDuration = BondingDuration; - type SlashDeferDuration = SlashDeferDuration; type AdminOrigin = frame_system::EnsureRoot; type SessionInterface = Self; type UnixTime = pallet_timestamp::Pallet; type EraPayout = pallet_staking::ConvertCurve; - type MaxExposurePageSize = ConstU32<64>; type NextNewSession = Session; type ElectionProvider = onchain::OnChainExecution; type GenesisElectionProvider = Self::ElectionProvider; type VoterList = pallet_staking::UseNominatorsAndValidatorsMap; type TargetList = pallet_staking::UseValidatorsMap; - type NominationsQuota = FixedNominationsQuota<16>; - type MaxUnlockingChunks = ConstU32<32>; - type MaxControllersInDeprecationBatch = ConstU32<100>; - type HistoryDepth = ConstU32<84>; - type EventListeners = (); - type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; - type WeightInfo = (); - type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; } impl pallet_offences::Config for Test { diff --git a/substrate/frame/bags-list/Cargo.toml b/substrate/frame/bags-list/Cargo.toml index 3429d2f28a6cc7445e383a28e5f817b876251f2b..bf57bd2af53cef42fda4c963b327f52aa08edb89 100644 --- a/substrate/frame/bags-list/Cargo.toml +++ b/substrate/frame/bags-list/Cargo.toml @@ -16,41 +16,41 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] # parity -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", -] } -scale-info = { version = "2.11.1", default-features = false, features = [ +], workspace = true } +scale-info = { features = [ "derive", -] } +], workspace = true } # primitives -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +sp-runtime = { workspace = true } +sp-std = { workspace = true } # FRAME -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -frame-election-provider-support = { path = "../election-provider-support", default-features = false } +frame-support = { workspace = true } +frame-system = { workspace = true } +frame-election-provider-support = { workspace = true } # third party log = { workspace = true } -docify = "0.2.8" -aquamarine = { version = "0.5.0" } +docify = { workspace = true } +aquamarine = { workspace = true } # Optional imports for benchmarking -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -pallet-balances = { path = "../balances", default-features = false, optional = true } -sp-core = { path = "../../primitives/core", default-features = false, optional = true } -sp-io = { path = "../../primitives/io", default-features = false, optional = true } -sp-tracing = { path = "../../primitives/tracing", default-features = false, optional = true } +frame-benchmarking = { optional = true, workspace = true } +pallet-balances = { optional = true, workspace = true } +sp-core = { optional = true, workspace = true } +sp-io = { optional = true, workspace = true } +sp-tracing = { optional = true, workspace = true } [dev-dependencies] -sp-core = { path = "../../primitives/core" } -sp-io = { path = "../../primitives/io" } -sp-tracing = { path = "../../primitives/tracing" } -pallet-balances = { path = "../balances" } -frame-election-provider-support = { path = "../election-provider-support" } -frame-benchmarking = { path = "../benchmarking" } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +frame-election-provider-support = { workspace = true, default-features = true } +frame-benchmarking = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/bags-list/fuzzer/Cargo.toml b/substrate/frame/bags-list/fuzzer/Cargo.toml index 20760141b23612bee46b8a79ce40874dfdef8a7b..f8631be159cd42a80a9ea49eb3de0a953cf843bb 100644 --- a/substrate/frame/bags-list/fuzzer/Cargo.toml +++ b/substrate/frame/bags-list/fuzzer/Cargo.toml @@ -13,10 +13,10 @@ publish = false workspace = true [dependencies] -honggfuzz = "0.5" -rand = { version = "0.8", features = ["small_rng", "std"] } -frame-election-provider-support = { path = "../../election-provider-support", features = ["fuzz"] } -pallet-bags-list = { path = "..", features = ["fuzz"] } +honggfuzz = { workspace = true } +rand = { features = ["small_rng", "std"], workspace = true, default-features = true } +frame-election-provider-support = { features = ["fuzz"], workspace = true, default-features = true } +pallet-bags-list = { features = ["fuzz"], workspace = true, default-features = true } [[bin]] name = "bags-list" diff --git a/substrate/frame/bags-list/remote-tests/Cargo.toml b/substrate/frame/bags-list/remote-tests/Cargo.toml index 266355f5cabe19214643db024e641339acd60630..45f2498aa88b4f6b6f4b4b83fa7b3e7eb5275d13 100644 --- a/substrate/frame/bags-list/remote-tests/Cargo.toml +++ b/substrate/frame/bags-list/remote-tests/Cargo.toml @@ -17,21 +17,21 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] # frame -pallet-staking = { path = "../../staking" } -pallet-bags-list = { path = "..", features = ["fuzz"] } -frame-election-provider-support = { path = "../../election-provider-support" } -frame-system = { path = "../../system" } -frame-support = { path = "../../support" } +pallet-staking = { workspace = true, default-features = true } +pallet-bags-list = { features = ["fuzz"], workspace = true, default-features = true } +frame-election-provider-support = { workspace = true, default-features = true } +frame-system = { workspace = true, default-features = true } +frame-support = { workspace = true, default-features = true } # core -sp-storage = { path = "../../../primitives/storage" } -sp-core = { path = "../../../primitives/core" } -sp-tracing = { path = "../../../primitives/tracing" } -sp-runtime = { path = "../../../primitives/runtime" } -sp-std = { path = "../../../primitives/std" } +sp-storage = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-std = { workspace = true, default-features = true } # utils -remote-externalities = { package = "frame-remote-externalities", path = "../../../utils/frame/remote-externalities" } +remote-externalities = { workspace = true, default-features = true } # others log = { workspace = true, default-features = true } diff --git a/substrate/frame/balances/Cargo.toml b/substrate/frame/balances/Cargo.toml index 4da14aea12809f09c797d0eb0925e1c43bfdc8d6..5fa8fa84bf59e2401fba74f17f9c838f6cf3775a 100644 --- a/substrate/frame/balances/Cargo.toml +++ b/substrate/frame/balances/Cargo.toml @@ -16,22 +16,22 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive", "max-encoded-len"] } +codec = { features = ["derive", "max-encoded-len"], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -docify = "0.2.8" +scale-info = { features = ["derive"], workspace = true } +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] -pallet-transaction-payment = { path = "../transaction-payment" } -frame-support = { path = "../support", features = ["experimental"] } -sp-core = { path = "../../primitives/core" } -sp-io = { path = "../../primitives/io" } -paste = "1.0.12" +pallet-transaction-payment = { workspace = true, default-features = true } +frame-support = { features = ["experimental"], workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +paste = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/balances/src/lib.rs b/substrate/frame/balances/src/lib.rs index 56eb81b49e2db695abbb8d705db7cef21f599416..d01884293c0902ea66636877d1b3d65fbd74f5a1 100644 --- a/substrate/frame/balances/src/lib.rs +++ b/substrate/frame/balances/src/lib.rs @@ -158,6 +158,7 @@ use frame_support::{ tokens::{ fungible, BalanceStatus as Status, DepositConsequence, Fortitude::{self, Force, Polite}, + IdAmount, Preservation::{Expendable, Preserve, Protect}, WithdrawConsequence, }, @@ -177,8 +178,7 @@ use sp_runtime::{ }; use sp_std::{cmp, fmt::Debug, mem, prelude::*, result}; pub use types::{ - AccountData, AdjustmentDirection, BalanceLock, DustCleaner, ExtraFlags, IdAmount, Reasons, - ReserveData, + AccountData, AdjustmentDirection, BalanceLock, DustCleaner, ExtraFlags, Reasons, ReserveData, }; pub use weights::WeightInfo; @@ -222,13 +222,13 @@ pub mod pallet { type ExistentialDeposit = ConstU64<1>; type ReserveIdentifier = (); - type FreezeIdentifier = (); + type FreezeIdentifier = Self::RuntimeFreezeReason; type DustRemoval = (); type MaxLocks = ConstU32<100>; type MaxReserves = ConstU32<100>; - type MaxFreezes = ConstU32<100>; + type MaxFreezes = VariantCountOf; type WeightInfo = (); } diff --git a/substrate/frame/balances/src/tests/dispatchable_tests.rs b/substrate/frame/balances/src/tests/dispatchable_tests.rs index 4bc96f6b43d97444252f42e4820d97168ed50e1e..ebc9f1b1a3695cb446e64018acc2bca772169b29 100644 --- a/substrate/frame/balances/src/tests/dispatchable_tests.rs +++ b/substrate/frame/balances/src/tests/dispatchable_tests.rs @@ -281,7 +281,7 @@ fn force_adjust_total_issuance_saturates() { ExtBuilder::default().build_and_execute_with(|| { assert_ok!(Balances::force_set_balance(RuntimeOrigin::root(), 1337, 64)); let ti = Balances::total_issuance(); - let max = Balance::max_value(); + let max = ::Balance::max_value(); assert_eq!(ti, 64); // Increment saturates: diff --git a/substrate/frame/balances/src/tests/fungible_tests.rs b/substrate/frame/balances/src/tests/fungible_tests.rs index 52fbe10bedec0f7131fe35fa7e6f809968741d42..1a09303a6590d54b3bb94ffb1d870d5c1e687b24 100644 --- a/substrate/frame/balances/src/tests/fungible_tests.rs +++ b/substrate/frame/balances/src/tests/fungible_tests.rs @@ -18,13 +18,20 @@ //! Tests regarding the functionality of the `fungible` trait set implementations. use super::*; -use frame_support::traits::tokens::{ - Fortitude::{Force, Polite}, - Precision::{BestEffort, Exact}, - Preservation::{Expendable, Preserve, Protect}, - Restriction::Free, +use frame_support::traits::{ + tokens::{ + Fortitude::{Force, Polite}, + Precision::{BestEffort, Exact}, + Preservation::{Expendable, Preserve, Protect}, + Restriction::Free, + }, + Consideration, Footprint, LinearStoragePrice, }; -use fungible::{Inspect, InspectFreeze, InspectHold, Mutate, MutateFreeze, MutateHold, Unbalanced}; +use fungible::{ + FreezeConsideration, HoldConsideration, Inspect, InspectFreeze, InspectHold, + LoneFreezeConsideration, LoneHoldConsideration, Mutate, MutateFreeze, MutateHold, Unbalanced, +}; +use sp_core::ConstU64; #[test] fn inspect_trait_reducible_balance_basic_works() { @@ -493,3 +500,161 @@ fn withdraw_precision_exact_works() { ); }); } + +#[test] +fn freeze_consideration_works() { + ExtBuilder::default() + .existential_deposit(1) + .monied(true) + .build_and_execute_with(|| { + type Consideration = FreezeConsideration< + u64, + Balances, + FooReason, + LinearStoragePrice, ConstU64<1>, u64>, + Footprint, + >; + + let who = 4; + // freeze amount taken somewhere outside of our (Consideration) scope. + let extend_freeze = 15; + assert_eq!(Balances::balance_frozen(&TestId::Foo, &who), 0); + + let ticket = Consideration::new(&who, Footprint::from_parts(10, 1)).unwrap().unwrap(); + assert_eq!(Balances::balance_frozen(&TestId::Foo, &who), 10); + + let ticket = ticket.update(&who, Footprint::from_parts(4, 1)).unwrap().unwrap(); + assert_eq!(Balances::balance_frozen(&TestId::Foo, &who), 4); + + assert_ok!(Balances::increase_frozen(&TestId::Foo, &who, extend_freeze)); + assert_eq!(Balances::balance_frozen(&TestId::Foo, &who), 4 + extend_freeze); + + let ticket = ticket.update(&who, Footprint::from_parts(8, 1)).unwrap().unwrap(); + assert_eq!(Balances::balance_frozen(&TestId::Foo, &who), 8 + extend_freeze); + + assert_eq!(ticket.update(&who, Footprint::from_parts(0, 0)).unwrap(), None); + assert_eq!(Balances::balance_frozen(&TestId::Foo, &who), 0 + extend_freeze); + + let ticket = Consideration::new(&who, Footprint::from_parts(10, 1)).unwrap().unwrap(); + assert_eq!(Balances::balance_frozen(&TestId::Foo, &who), 10 + extend_freeze); + + let _ = ticket.drop(&who).unwrap(); + assert_eq!(Balances::balance_frozen(&TestId::Foo, &who), 0 + extend_freeze); + }); +} + +#[test] +fn hold_consideration_works() { + ExtBuilder::default() + .existential_deposit(1) + .monied(true) + .build_and_execute_with(|| { + type Consideration = HoldConsideration< + u64, + Balances, + FooReason, + LinearStoragePrice, ConstU64<1>, u64>, + Footprint, + >; + + let who = 4; + // hold amount taken somewhere outside of our (Consideration) scope. + let extend_hold = 15; + assert_eq!(Balances::balance_on_hold(&TestId::Foo, &who), 0); + + let ticket = Consideration::new(&who, Footprint::from_parts(10, 1)).unwrap().unwrap(); + assert_eq!(Balances::balance_on_hold(&TestId::Foo, &who), 10); + + let ticket = ticket.update(&who, Footprint::from_parts(4, 1)).unwrap().unwrap(); + assert_eq!(Balances::balance_on_hold(&TestId::Foo, &who), 4); + + assert_ok!(Balances::hold(&TestId::Foo, &who, extend_hold)); + assert_eq!(Balances::balance_on_hold(&TestId::Foo, &who), 4 + extend_hold); + + let ticket = ticket.update(&who, Footprint::from_parts(8, 1)).unwrap().unwrap(); + assert_eq!(Balances::balance_on_hold(&TestId::Foo, &who), 8 + extend_hold); + + assert_eq!(ticket.update(&who, Footprint::from_parts(0, 0)).unwrap(), None); + assert_eq!(Balances::balance_on_hold(&TestId::Foo, &who), 0 + extend_hold); + + let ticket = Consideration::new(&who, Footprint::from_parts(10, 1)).unwrap().unwrap(); + assert_eq!(Balances::balance_on_hold(&TestId::Foo, &who), 10 + extend_hold); + + let _ = ticket.drop(&who).unwrap(); + assert_eq!(Balances::balance_on_hold(&TestId::Foo, &who), 0 + extend_hold); + }); +} + +#[test] +fn lone_freeze_consideration_works() { + ExtBuilder::default() + .existential_deposit(1) + .monied(true) + .build_and_execute_with(|| { + type Consideration = LoneFreezeConsideration< + u64, + Balances, + FooReason, + LinearStoragePrice, ConstU64<1>, u64>, + Footprint, + >; + + let who = 4; + assert_eq!(Balances::balance_frozen(&TestId::Foo, &who), 0); + + let ticket = Consideration::new(&who, Footprint::from_parts(10, 1)).unwrap().unwrap(); + assert_eq!(Balances::balance_frozen(&TestId::Foo, &who), 10); + + assert_ok!(Balances::increase_frozen(&TestId::Foo, &who, 5)); + assert_eq!(Balances::balance_frozen(&TestId::Foo, &who), 15); + + let ticket = ticket.update(&who, Footprint::from_parts(4, 1)).unwrap().unwrap(); + assert_eq!(Balances::balance_frozen(&TestId::Foo, &who), 4); + + assert_eq!(ticket.update(&who, Footprint::from_parts(0, 0)).unwrap(), None); + assert_eq!(Balances::balance_frozen(&TestId::Foo, &who), 0); + + let ticket = Consideration::new(&who, Footprint::from_parts(10, 1)).unwrap().unwrap(); + assert_eq!(Balances::balance_frozen(&TestId::Foo, &who), 10); + + let _ = ticket.drop(&who).unwrap(); + assert_eq!(Balances::balance_frozen(&TestId::Foo, &who), 0); + }); +} + +#[test] +fn lone_hold_consideration_works() { + ExtBuilder::default() + .existential_deposit(1) + .monied(true) + .build_and_execute_with(|| { + type Consideration = LoneHoldConsideration< + u64, + Balances, + FooReason, + LinearStoragePrice, ConstU64<1>, u64>, + Footprint, + >; + + let who = 4; + assert_eq!(Balances::balance_on_hold(&TestId::Foo, &who), 0); + + let ticket = Consideration::new(&who, Footprint::from_parts(10, 1)).unwrap().unwrap(); + assert_eq!(Balances::balance_on_hold(&TestId::Foo, &who), 10); + + assert_ok!(Balances::hold(&TestId::Foo, &who, 5)); + assert_eq!(Balances::balance_on_hold(&TestId::Foo, &who), 15); + + let ticket = ticket.update(&who, Footprint::from_parts(4, 1)).unwrap().unwrap(); + assert_eq!(Balances::balance_on_hold(&TestId::Foo, &who), 4); + + assert_eq!(ticket.update(&who, Footprint::from_parts(0, 0)).unwrap(), None); + assert_eq!(Balances::balance_on_hold(&TestId::Foo, &who), 0); + + let ticket = Consideration::new(&who, Footprint::from_parts(10, 1)).unwrap().unwrap(); + assert_eq!(Balances::balance_on_hold(&TestId::Foo, &who), 10); + + let _ = ticket.drop(&who).unwrap(); + assert_eq!(Balances::balance_on_hold(&TestId::Foo, &who), 0); + }); +} diff --git a/substrate/frame/balances/src/tests/mod.rs b/substrate/frame/balances/src/tests/mod.rs index 0abf2251290fee6881f0346aaab7df37ff2f0efb..ba0cdabdabbbdc8459fcb551ae3a1b704d479262 100644 --- a/substrate/frame/balances/src/tests/mod.rs +++ b/substrate/frame/balances/src/tests/mod.rs @@ -27,7 +27,7 @@ use frame_support::{ parameter_types, traits::{ fungible, ConstU32, ConstU8, Imbalance as ImbalanceT, OnUnbalanced, StorageMapShim, - StoredMap, VariantCount, WhitelistedStorageKeys, + StoredMap, VariantCount, VariantCountOf, WhitelistedStorageKeys, }, weights::{IdentityFee, Weight}, }; @@ -107,22 +107,21 @@ impl pallet_transaction_payment::Config for Test { type FeeMultiplierUpdate = (); } -pub(crate) type Balance = u64; +parameter_types! { + pub FooReason: TestId = TestId::Foo; +} +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl Config for Test { - type Balance = Balance; type DustRemoval = DustTrap; - type RuntimeEvent = RuntimeEvent; type ExistentialDeposit = ExistentialDeposit; type AccountStore = TestAccountStore; - type MaxLocks = ConstU32<50>; type MaxReserves = ConstU32<2>; type ReserveIdentifier = TestId; - type WeightInfo = (); type RuntimeHoldReason = TestId; - type RuntimeFreezeReason = RuntimeFreezeReason; + type RuntimeFreezeReason = TestId; type FreezeIdentifier = TestId; - type MaxFreezes = ConstU32<2>; + type MaxFreezes = VariantCountOf; } #[derive(Clone)] diff --git a/substrate/frame/balances/src/types.rs b/substrate/frame/balances/src/types.rs index 3e36a83575c892812d687e5882784b023754fe44..917b7507d7c941156a080163bf029f468c75b097 100644 --- a/substrate/frame/balances/src/types.rs +++ b/substrate/frame/balances/src/types.rs @@ -78,15 +78,6 @@ pub struct ReserveData { pub amount: Balance, } -/// An identifier and balance. -#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, MaxEncodedLen, TypeInfo)] -pub struct IdAmount { - /// An identifier for this item. - pub id: Id, - /// Some amount for this item. - pub amount: Balance, -} - /// All balance information for an account. #[derive(Encode, Decode, Clone, PartialEq, Eq, Default, RuntimeDebug, MaxEncodedLen, TypeInfo)] pub struct AccountData { diff --git a/substrate/frame/beefy-mmr/Cargo.toml b/substrate/frame/beefy-mmr/Cargo.toml index 51abc306265d60a3ffc990fb6878831e12593a60..b46998a857426fb3edfa8affaea702cffc2f4732 100644 --- a/substrate/frame/beefy-mmr/Cargo.toml +++ b/substrate/frame/beefy-mmr/Cargo.toml @@ -12,28 +12,28 @@ homepage = "https://substrate.io" workspace = true [dependencies] -array-bytes = { version = "6.2.2", optional = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +array-bytes = { optional = true, workspace = true, default-features = true } +codec = { features = ["derive"], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } serde = { optional = true, workspace = true, default-features = true } -binary-merkle-tree = { path = "../../utils/binary-merkle-tree", default-features = false } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -pallet-beefy = { path = "../beefy", default-features = false } -pallet-mmr = { path = "../merkle-mountain-range", default-features = false } -pallet-session = { path = "../session", default-features = false } -sp-consensus-beefy = { path = "../../primitives/consensus/beefy", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -sp-api = { path = "../../primitives/api", default-features = false } -sp-state-machine = { path = "../../primitives/state-machine", default-features = false } +binary-merkle-tree = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-beefy = { workspace = true } +pallet-mmr = { workspace = true } +pallet-session = { workspace = true } +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 } [dev-dependencies] -array-bytes = "6.2.2" -sp-staking = { path = "../../primitives/staking" } +array-bytes = { workspace = true, default-features = true } +sp-staking = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/beefy/Cargo.toml b/substrate/frame/beefy/Cargo.toml index 890ac1399b9dfcee8d71348d8eac9ff7b3ae2546..8ce3a05985be7dfa383b91c187451f3a4753efd6 100644 --- a/substrate/frame/beefy/Cargo.toml +++ b/substrate/frame/beefy/Cargo.toml @@ -12,31 +12,31 @@ homepage = "https://substrate.io" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive", "serde"] } +scale-info = { features = ["derive", "serde"], workspace = true } serde = { optional = true, workspace = true, default-features = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -pallet-authorship = { path = "../authorship", default-features = false } -pallet-session = { path = "../session", default-features = false } -sp-consensus-beefy = { path = "../../primitives/consensus/beefy", default-features = false, features = ["serde"] } -sp-runtime = { path = "../../primitives/runtime", default-features = false, features = ["serde"] } -sp-session = { path = "../../primitives/session", default-features = false } -sp-staking = { path = "../../primitives/staking", default-features = false, features = ["serde"] } -sp-std = { path = "../../primitives/std", default-features = false } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-authorship = { workspace = true } +pallet-session = { workspace = true } +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 = { path = "../election-provider-support" } -pallet-balances = { path = "../balances" } -pallet-offences = { path = "../offences" } -pallet-staking = { path = "../staking" } -pallet-staking-reward-curve = { path = "../staking/reward-curve" } -pallet-timestamp = { path = "../timestamp" } -sp-core = { path = "../../primitives/core" } -sp-io = { path = "../../primitives/io" } -sp-staking = { path = "../../primitives/staking" } -sp-state-machine = { path = "../../primitives/state-machine", default-features = false } +frame-election-provider-support = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +pallet-offences = { workspace = true, default-features = true } +pallet-staking = { workspace = true, default-features = true } +pallet-staking-reward-curve = { workspace = true, default-features = true } +pallet-timestamp = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-staking = { workspace = true, default-features = true } +sp-state-machine = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/beefy/src/mock.rs b/substrate/frame/beefy/src/mock.rs index 0b87de6bf5d79a3884d96f6f7cf79fc96ab3568b..35bf172d60632c7d56aef4acd196946256abb629 100644 --- a/substrate/frame/beefy/src/mock.rs +++ b/substrate/frame/beefy/src/mock.rs @@ -120,20 +120,11 @@ impl pallet_authorship::Config for Test { type EventHandler = (); } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; type Balance = u128; - type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; type ExistentialDeposit = ConstU128<1>; type AccountStore = System; - type WeightInfo = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); - type FreezeIdentifier = (); - type MaxFreezes = (); } impl pallet_timestamp::Config for Test { @@ -171,35 +162,19 @@ impl onchain::Config for OnChainSeqPhragmen { type Bounds = ElectionsBoundsOnChain; } +#[derive_impl(pallet_staking::config_preludes::TestDefaultConfig)] impl pallet_staking::Config for Test { - type RewardRemainder = (); - type CurrencyToVote = (); type RuntimeEvent = RuntimeEvent; type Currency = Balances; - type CurrencyBalance = ::Balance; - type Slash = (); - type Reward = (); - type SessionsPerEra = SessionsPerEra; - type BondingDuration = BondingDuration; - type SlashDeferDuration = (); type AdminOrigin = frame_system::EnsureRoot; type SessionInterface = Self; type UnixTime = pallet_timestamp::Pallet; type EraPayout = pallet_staking::ConvertCurve; - type MaxExposurePageSize = ConstU32<64>; type NextNewSession = Session; type ElectionProvider = onchain::OnChainExecution; type GenesisElectionProvider = Self::ElectionProvider; type VoterList = pallet_staking::UseNominatorsAndValidatorsMap; type TargetList = pallet_staking::UseValidatorsMap; - type NominationsQuota = pallet_staking::FixedNominationsQuota<16>; - type MaxUnlockingChunks = ConstU32<32>; - type MaxControllersInDeprecationBatch = ConstU32<100>; - type HistoryDepth = ConstU32<84>; - type EventListeners = (); - type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; - type WeightInfo = (); - type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; } impl pallet_offences::Config for Test { diff --git a/substrate/frame/benchmarking/Cargo.toml b/substrate/frame/benchmarking/Cargo.toml index b5824ab2ec2eeaa2126bd72f6832e87736a8f914..a2c15951a596673edf2ab6d3485dbefb022e7acb 100644 --- a/substrate/frame/benchmarking/Cargo.toml +++ b/substrate/frame/benchmarking/Cargo.toml @@ -16,29 +16,29 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -linregress = { version = "0.5.1", optional = true } +codec = { workspace = true } +linregress = { optional = true, workspace = true } log = { workspace = true } -paste = "1.0" -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +paste = { workspace = true, default-features = true } +scale-info = { features = ["derive"], workspace = true } serde = { optional = true, workspace = true, default-features = true } -frame-support = { path = "../support", default-features = false } -frame-support-procedural = { path = "../support/procedural", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-api = { path = "../../primitives/api", default-features = false } -sp-application-crypto = { path = "../../primitives/application-crypto", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-runtime-interface = { path = "../../primitives/runtime-interface", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -sp-storage = { path = "../../primitives/storage", default-features = false } -static_assertions = "1.1.0" +frame-support = { workspace = true } +frame-support-procedural = { workspace = true } +frame-system = { workspace = true } +sp-api = { workspace = true } +sp-application-crypto = { workspace = true } +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 } [dev-dependencies] -array-bytes = "6.2.2" -rusty-fork = { version = "0.3.0", default-features = false } -sp-keystore = { path = "../../primitives/keystore" } +array-bytes = { workspace = true, default-features = true } +rusty-fork = { workspace = true } +sp-keystore = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/benchmarking/pov/Cargo.toml b/substrate/frame/benchmarking/pov/Cargo.toml index e4f3c272a63e4938aa2efd6fa30784543383c82a..4341f011fcbf9c323fbe9b5b7de7d1b86bc71c12 100644 --- a/substrate/frame/benchmarking/pov/Cargo.toml +++ b/substrate/frame/benchmarking/pov/Cargo.toml @@ -15,14 +15,14 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "..", default-features = false } -frame-support = { path = "../../support", default-features = false } -frame-system = { path = "../../system", default-features = false } -sp-io = { path = "../../../primitives/io", default-features = false } -sp-runtime = { path = "../../../primitives/runtime", default-features = false } -sp-std = { path = "../../../primitives/std", default-features = false } +codec = { workspace = true } +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/bounties/Cargo.toml b/substrate/frame/bounties/Cargo.toml index fac0054359060fd3c63741eaa1897c66990f5523..4b242a1a577ced6599a8142acc8d85f8af0f93e2 100644 --- a/substrate/frame/bounties/Cargo.toml +++ b/substrate/frame/bounties/Cargo.toml @@ -16,22 +16,22 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", -] } +], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -pallet-treasury = { path = "../treasury", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-treasury = { workspace = true } +sp-core = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -pallet-balances = { path = "../balances" } +pallet-balances = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/bounties/src/benchmarking.rs b/substrate/frame/bounties/src/benchmarking.rs index 3558847c8fedd263e6c57db24195a898a3d0dd6d..a009b132f0598c9ec54a52780982436c9839495f 100644 --- a/substrate/frame/bounties/src/benchmarking.rs +++ b/substrate/frame/bounties/src/benchmarking.rs @@ -177,7 +177,7 @@ benchmarks_instance_pallet! { Bounties::::propose_bounty(RawOrigin::Signed(caller).into(), value, reason)?; let bounty_id = BountyCount::::get() - 1; let approve_origin = - T::ApproveOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; + T::RejectOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; }: close_bounty(approve_origin, bounty_id) close_bounty_active { @@ -186,7 +186,7 @@ benchmarks_instance_pallet! { Treasury::::on_initialize(BlockNumberFor::::zero()); let bounty_id = BountyCount::::get() - 1; let approve_origin = - T::ApproveOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; + T::RejectOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; }: close_bounty(approve_origin, bounty_id) verify { assert_last_event::(Event::BountyCanceled { index: bounty_id }.into()) diff --git a/substrate/frame/bounties/src/lib.rs b/substrate/frame/bounties/src/lib.rs index c930868bf10159326bae978553eadcbd3fe03128..e27ecbda3a2b91ab7433724d488f016046ab71fd 100644 --- a/substrate/frame/bounties/src/lib.rs +++ b/substrate/frame/bounties/src/lib.rs @@ -245,6 +245,9 @@ pub mod pallet { /// The child bounty manager. type ChildBountyManager: ChildBountyManager>; + + /// Handler for the unbalanced decrease when slashing for a rejected bounty. + type OnSlash: OnUnbalanced>; } #[pallet::error] diff --git a/substrate/frame/bounties/src/tests.rs b/substrate/frame/bounties/src/tests.rs index a89f4ff9fbf301a8d03d9ad040a1b4009e7b18f6..9f3a52263ec8d8513e35b04835b632febb04c524 100644 --- a/substrate/frame/bounties/src/tests.rs +++ b/substrate/frame/bounties/src/tests.rs @@ -66,23 +66,11 @@ impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ConstU64<1>; type AccountStore = System; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } parameter_types! { - pub const ProposalBond: Permill = Permill::from_percent(5); pub static Burn: Permill = Permill::from_percent(50); pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry"); pub const TreasuryPalletId2: PalletId = PalletId(*b"py/trsr2"); @@ -95,13 +83,8 @@ parameter_types! { impl pallet_treasury::Config for Test { type PalletId = TreasuryPalletId; type Currency = pallet_balances::Pallet; - type ApproveOrigin = frame_system::EnsureRoot; type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; - type OnSlash = (); - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ConstU64<1>; - type ProposalBondMaximum = (); type SpendPeriod = ConstU64<2>; type Burn = Burn; type BurnDestination = (); // Just gets burned. @@ -122,13 +105,8 @@ impl pallet_treasury::Config for Test { impl pallet_treasury::Config for Test { type PalletId = TreasuryPalletId2; type Currency = pallet_balances::Pallet; - type ApproveOrigin = frame_system::EnsureRoot; type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; - type OnSlash = (); - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ConstU64<1>; - type ProposalBondMaximum = (); type SpendPeriod = ConstU64<2>; type Burn = Burn; type BurnDestination = (); // Just gets burned. @@ -167,6 +145,7 @@ impl Config for Test { type MaximumReasonLength = ConstU32<16384>; type WeightInfo = (); type ChildBountyManager = (); + type OnSlash = (); } impl Config for Test { @@ -182,6 +161,7 @@ impl Config for Test { type MaximumReasonLength = ConstU32<16384>; type WeightInfo = (); type ChildBountyManager = (); + type OnSlash = (); } type TreasuryError = pallet_treasury::Error; @@ -227,56 +207,12 @@ fn minting_works() { }); } -#[test] -fn spend_proposal_takes_min_deposit() { - new_test_ext().execute_with(|| { - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 1, 3) - }); - assert_eq!(Balances::free_balance(0), 99); - assert_eq!(Balances::reserved_balance(0), 1); - }); -} - -#[test] -fn spend_proposal_takes_proportional_deposit() { - new_test_ext().execute_with(|| { - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_eq!(Balances::free_balance(0), 95); - assert_eq!(Balances::reserved_balance(0), 5); - }); -} - -#[test] -fn spend_proposal_fails_when_proposer_poor() { - new_test_ext().execute_with(|| { - assert_noop!( - { - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(2), 100, 3) - }, - TreasuryError::InsufficientProposersBalance, - ); - }); -} - #[test] fn accepted_spend_proposal_ignored_outside_spend_period() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }); + assert_ok!({ Treasury::spend_local(RuntimeOrigin::root(), 100, 3) }); >::on_initialize(1); assert_eq!(Balances::free_balance(3), 0); @@ -297,112 +233,13 @@ fn unused_pot_should_diminish() { }); } -#[test] -fn rejected_spend_proposal_ignored_on_spend_period() { - new_test_ext().execute_with(|| { - Balances::make_free_balance_be(&Treasury::account_id(), 101); - - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::reject_proposal(RuntimeOrigin::root(), 0) - }); - - >::on_initialize(2); - assert_eq!(Balances::free_balance(3), 0); - assert_eq!(Treasury::pot(), 50); - }); -} - -#[test] -fn reject_already_rejected_spend_proposal_fails() { - new_test_ext().execute_with(|| { - Balances::make_free_balance_be(&Treasury::account_id(), 101); - - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::reject_proposal(RuntimeOrigin::root(), 0) - }); - assert_noop!( - { - #[allow(deprecated)] - Treasury::reject_proposal(RuntimeOrigin::root(), 0) - }, - TreasuryError::InvalidIndex - ); - }); -} - -#[test] -fn reject_non_existent_spend_proposal_fails() { - new_test_ext().execute_with(|| { - assert_noop!( - { - #[allow(deprecated)] - Treasury::reject_proposal(RuntimeOrigin::root(), 0) - }, - pallet_treasury::Error::::InvalidIndex - ); - }); -} - -#[test] -fn accept_non_existent_spend_proposal_fails() { - new_test_ext().execute_with(|| { - assert_noop!( - { - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }, - TreasuryError::InvalidIndex - ); - }); -} - -#[test] -fn accept_already_rejected_spend_proposal_fails() { - new_test_ext().execute_with(|| { - Balances::make_free_balance_be(&Treasury::account_id(), 101); - - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::reject_proposal(RuntimeOrigin::root(), 0) - }); - assert_noop!( - { - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }, - TreasuryError::InvalidIndex - ); - }); -} - #[test] fn accepted_spend_proposal_enacted_on_spend_period() { new_test_ext().execute_with(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Treasury::pot(), 100); - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }); + assert_ok!({ Treasury::spend_local(RuntimeOrigin::root(), 100, 3) }); >::on_initialize(2); assert_eq!(Balances::free_balance(3), 100); @@ -416,14 +253,7 @@ fn pot_underflow_should_not_diminish() { Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Treasury::pot(), 100); - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 150, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }); + assert_ok!({ Treasury::spend_local(RuntimeOrigin::root(), 150, 3) }); >::on_initialize(2); assert_eq!(Treasury::pot(), 100); // Pot hasn't changed @@ -444,26 +274,12 @@ fn treasury_account_doesnt_get_deleted() { assert_eq!(Treasury::pot(), 100); let treasury_balance = Balances::free_balance(&Treasury::account_id()); - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), treasury_balance, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }); + assert_ok!({ Treasury::spend_local(RuntimeOrigin::root(), treasury_balance, 3) }); >::on_initialize(2); assert_eq!(Treasury::pot(), 100); // Pot hasn't changed - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), Treasury::pot(), 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 1) - }); + assert_ok!({ Treasury::spend_local(RuntimeOrigin::root(), Treasury::pot(), 3) }); >::on_initialize(4); assert_eq!(Treasury::pot(), 0); // Pot is emptied @@ -486,22 +302,8 @@ fn inexistent_account_works() { assert_eq!(Balances::free_balance(Treasury::account_id()), 0); // Account does not exist assert_eq!(Treasury::pot(), 0); // Pot is empty - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 99, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 1, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 1) - }); + assert_ok!({ Treasury::spend_local(RuntimeOrigin::root(), 99, 3) }); + assert_ok!({ Treasury::spend_local(RuntimeOrigin::root(), 1, 3) }); >::on_initialize(2); assert_eq!(Treasury::pot(), 0); // Pot hasn't changed assert_eq!(Balances::free_balance(3), 0); // Balance of `3` hasn't changed diff --git a/substrate/frame/broker/Cargo.toml b/substrate/frame/broker/Cargo.toml index 8a84fbfdfb701c87cde1dfb935ad1dcb6cf56e04..77c4883e4a433ffb0e0fb8c376b23bf109948769 100644 --- a/substrate/frame/broker/Cargo.toml +++ b/substrate/frame/broker/Cargo.toml @@ -16,22 +16,22 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] log = { workspace = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -bitvec = { version = "1.0.0", default-features = false } -sp-api = { path = "../../primitives/api", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -sp-arithmetic = { path = "../../primitives/arithmetic", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } +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 } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } [dev-dependencies] -sp-io = { path = "../../primitives/io" } -sp-tracing = { path = "../../primitives/tracing" } -pretty_assertions = "1.3.0" +sp-io = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +pretty_assertions = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/child-bounties/Cargo.toml b/substrate/frame/child-bounties/Cargo.toml index 09271632df54b74601d5d318a4749bffcbc86777..d0072e3a476132fb7ea2eeef35d895dc2829dc80 100644 --- a/substrate/frame/child-bounties/Cargo.toml +++ b/substrate/frame/child-bounties/Cargo.toml @@ -16,23 +16,23 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", -] } +], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -pallet-bounties = { path = "../bounties", default-features = false } -pallet-treasury = { path = "../treasury", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-bounties = { workspace = true } +pallet-treasury = { workspace = true } +sp-core = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -pallet-balances = { path = "../balances" } +pallet-balances = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/child-bounties/src/tests.rs b/substrate/frame/child-bounties/src/tests.rs index d9405d3d28977c2cac3b42a034eb5fcfe8e56e8f..125844fa70e2c8dbcbb528bb77551942c497d75a 100644 --- a/substrate/frame/child-bounties/src/tests.rs +++ b/substrate/frame/child-bounties/src/tests.rs @@ -69,23 +69,11 @@ impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ConstU64<1>; type AccountStore = System; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } parameter_types! { - pub const ProposalBond: Permill = Permill::from_percent(5); pub const Burn: Permill = Permill::from_percent(50); pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry"); pub TreasuryAccount: u128 = Treasury::account_id(); @@ -95,13 +83,8 @@ parameter_types! { impl pallet_treasury::Config for Test { type PalletId = TreasuryPalletId; type Currency = pallet_balances::Pallet; - type ApproveOrigin = frame_system::EnsureRoot; type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; - type OnSlash = (); - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ConstU64<1>; - type ProposalBondMaximum = (); type SpendPeriod = ConstU64<2>; type Burn = Burn; type BurnDestination = (); @@ -138,6 +121,7 @@ impl pallet_bounties::Config for Test { type MaximumReasonLength = ConstU32<300>; type WeightInfo = (); type ChildBountyManager = ChildBounties; + type OnSlash = (); } impl pallet_child_bounties::Config for Test { type RuntimeEvent = RuntimeEvent; diff --git a/substrate/frame/collective/Cargo.toml b/substrate/frame/collective/Cargo.toml index d966370238bc4f2c8597555187a1830280752732..6fc4bb7782987f6e32faaabea1e4e661822829bb 100644 --- a/substrate/frame/collective/Cargo.toml +++ b/substrate/frame/collective/Cargo.toml @@ -16,16 +16,16 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-core = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/contracts/Cargo.toml b/substrate/frame/contracts/Cargo.toml index 70363562f6af3c52846cb7103e5834c617ac0ae8..252151fb9193b5f76bfae95187dc9db650cf78be 100644 --- a/substrate/frame/contracts/Cargo.toml +++ b/substrate/frame/contracts/Cargo.toml @@ -18,64 +18,64 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -paste = { version = "1.0", default-features = false } -bitflags = "1.3" -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +paste = { workspace = true } +bitflags = { workspace = true } +codec = { features = [ "derive", "max-encoded-len", -] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +], workspace = true } +scale-info = { features = ["derive"], workspace = true } log = { workspace = true } serde = { optional = true, features = ["derive"], workspace = true, default-features = true } -smallvec = { version = "1", default-features = false, features = [ +smallvec = { features = [ "const_generics", -] } -wasmi = { version = "0.32.3", default-features = false } -impl-trait-for-tuples = "0.2" +], workspace = true } +wasmi = { workspace = true } +impl-trait-for-tuples = { workspace = true } # Only used in benchmarking to generate contract code -wasm-instrument = { version = "0.4", optional = true, default-features = false } -rand = { version = "0.8", optional = true, default-features = false } -rand_pcg = { version = "0.3", optional = true } +wasm-instrument = { optional = true, workspace = true } +rand = { optional = true, workspace = true } +rand_pcg = { optional = true, workspace = true } # Substrate Dependencies -environmental = { version = "1.1.4", default-features = false } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -pallet-balances = { path = "../balances", default-features = false, optional = true } -pallet-contracts-uapi = { path = "uapi" } -pallet-contracts-proc-macro = { path = "proc-macro" } -sp-api = { path = "../../primitives/api", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +environmental = { workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-balances = { optional = true, workspace = true } +pallet-contracts-uapi = { workspace = true, default-features = true } +pallet-contracts-proc-macro = { workspace = true, default-features = true } +sp-api = { workspace = true } +sp-core = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } -xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../polkadot/xcm/xcm-builder", default-features = false } +xcm = { workspace = true } +xcm-builder = { workspace = true } [dev-dependencies] -array-bytes = "6.2.2" -assert_matches = "1" -env_logger = "0.11" -pretty_assertions = "1" -wat = "1" -pallet-contracts-fixtures = { path = "./fixtures" } +array-bytes = { workspace = true, default-features = true } +assert_matches = { workspace = true } +env_logger = { workspace = true } +pretty_assertions = { workspace = true } +wat = { workspace = true } +pallet-contracts-fixtures = { workspace = true } # Polkadot Dependencies -xcm-builder = { package = "staging-xcm-builder", path = "../../../polkadot/xcm/xcm-builder" } +xcm-builder = { workspace = true, default-features = true } # Substrate Dependencies -pallet-balances = { path = "../balances" } -pallet-timestamp = { path = "../timestamp" } -pallet-message-queue = { path = "../message-queue" } -pallet-insecure-randomness-collective-flip = { path = "../insecure-randomness-collective-flip" } -pallet-utility = { path = "../utility" } -pallet-assets = { path = "../assets" } -pallet-proxy = { path = "../proxy" } -sp-keystore = { path = "../../primitives/keystore" } -sp-tracing = { path = "../../primitives/tracing" } +pallet-balances = { workspace = true, default-features = true } +pallet-timestamp = { workspace = true, default-features = true } +pallet-message-queue = { workspace = true, default-features = true } +pallet-insecure-randomness-collective-flip = { workspace = true, default-features = true } +pallet-utility = { workspace = true, default-features = true } +pallet-assets = { workspace = true, default-features = true } +pallet-proxy = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/contracts/fixtures/Cargo.toml b/substrate/frame/contracts/fixtures/Cargo.toml index 8c93c6f16f66fa2c4a6955607fbd9797c0eda925..6b0751571cc9c1cc8b3284c2ea17a23ca48c5194 100644 --- a/substrate/frame/contracts/fixtures/Cargo.toml +++ b/substrate/frame/contracts/fixtures/Cargo.toml @@ -11,17 +11,17 @@ description = "Fixtures for testing contracts pallet." workspace = true [dependencies] -frame-system = { path = "../../system" } -sp-runtime = { path = "../../../primitives/runtime" } -anyhow = "1.0.81" +frame-system = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +anyhow = { workspace = true } [build-dependencies] -parity-wasm = "0.45.0" -tempfile = "3.8.1" -toml = "0.8.2" -twox-hash = "1.6.3" +parity-wasm = { workspace = true } +tempfile = { workspace = true } +toml = { workspace = true } +twox-hash = { workspace = true, default-features = true } polkavm-linker = { workspace = true, optional = true } -anyhow = "1.0.81" +anyhow = { workspace = true } [features] riscv = ["polkavm-linker"] diff --git a/substrate/frame/contracts/mock-network/Cargo.toml b/substrate/frame/contracts/mock-network/Cargo.toml index a348b7308d1232109a4763dcc764fdac87deee6d..7df5d304c34afa9258492a121ca23feff0318de9 100644 --- a/substrate/frame/contracts/mock-network/Cargo.toml +++ b/substrate/frame/contracts/mock-network/Cargo.toml @@ -12,41 +12,41 @@ description = "A mock network for testing pallet-contracts" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive", "max-encoded-len"] } +codec = { features = ["derive", "max-encoded-len"], workspace = true } -frame-support = { path = "../../support", default-features = false } -frame-system = { path = "../../system", default-features = false } -pallet-assets = { path = "../../assets" } -pallet-balances = { path = "../../balances" } -pallet-contracts = { path = ".." } -pallet-contracts-uapi = { path = "../uapi", default-features = false } -pallet-contracts-proc-macro = { path = "../proc-macro" } -pallet-insecure-randomness-collective-flip = { path = "../../insecure-randomness-collective-flip" } -pallet-message-queue = { path = "../../message-queue" } -pallet-proxy = { path = "../../proxy" } -pallet-timestamp = { path = "../../timestamp" } -pallet-utility = { path = "../../utility" } -pallet-xcm = { path = "../../../../polkadot/xcm/pallet-xcm", default-features = false } -polkadot-parachain-primitives = { path = "../../../../polkadot/parachain" } -polkadot-primitives = { path = "../../../../polkadot/primitives" } -polkadot-runtime-parachains = { path = "../../../../polkadot/runtime/parachains" } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -sp-api = { path = "../../../primitives/api", default-features = false } -sp-core = { path = "../../../primitives/core", default-features = false } -sp-io = { path = "../../../primitives/io", default-features = false } -sp-keystore = { path = "../../../primitives/keystore" } -sp-runtime = { path = "../../../primitives/runtime", default-features = false } -sp-std = { path = "../../../primitives/std", default-features = false } -sp-tracing = { path = "../../../primitives/tracing" } -xcm = { package = "staging-xcm", path = "../../../../polkadot/xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../../polkadot/xcm/xcm-builder" } -xcm-executor = { package = "staging-xcm-executor", path = "../../../../polkadot/xcm/xcm-executor", default-features = false } -xcm-simulator = { path = "../../../../polkadot/xcm/xcm-simulator" } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-assets = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +pallet-contracts = { workspace = true, default-features = true } +pallet-contracts-uapi = { workspace = true } +pallet-contracts-proc-macro = { workspace = true, default-features = true } +pallet-insecure-randomness-collective-flip = { workspace = true, default-features = true } +pallet-message-queue = { workspace = true, default-features = true } +pallet-proxy = { workspace = true, default-features = true } +pallet-timestamp = { workspace = true, default-features = true } +pallet-utility = { workspace = true, default-features = true } +pallet-xcm = { workspace = true } +polkadot-parachain-primitives = { workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +polkadot-runtime-parachains = { workspace = true, default-features = true } +scale-info = { features = ["derive"], workspace = true } +sp-api = { workspace = true } +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 } +xcm-executor = { workspace = true } +xcm-simulator = { workspace = true, default-features = true } [dev-dependencies] -assert_matches = "1" -pretty_assertions = "1" -pallet-contracts-fixtures = { path = "../fixtures" } +assert_matches = { workspace = true } +pretty_assertions = { workspace = true } +pallet-contracts-fixtures = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/contracts/proc-macro/Cargo.toml b/substrate/frame/contracts/proc-macro/Cargo.toml index 4080cd0442dbc516231dc983a3b6609a211523db..3651b172d75fb0c93f9d62980aed0706cbcceeab 100644 --- a/substrate/frame/contracts/proc-macro/Cargo.toml +++ b/substrate/frame/contracts/proc-macro/Cargo.toml @@ -18,6 +18,6 @@ targets = ["x86_64-unknown-linux-gnu"] proc-macro = true [dependencies] -proc-macro2 = "1.0.56" +proc-macro2 = { workspace = true } quote = { workspace = true } syn = { features = ["full"], workspace = true } diff --git a/substrate/frame/contracts/src/lib.rs b/substrate/frame/contracts/src/lib.rs index e9cf28a66912be821de182a707d52d74ecd6c519..47772e0a5a0bc34ff3662cdb1bc5211b44032e40 100644 --- a/substrate/frame/contracts/src/lib.rs +++ b/substrate/frame/contracts/src/lib.rs @@ -529,7 +529,7 @@ pub mod pallet { } } - #[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig, no_aggregated_types)] + #[derive_impl(frame_system::config_preludes::TestDefaultConfig, no_aggregated_types)] impl frame_system::DefaultConfig for TestDefaultConfig {} #[frame_support::register_default_impl(TestDefaultConfig)] diff --git a/substrate/frame/contracts/uapi/Cargo.toml b/substrate/frame/contracts/uapi/Cargo.toml index e19caa460419eb1557f9ed2cad9d8112e1270175..cb559ec88d281288dc352255ad1b3e93f200151c 100644 --- a/substrate/frame/contracts/uapi/Cargo.toml +++ b/substrate/frame/contracts/uapi/Cargo.toml @@ -12,13 +12,13 @@ description = "Exposes all the host functions that a contract can import." workspace = true [dependencies] -paste = { version = "1.0", default-features = false } -bitflags = "1.0" -scale-info = { version = "2.11.1", default-features = false, features = ["derive"], optional = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +paste = { workspace = true } +bitflags = { workspace = true } +scale-info = { features = ["derive"], optional = true, workspace = true } +codec = { features = [ "derive", "max-encoded-len", -], optional = true } +], optional = true, workspace = true } [target.'cfg(target_arch = "riscv32")'.dependencies] polkavm-derive = { workspace = true } diff --git a/substrate/frame/conviction-voting/Cargo.toml b/substrate/frame/conviction-voting/Cargo.toml index 20de4d858ad62e4e499e5c4ee6786b1f5ee2f6c4..b96809b8aeb4d2a1011c003471f3c918157e60a9 100644 --- a/substrate/frame/conviction-voting/Cargo.toml +++ b/substrate/frame/conviction-voting/Cargo.toml @@ -16,24 +16,24 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -assert_matches = "1.3.0" -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +assert_matches = { workspace = true } +codec = { features = [ "derive", "max-encoded-len", -] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +], workspace = true } +scale-info = { features = ["derive"], workspace = true } serde = { features = ["derive"], optional = true, workspace = true, default-features = true } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -pallet-balances = { path = "../balances" } -pallet-scheduler = { path = "../scheduler" } -sp-core = { path = "../../primitives/core" } +pallet-balances = { workspace = true, default-features = true } +pallet-scheduler = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/conviction-voting/src/tests.rs b/substrate/frame/conviction-voting/src/tests.rs index 0e985e25290fad07961c0a5e5deba4b0148dc1af..78569fb3c9f250d6b5d009936a34a6187639ce1a 100644 --- a/substrate/frame/conviction-voting/src/tests.rs +++ b/substrate/frame/conviction-voting/src/tests.rs @@ -54,20 +54,9 @@ impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type MaxLocks = ConstU32<10>; - type Balance = u64; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ConstU64<1>; type AccountStore = System; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } #[derive(Clone, PartialEq, Eq, Debug)] diff --git a/substrate/frame/core-fellowship/Cargo.toml b/substrate/frame/core-fellowship/Cargo.toml index 8773a124cd02accb450daa2218c161563a68d8bf..44290402594a956e58250cf4086d4f0e9cc4400f 100644 --- a/substrate/frame/core-fellowship/Cargo.toml +++ b/substrate/frame/core-fellowship/Cargo.toml @@ -16,18 +16,18 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-arithmetic = { path = "../../primitives/arithmetic", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -pallet-ranked-collective = { path = "../ranked-collective", default-features = false, optional = true } +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +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] default = ["std"] diff --git a/substrate/frame/core-fellowship/src/benchmarking.rs b/substrate/frame/core-fellowship/src/benchmarking.rs index b3ee3ab7d165fd87710b207ab4668bba450e2189..34461e062b35cc73c727e81fcdb9ab9081c2580c 100644 --- a/substrate/frame/core-fellowship/src/benchmarking.rs +++ b/substrate/frame/core-fellowship/src/benchmarking.rs @@ -85,6 +85,45 @@ mod benchmarks { Ok(()) } + #[benchmark] + fn set_partial_params() -> Result<(), BenchmarkError> { + let max_rank = T::MaxRank::get().try_into().unwrap(); + + // Set up the initial default state for the Params storage + let params = ParamsType { + active_salary: BoundedVec::try_from(vec![100u32.into(); max_rank]).unwrap(), + passive_salary: BoundedVec::try_from(vec![10u32.into(); max_rank]).unwrap(), + demotion_period: BoundedVec::try_from(vec![100u32.into(); max_rank]).unwrap(), + min_promotion_period: BoundedVec::try_from(vec![100u32.into(); max_rank]).unwrap(), + offboard_timeout: 1u32.into(), + }; + CoreFellowship::::set_params(RawOrigin::Root.into(), Box::new(params))?; + + let default_params = Params::::get(); + let expected_params = ParamsType { + active_salary: default_params.active_salary, + passive_salary: BoundedVec::try_from(vec![10u32.into(); max_rank]).unwrap(), + demotion_period: default_params.demotion_period, + min_promotion_period: BoundedVec::try_from(vec![100u32.into(); max_rank]).unwrap(), + offboard_timeout: 1u32.into(), + }; + + let params_payload = ParamsType { + active_salary: BoundedVec::try_from(vec![None; max_rank]).unwrap(), + passive_salary: BoundedVec::try_from(vec![Some(10u32.into()); max_rank]).unwrap(), + demotion_period: BoundedVec::try_from(vec![None; max_rank]).unwrap(), + min_promotion_period: BoundedVec::try_from(vec![Some(100u32.into()); max_rank]) + .unwrap(), + offboard_timeout: None, + }; + + #[extrinsic_call] + _(RawOrigin::Root, Box::new(params_payload.clone())); + + assert_eq!(Params::::get(), expected_params); + Ok(()) + } + #[benchmark] fn bump_offboard() -> Result<(), BenchmarkError> { set_benchmark_params::()?; @@ -171,6 +210,22 @@ mod benchmarks { Ok(()) } + /// Benchmark the `promote_fast` extrinsic to promote someone up to `r`. + #[benchmark] + fn promote_fast(r: Linear<1, { T::MaxRank::get() as u32 }>) -> Result<(), BenchmarkError> { + let r = r.try_into().expect("r is too large"); + let member = make_member::(0)?; + + ensure_evidence::(&member)?; + + #[extrinsic_call] + _(RawOrigin::Root, member.clone(), r); + + assert_eq!(T::Members::rank_of(&member), Some(r)); + assert!(!MemberEvidence::::contains_key(&member)); + Ok(()) + } + #[benchmark] fn offboard() -> Result<(), BenchmarkError> { let member = make_member::(0)?; diff --git a/substrate/frame/core-fellowship/src/lib.rs b/substrate/frame/core-fellowship/src/lib.rs index 94339b85d0524a297241248312e92b31e761149c..5ed2562d6d019b9a85e3974005831861a3e37887 100644 --- a/substrate/frame/core-fellowship/src/lib.rs +++ b/substrate/frame/core-fellowship/src/lib.rs @@ -209,6 +209,10 @@ pub mod pallet { /// rank to which it can promote. type PromoteOrigin: EnsureOrigin>; + /// The origin that has permission to "fast" promote a member by ignoring promotion periods + /// and skipping ranks. The `Success` value is the maximum rank to which it can promote. + type FastPromoteOrigin: EnsureOrigin>; + /// The maximum size in bytes submitted evidence is allowed to be. #[pallet::constant] type EvidenceSize: Get; @@ -222,6 +226,11 @@ pub mod pallet { pub type ParamsOf = ParamsType<>::Balance, BlockNumberFor, >::MaxRank>; + pub type PartialParamsOf = ParamsType< + Option<>::Balance>, + Option>, + >::MaxRank, + >; pub type MemberStatusOf = MemberStatus>; pub type RankOf = <>::Members as RankedMembers>::Rank; @@ -493,6 +502,44 @@ pub mod pallet { Ok(()) } + /// Fast promotions can skip ranks and ignore the `min_promotion_period`. + /// + /// This is useful for out-of-band promotions, hence it has its own `FastPromoteOrigin` to + /// be (possibly) more restrictive than `PromoteOrigin`. Note that the member must already + /// be inducted. + #[pallet::weight(T::WeightInfo::promote_fast(*to_rank as u32))] + #[pallet::call_index(10)] + pub fn promote_fast( + origin: OriginFor, + who: T::AccountId, + to_rank: RankOf, + ) -> DispatchResult { + match T::FastPromoteOrigin::try_origin(origin) { + Ok(allow_rank) => ensure!(allow_rank >= to_rank, Error::::NoPermission), + Err(origin) => ensure_root(origin)?, + } + ensure!(to_rank as u32 <= T::MaxRank::get(), Error::::InvalidRank); + let curr_rank = T::Members::rank_of(&who).ok_or(Error::::Unranked)?; + ensure!(to_rank > curr_rank, Error::::UnexpectedRank); + + let mut member = Member::::get(&who).ok_or(Error::::NotTracked)?; + let now = frame_system::Pallet::::block_number(); + member.last_promotion = now; + member.last_proof = now; + + for rank in (curr_rank + 1)..=to_rank { + T::Members::promote(&who)?; + + // NOTE: We could factor this out, but it would destroy our invariants: + Member::::insert(&who, &member); + + Self::dispose_evidence(who.clone(), rank.saturating_sub(1), Some(rank)); + Self::deposit_event(Event::::Promoted { who: who.clone(), to_rank: rank }); + } + + Ok(()) + } + /// Stop tracking a prior member who is now not a ranked member of the collective. /// /// - `origin`: A `Signed` origin of an account. @@ -558,9 +605,59 @@ pub mod pallet { Ok(Pays::No.into()) } + + /// Set the parameters partially. + /// + /// - `origin`: An origin complying with `ParamsOrigin` or root. + /// - `partial_params`: The new parameters for the pallet. + /// + /// This update config with multiple arguments without duplicating + /// the fields that does not need to update (set to None). + #[pallet::weight(T::WeightInfo::set_partial_params())] + #[pallet::call_index(9)] + pub fn set_partial_params( + origin: OriginFor, + partial_params: Box>, + ) -> DispatchResult { + T::ParamsOrigin::ensure_origin_or_root(origin)?; + let params = Params::::mutate(|p| { + Self::set_partial_params_slice(&mut p.active_salary, partial_params.active_salary); + Self::set_partial_params_slice( + &mut p.passive_salary, + partial_params.passive_salary, + ); + Self::set_partial_params_slice( + &mut p.demotion_period, + partial_params.demotion_period, + ); + Self::set_partial_params_slice( + &mut p.min_promotion_period, + partial_params.min_promotion_period, + ); + if let Some(new_offboard_timeout) = partial_params.offboard_timeout { + p.offboard_timeout = new_offboard_timeout; + } + p.clone() + }); + Self::deposit_event(Event::::ParamsChanged { params }); + Ok(()) + } } impl, I: 'static> Pallet { + /// Partially update the base slice with a new slice + /// + /// Only elements in the base slice which has a new value in the new slice will be updated. + pub(crate) fn set_partial_params_slice( + base_slice: &mut BoundedVec>::MaxRank>, + new_slice: BoundedVec, >::MaxRank>, + ) { + for (base_element, new_element) in base_slice.iter_mut().zip(new_slice) { + if let Some(element) = new_element { + *base_element = element; + } + } + } /// Convert a rank into a `0..RANK_COUNT` index suitable for the arrays in Params. /// /// Rank 1 becomes index 0, rank `RANK_COUNT` becomes index `RANK_COUNT - 1`. Any rank not diff --git a/substrate/frame/core-fellowship/src/tests/integration.rs b/substrate/frame/core-fellowship/src/tests/integration.rs index f3137316658576d91616428ee32d51b916189963..bcf70c7beb102c49f86a583e9e4c476aa216275e 100644 --- a/substrate/frame/core-fellowship/src/tests/integration.rs +++ b/substrate/frame/core-fellowship/src/tests/integration.rs @@ -78,6 +78,7 @@ impl Config for Test { type InductOrigin = EnsureInducted; type ApproveOrigin = TryMapSuccess, u64>, TryMorphInto>; type PromoteOrigin = TryMapSuccess, u64>, TryMorphInto>; + type FastPromoteOrigin = Self::PromoteOrigin; type EvidenceSize = EvidenceSize; type MaxRank = ConstU32<9>; } @@ -157,6 +158,7 @@ impl pallet_ranked_collective::Config for Test { type MinRankOfClass = MinRankOfClass; type MemberSwappedHandler = CoreFellowship; type VoteWeight = Geometric; + type MaxMemberCount = (); #[cfg(feature = "runtime-benchmarks")] type BenchmarkSetup = CoreFellowship; } diff --git a/substrate/frame/core-fellowship/src/tests/unit.rs b/substrate/frame/core-fellowship/src/tests/unit.rs index 9245e5159a901d47842339836ae3f0767a2b1b1f..11d1ea9fe5b7563f16d6d9c7118071ec2b1a2e92 100644 --- a/substrate/frame/core-fellowship/src/tests/unit.rs +++ b/substrate/frame/core-fellowship/src/tests/unit.rs @@ -21,7 +21,7 @@ use std::collections::BTreeMap; use core::cell::RefCell; use frame_support::{ - assert_noop, assert_ok, derive_impl, ord_parameter_types, + assert_noop, assert_ok, derive_impl, hypothetically, ord_parameter_types, pallet_prelude::Weight, parameter_types, traits::{tokens::GetSalary, ConstU32, IsInVec, TryMapSuccess}, @@ -115,6 +115,7 @@ impl Config for Test { type InductOrigin = EnsureInducted; type ApproveOrigin = TryMapSuccess, u64>, TryMorphInto>; type PromoteOrigin = TryMapSuccess, u64>, TryMorphInto>; + type FastPromoteOrigin = Self::PromoteOrigin; type EvidenceSize = ConstU32<1024>; type MaxRank = ConstU32<9>; } @@ -187,6 +188,40 @@ fn set_params_works() { }); } +#[test] +fn set_partial_params_works() { + new_test_ext().execute_with(|| { + let params = ParamsType { + active_salary: bounded_vec![None; 9], + passive_salary: bounded_vec![None; 9], + demotion_period: bounded_vec![None, Some(10), None, None, None, None, None, None, None], + min_promotion_period: bounded_vec![None; 9], + offboard_timeout: Some(2), + }; + assert_noop!( + CoreFellowship::set_partial_params(signed(2), Box::new(params.clone())), + DispatchError::BadOrigin + ); + assert_ok!(CoreFellowship::set_partial_params(signed(1), Box::new(params))); + + // Update params from the base params value declared in `new_test_ext` + let raw_updated_params = ParamsType { + active_salary: bounded_vec![10, 20, 30, 40, 50, 60, 70, 80, 90], + passive_salary: bounded_vec![1, 2, 3, 4, 5, 6, 7, 8, 9], + demotion_period: bounded_vec![2, 10, 6, 8, 10, 12, 14, 16, 18], + min_promotion_period: bounded_vec![3, 6, 9, 12, 15, 18, 21, 24, 27], + offboard_timeout: 2, + }; + // Updated params stored in Params storage value + let updated_params = Params::::get(); + assert_eq!(raw_updated_params, updated_params); + + System::assert_last_event( + Event::::ParamsChanged { params: updated_params }.into(), + ); + }); +} + #[test] fn induct_works() { new_test_ext().execute_with(|| { @@ -222,6 +257,99 @@ fn promote_works() { }); } +#[test] +fn promote_fast_works() { + let alice = 1; + + new_test_ext().execute_with(|| { + assert_noop!( + CoreFellowship::promote_fast(signed(alice), alice, 1), + Error::::Unranked + ); + set_rank(alice, 0); + assert_noop!( + CoreFellowship::promote_fast(signed(alice), alice, 1), + Error::::NotTracked + ); + assert_ok!(CoreFellowship::import(signed(alice))); + + // Cannot fast promote to the same rank: + assert_noop!( + CoreFellowship::promote_fast(signed(alice), alice, 0), + Error::::UnexpectedRank + ); + assert_ok!(CoreFellowship::promote_fast(signed(alice), alice, 1)); + assert_eq!(TestClub::rank_of(&alice), Some(1)); + + // Cannot promote normally because of the period: + assert_noop!(CoreFellowship::promote(signed(2), alice, 2), Error::::TooSoon); + // But can fast promote: + assert_ok!(CoreFellowship::promote_fast(signed(2), alice, 2)); + assert_eq!(TestClub::rank_of(&alice), Some(2)); + + // Cannot promote to lower rank: + assert_noop!( + CoreFellowship::promote_fast(signed(alice), alice, 0), + Error::::UnexpectedRank + ); + assert_noop!( + CoreFellowship::promote_fast(signed(alice), alice, 1), + Error::::UnexpectedRank + ); + // Permission is checked: + assert_noop!( + CoreFellowship::promote_fast(signed(alice), alice, 2), + Error::::NoPermission + ); + + // Can fast promote up to the maximum: + assert_ok!(CoreFellowship::promote_fast(signed(9), alice, 9)); + // But not past the maximum: + assert_noop!( + CoreFellowship::promote_fast(RuntimeOrigin::root(), alice, 10), + Error::::InvalidRank + ); + }); +} + +/// Compare the storage root hashes of a normal promote and a fast promote. +#[test] +fn promote_fast_identical_to_promote() { + let alice = 1; + + new_test_ext().execute_with(|| { + set_rank(alice, 0); + assert_eq!(TestClub::rank_of(&alice), Some(0)); + assert_ok!(CoreFellowship::import(signed(alice))); + run_to(3); + assert_eq!(TestClub::rank_of(&alice), Some(0)); + assert_ok!(CoreFellowship::submit_evidence( + signed(alice), + Wish::Promotion, + bounded_vec![0; 1024] + )); + + let root_promote = hypothetically!({ + assert_ok!(CoreFellowship::promote(signed(alice), alice, 1)); + // Don't clean the events since they should emit the same events: + sp_io::storage::root(sp_runtime::StateVersion::V1) + }); + + // This is using thread locals instead of storage... + TestClub::demote(&alice).unwrap(); + + let root_promote_fast = hypothetically!({ + assert_ok!(CoreFellowship::promote_fast(signed(alice), alice, 1)); + + sp_io::storage::root(sp_runtime::StateVersion::V1) + }); + + assert_eq!(root_promote, root_promote_fast); + // Ensure that we don't compare trivial stuff like `()` from a type error above. + assert_eq!(root_promote.len(), 32); + }); +} + #[test] fn sync_works() { new_test_ext().execute_with(|| { diff --git a/substrate/frame/core-fellowship/src/weights.rs b/substrate/frame/core-fellowship/src/weights.rs index 8fad6f585c1129e9a6c4160ed396cea28158e990..5e64600b662b948dee4cbe00f588aaff5f8a76fd 100644 --- a/substrate/frame/core-fellowship/src/weights.rs +++ b/substrate/frame/core-fellowship/src/weights.rs @@ -18,9 +18,9 @@ //! Autogenerated weights for `pallet_core_fellowship` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 32.0.0 -//! DATE: 2024-04-12, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2024-06-26, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `runner-anb7yjbi-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` +//! HOSTNAME: `runner-x5tnzzy-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: `Compiled`, CHAIN: `Some("dev")`, DB CACHE: `1024` // Executed Command: @@ -50,11 +50,13 @@ use core::marker::PhantomData; /// Weight functions needed for `pallet_core_fellowship`. pub trait WeightInfo { fn set_params() -> Weight; + fn set_partial_params() -> Weight; fn bump_offboard() -> Weight; fn bump_demote() -> Weight; fn set_active() -> Weight; fn induct() -> Weight; fn promote() -> Weight; + fn promote_fast(r: u32, ) -> Weight; fn offboard() -> Weight; fn import() -> Weight; fn approve() -> Weight; @@ -70,8 +72,19 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_633_000 picoseconds. - Weight::from_parts(8_018_000, 0) + // Minimum execution time: 5_772_000 picoseconds. + Weight::from_parts(6_000_000, 0) + .saturating_add(T::DbWeight::get().writes(1_u64)) + } + /// Storage: `CoreFellowship::Params` (r:1 w:1) + /// Proof: `CoreFellowship::Params` (`max_values`: Some(1), `max_size`: Some(368), added: 863, mode: `MaxEncodedLen`) + fn set_partial_params() -> Weight { + // Proof Size summary in bytes: + // Measured: `399` + // Estimated: `1853` + // Minimum execution time: 10_050_000 picoseconds. + Weight::from_parts(10_244_000, 1853) + .saturating_add(T::DbWeight::get().reads(1_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } /// Storage: `CoreFellowship::Member` (r:1 w:1) @@ -92,8 +105,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `17278` // Estimated: `19894` - // Minimum execution time: 57_597_000 picoseconds. - Weight::from_parts(58_825_000, 19894) + // Minimum execution time: 54_433_000 picoseconds. + Weight::from_parts(55_650_000, 19894) .saturating_add(T::DbWeight::get().reads(6_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } @@ -115,8 +128,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `17388` // Estimated: `19894` - // Minimum execution time: 61_387_000 picoseconds. - Weight::from_parts(63_408_000, 19894) + // Minimum execution time: 57_634_000 picoseconds. + Weight::from_parts(58_816_000, 19894) .saturating_add(T::DbWeight::get().reads(6_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } @@ -128,8 +141,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `388` // Estimated: `3514` - // Minimum execution time: 15_941_000 picoseconds. - Weight::from_parts(16_547_000, 3514) + // Minimum execution time: 14_527_000 picoseconds. + Weight::from_parts(14_948_000, 3514) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -147,8 +160,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `146` // Estimated: `3514` - // Minimum execution time: 24_963_000 picoseconds. - Weight::from_parts(25_873_000, 3514) + // Minimum execution time: 22_137_000 picoseconds. + Weight::from_parts(22_925_000, 3514) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(5_u64)) } @@ -170,11 +183,38 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `16931` // Estimated: `19894` - // Minimum execution time: 55_062_000 picoseconds. - Weight::from_parts(58_422_000, 19894) + // Minimum execution time: 51_837_000 picoseconds. + Weight::from_parts(52_810_000, 19894) .saturating_add(T::DbWeight::get().reads(5_u64)) .saturating_add(T::DbWeight::get().writes(6_u64)) } + /// Storage: `RankedCollective::Members` (r:1 w:1) + /// Proof: `RankedCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `CoreFellowship::Member` (r:1 w:1) + /// Proof: `CoreFellowship::Member` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + /// Storage: `RankedCollective::MemberCount` (r:9 w:9) + /// Proof: `RankedCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `CoreFellowship::MemberEvidence` (r:1 w:1) + /// Proof: `CoreFellowship::MemberEvidence` (`max_values`: None, `max_size`: Some(16429), added: 18904, mode: `MaxEncodedLen`) + /// Storage: `RankedCollective::IndexToId` (r:0 w:9) + /// Proof: `RankedCollective::IndexToId` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `RankedCollective::IdToIndex` (r:0 w:9) + /// Proof: `RankedCollective::IdToIndex` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// The range of component `r` is `[1, 9]`. + fn promote_fast(r: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `16844` + // Estimated: `19894 + r * (2489 ยฑ0)` + // Minimum execution time: 45_065_000 picoseconds. + Weight::from_parts(34_090_392, 19894) + // Standard Error: 18_620 + .saturating_add(Weight::from_parts(13_578_046, 0).saturating_mul(r.into())) + .saturating_add(T::DbWeight::get().reads(3_u64)) + .saturating_add(T::DbWeight::get().reads((1_u64).saturating_mul(r.into()))) + .saturating_add(T::DbWeight::get().writes(3_u64)) + .saturating_add(T::DbWeight::get().writes((3_u64).saturating_mul(r.into()))) + .saturating_add(Weight::from_parts(0, 2489).saturating_mul(r.into())) + } /// Storage: `RankedCollective::Members` (r:1 w:0) /// Proof: `RankedCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) /// Storage: `CoreFellowship::Member` (r:1 w:1) @@ -185,8 +225,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `293` // Estimated: `3514` - // Minimum execution time: 15_901_000 picoseconds. - Weight::from_parts(16_746_000, 3514) + // Minimum execution time: 14_321_000 picoseconds. + Weight::from_parts(14_747_000, 3514) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -198,8 +238,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `313` // Estimated: `3514` - // Minimum execution time: 14_768_000 picoseconds. - Weight::from_parts(15_421_000, 3514) + // Minimum execution time: 13_525_000 picoseconds. + Weight::from_parts(13_843_000, 3514) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -213,8 +253,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `16843` // Estimated: `19894` - // Minimum execution time: 36_925_000 picoseconds. - Weight::from_parts(38_330_000, 19894) + // Minimum execution time: 34_719_000 picoseconds. + Weight::from_parts(35_162_000, 19894) .saturating_add(T::DbWeight::get().reads(3_u64)) .saturating_add(T::DbWeight::get().writes(2_u64)) } @@ -226,8 +266,8 @@ impl WeightInfo for SubstrateWeight { // Proof Size summary in bytes: // Measured: `79` // Estimated: `19894` - // Minimum execution time: 25_210_000 picoseconds. - Weight::from_parts(26_247_000, 19894) + // Minimum execution time: 23_477_000 picoseconds. + Weight::from_parts(23_897_000, 19894) .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(1_u64)) } @@ -241,8 +281,19 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `0` // Estimated: `0` - // Minimum execution time: 7_633_000 picoseconds. - Weight::from_parts(8_018_000, 0) + // Minimum execution time: 5_772_000 picoseconds. + Weight::from_parts(6_000_000, 0) + .saturating_add(RocksDbWeight::get().writes(1_u64)) + } + /// Storage: `CoreFellowship::Params` (r:1 w:1) + /// Proof: `CoreFellowship::Params` (`max_values`: Some(1), `max_size`: Some(368), added: 863, mode: `MaxEncodedLen`) + fn set_partial_params() -> Weight { + // Proof Size summary in bytes: + // Measured: `399` + // Estimated: `1853` + // Minimum execution time: 10_050_000 picoseconds. + Weight::from_parts(10_244_000, 1853) + .saturating_add(RocksDbWeight::get().reads(1_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } /// Storage: `CoreFellowship::Member` (r:1 w:1) @@ -263,8 +314,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `17278` // Estimated: `19894` - // Minimum execution time: 57_597_000 picoseconds. - Weight::from_parts(58_825_000, 19894) + // Minimum execution time: 54_433_000 picoseconds. + Weight::from_parts(55_650_000, 19894) .saturating_add(RocksDbWeight::get().reads(6_u64)) .saturating_add(RocksDbWeight::get().writes(6_u64)) } @@ -286,8 +337,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `17388` // Estimated: `19894` - // Minimum execution time: 61_387_000 picoseconds. - Weight::from_parts(63_408_000, 19894) + // Minimum execution time: 57_634_000 picoseconds. + Weight::from_parts(58_816_000, 19894) .saturating_add(RocksDbWeight::get().reads(6_u64)) .saturating_add(RocksDbWeight::get().writes(6_u64)) } @@ -299,8 +350,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `388` // Estimated: `3514` - // Minimum execution time: 15_941_000 picoseconds. - Weight::from_parts(16_547_000, 3514) + // Minimum execution time: 14_527_000 picoseconds. + Weight::from_parts(14_948_000, 3514) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -318,8 +369,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `146` // Estimated: `3514` - // Minimum execution time: 24_963_000 picoseconds. - Weight::from_parts(25_873_000, 3514) + // Minimum execution time: 22_137_000 picoseconds. + Weight::from_parts(22_925_000, 3514) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(5_u64)) } @@ -341,11 +392,38 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `16931` // Estimated: `19894` - // Minimum execution time: 55_062_000 picoseconds. - Weight::from_parts(58_422_000, 19894) + // Minimum execution time: 51_837_000 picoseconds. + Weight::from_parts(52_810_000, 19894) .saturating_add(RocksDbWeight::get().reads(5_u64)) .saturating_add(RocksDbWeight::get().writes(6_u64)) } + /// Storage: `RankedCollective::Members` (r:1 w:1) + /// Proof: `RankedCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) + /// Storage: `CoreFellowship::Member` (r:1 w:1) + /// Proof: `CoreFellowship::Member` (`max_values`: None, `max_size`: Some(49), added: 2524, mode: `MaxEncodedLen`) + /// Storage: `RankedCollective::MemberCount` (r:9 w:9) + /// Proof: `RankedCollective::MemberCount` (`max_values`: None, `max_size`: Some(14), added: 2489, mode: `MaxEncodedLen`) + /// Storage: `CoreFellowship::MemberEvidence` (r:1 w:1) + /// Proof: `CoreFellowship::MemberEvidence` (`max_values`: None, `max_size`: Some(16429), added: 18904, mode: `MaxEncodedLen`) + /// Storage: `RankedCollective::IndexToId` (r:0 w:9) + /// Proof: `RankedCollective::IndexToId` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// Storage: `RankedCollective::IdToIndex` (r:0 w:9) + /// Proof: `RankedCollective::IdToIndex` (`max_values`: None, `max_size`: Some(54), added: 2529, mode: `MaxEncodedLen`) + /// The range of component `r` is `[1, 9]`. + fn promote_fast(r: u32, ) -> Weight { + // Proof Size summary in bytes: + // Measured: `16844` + // Estimated: `19894 + r * (2489 ยฑ0)` + // Minimum execution time: 45_065_000 picoseconds. + Weight::from_parts(34_090_392, 19894) + // Standard Error: 18_620 + .saturating_add(Weight::from_parts(13_578_046, 0).saturating_mul(r.into())) + .saturating_add(RocksDbWeight::get().reads(3_u64)) + .saturating_add(RocksDbWeight::get().reads((1_u64).saturating_mul(r.into()))) + .saturating_add(RocksDbWeight::get().writes(3_u64)) + .saturating_add(RocksDbWeight::get().writes((3_u64).saturating_mul(r.into()))) + .saturating_add(Weight::from_parts(0, 2489).saturating_mul(r.into())) + } /// Storage: `RankedCollective::Members` (r:1 w:0) /// Proof: `RankedCollective::Members` (`max_values`: None, `max_size`: Some(42), added: 2517, mode: `MaxEncodedLen`) /// Storage: `CoreFellowship::Member` (r:1 w:1) @@ -356,8 +434,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `293` // Estimated: `3514` - // Minimum execution time: 15_901_000 picoseconds. - Weight::from_parts(16_746_000, 3514) + // Minimum execution time: 14_321_000 picoseconds. + Weight::from_parts(14_747_000, 3514) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -369,8 +447,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `313` // Estimated: `3514` - // Minimum execution time: 14_768_000 picoseconds. - Weight::from_parts(15_421_000, 3514) + // Minimum execution time: 13_525_000 picoseconds. + Weight::from_parts(13_843_000, 3514) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } @@ -384,8 +462,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `16843` // Estimated: `19894` - // Minimum execution time: 36_925_000 picoseconds. - Weight::from_parts(38_330_000, 19894) + // Minimum execution time: 34_719_000 picoseconds. + Weight::from_parts(35_162_000, 19894) .saturating_add(RocksDbWeight::get().reads(3_u64)) .saturating_add(RocksDbWeight::get().writes(2_u64)) } @@ -397,8 +475,8 @@ impl WeightInfo for () { // Proof Size summary in bytes: // Measured: `79` // Estimated: `19894` - // Minimum execution time: 25_210_000 picoseconds. - Weight::from_parts(26_247_000, 19894) + // Minimum execution time: 23_477_000 picoseconds. + Weight::from_parts(23_897_000, 19894) .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(1_u64)) } diff --git a/substrate/frame/delegated-staking/Cargo.toml b/substrate/frame/delegated-staking/Cargo.toml index 3b122dc2e26c3c9d0f56f07427b037bd1cd388c0..0c1bcf0df0c5e3422367d64ec3c3d21e85f50e75 100644 --- a/substrate/frame/delegated-staking/Cargo.toml +++ b/substrate/frame/delegated-staking/Cargo.toml @@ -12,25 +12,25 @@ description = "FRAME delegated staking pallet" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } -sp-std = { path = "../../primitives/std", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-staking = { path = "../../primitives/staking", default-features = false } +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 } [dev-dependencies] -sp-core = { path = "../../primitives/core" } -sp-io = { path = "../../primitives/io" } -substrate-test-utils = { path = "../../test-utils" } -sp-tracing = { path = "../../primitives/tracing" } -pallet-staking = { path = "../staking" } -pallet-nomination-pools = { path = "../nomination-pools" } -pallet-balances = { path = "../balances" } -pallet-timestamp = { path = "../timestamp" } -pallet-staking-reward-curve = { path = "../staking/reward-curve" } -frame-election-provider-support = { path = "../election-provider-support", default-features = false } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +substrate-test-utils = { workspace = true } +sp-tracing = { workspace = true, default-features = true } +pallet-staking = { workspace = true, default-features = true } +pallet-nomination-pools = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +pallet-timestamp = { workspace = true, default-features = true } +pallet-staking-reward-curve = { workspace = true, default-features = true } +frame-election-provider-support = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/delegated-staking/src/mock.rs b/substrate/frame/delegated-staking/src/mock.rs index c1875055f2fec78ea80c908bb11379291efad4a8..811d5739f4e98f24c30c7514455dac049fbbc421 100644 --- a/substrate/frame/delegated-staking/src/mock.rs +++ b/substrate/frame/delegated-staking/src/mock.rs @@ -20,7 +20,7 @@ use frame_support::{ assert_ok, derive_impl, pallet_prelude::*, parameter_types, - traits::{ConstU64, Currency}, + traits::{ConstU64, Currency, VariantCountOf}, PalletId, }; @@ -44,7 +44,7 @@ pub const GENESIS_VALIDATOR: AccountId = 1; pub const GENESIS_NOMINATOR_ONE: AccountId = 101; pub const GENESIS_NOMINATOR_TWO: AccountId = 102; -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +#[derive_impl(frame_system::config_preludes::TestDefaultConfig)] impl frame_system::Config for Runtime { type Block = Block; type AccountData = pallet_balances::AccountData; @@ -64,19 +64,14 @@ pub type Balance = u128; parameter_types! { pub static ExistentialDeposit: Balance = 1; } + +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Runtime { - type MaxLocks = ConstU32<128>; - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type WeightInfo = (); type FreezeIdentifier = RuntimeFreezeReason; - type MaxFreezes = ConstU32<1>; - type RuntimeHoldReason = RuntimeHoldReason; + type MaxFreezes = VariantCountOf; type RuntimeFreezeReason = RuntimeFreezeReason; } @@ -93,7 +88,6 @@ pallet_staking_reward_curve::build! { parameter_types! { pub const RewardCurve: &'static sp_runtime::curve::PiecewiseLinear<'static> = &I_NPOS; - pub static BondingDuration: u32 = 3; pub static ElectionsBoundsOnChain: ElectionBounds = ElectionBoundsBuilder::default().build(); } pub struct OnChainSeqPhragmen; @@ -106,35 +100,17 @@ impl onchain::Config for OnChainSeqPhragmen { type Bounds = ElectionsBoundsOnChain; } +#[derive_impl(pallet_staking::config_preludes::TestDefaultConfig)] impl pallet_staking::Config for Runtime { type Currency = Balances; - type CurrencyBalance = Balance; type UnixTime = pallet_timestamp::Pallet; - type CurrencyToVote = (); - type RewardRemainder = (); - type RuntimeEvent = RuntimeEvent; - type Slash = (); - type Reward = (); - type SessionsPerEra = ConstU32<1>; - type SlashDeferDuration = (); type AdminOrigin = frame_system::EnsureRoot; - type BondingDuration = BondingDuration; - type SessionInterface = (); type EraPayout = pallet_staking::ConvertCurve; - type NextNewSession = (); - type HistoryDepth = ConstU32<84>; - type MaxExposurePageSize = ConstU32<64>; type ElectionProvider = onchain::OnChainExecution; type GenesisElectionProvider = Self::ElectionProvider; type VoterList = pallet_staking::UseNominatorsAndValidatorsMap; type TargetList = pallet_staking::UseValidatorsMap; - type NominationsQuota = pallet_staking::FixedNominationsQuota<16>; - type MaxUnlockingChunks = ConstU32<10>; - type MaxControllersInDeprecationBatch = ConstU32<100>; type EventListeners = (Pools, DelegatedStaking); - type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; - type WeightInfo = (); - type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; } parameter_types! { diff --git a/substrate/frame/delegated-staking/src/tests.rs b/substrate/frame/delegated-staking/src/tests.rs index d40539d40dddac6c517691bef58a41509949f421..2295f7d0c8719bdd8c57be1a341816bdc547baf9 100644 --- a/substrate/frame/delegated-staking/src/tests.rs +++ b/substrate/frame/delegated-staking/src/tests.rs @@ -501,17 +501,17 @@ mod staking_integration { ExtBuilder::default().build_and_execute(|| { start_era(1); let agent = 200; - setup_delegation_stake(agent, 201, (300..350).collect(), 100, 0); + setup_delegation_stake(agent, 201, (300..350).collect(), 320, 0); // verify withdraw not possible yet assert_noop!( - DelegatedStaking::release_delegation(RawOrigin::Signed(agent).into(), 300, 100, 0), + DelegatedStaking::release_delegation(RawOrigin::Signed(agent).into(), 300, 320, 0), Error::::NotEnoughFunds ); // fill up unlocking chunks in core staking. - // 10 is the max chunks - for i in 2..=11 { + // 32 is the max chunks + for i in 2..=33 { start_era(i); assert_ok!(Staking::unbond(RawOrigin::Signed(agent).into(), 10)); // no withdrawals from core staking yet. @@ -519,35 +519,35 @@ mod staking_integration { } // another unbond would trigger withdrawal - start_era(12); + start_era(34); assert_ok!(Staking::unbond(RawOrigin::Signed(agent).into(), 10)); - // 8 previous unbonds would be withdrawn as they were already unlocked. Unlocking period - // is 3 eras. - assert_eq!(get_agent_ledger(&agent).ledger.unclaimed_withdrawals, 8 * 10); + // 30 previous unbonds would be withdrawn as they were already unlocked. Unlocking + // period is 3 eras. + assert_eq!(get_agent_ledger(&agent).ledger.unclaimed_withdrawals, 30 * 10); // release some delegation now. assert_ok!(DelegatedStaking::release_delegation( RawOrigin::Signed(agent).into(), 300, - 40, + 160, 0 )); - assert_eq!(get_agent_ledger(&agent).ledger.unclaimed_withdrawals, 80 - 40); + assert_eq!(get_agent_ledger(&agent).ledger.unclaimed_withdrawals, 300 - 160); // cannot release more than available assert_noop!( - DelegatedStaking::release_delegation(RawOrigin::Signed(agent).into(), 300, 50, 0), + DelegatedStaking::release_delegation(RawOrigin::Signed(agent).into(), 300, 141, 0), Error::::NotEnoughFunds ); assert_ok!(DelegatedStaking::release_delegation( RawOrigin::Signed(agent).into(), 300, - 40, + 140, 0 )); - assert_eq!(DelegatedStaking::held_balance_of(Delegator::from(300)), 100 - 80); + assert_eq!(DelegatedStaking::held_balance_of(Delegator::from(300)), 320 - 300); }); } diff --git a/substrate/frame/democracy/Cargo.toml b/substrate/frame/democracy/Cargo.toml index 7f182447ead61a0b694b7dc21a888fd4480e1197..6a44951e09c4bbf1a64ccff0b60459aba5865193 100644 --- a/substrate/frame/democracy/Cargo.toml +++ b/substrate/frame/democracy/Cargo.toml @@ -16,24 +16,24 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", -] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +], workspace = true } +scale-info = { features = ["derive"], workspace = true } serde = { features = ["derive"], optional = true, workspace = true, default-features = true } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +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 } [dev-dependencies] -pallet-balances = { path = "../balances" } -pallet-scheduler = { path = "../scheduler" } -pallet-preimage = { path = "../preimage" } +pallet-balances = { workspace = true, default-features = true } +pallet-scheduler = { workspace = true, default-features = true } +pallet-preimage = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/democracy/src/tests.rs b/substrate/frame/democracy/src/tests.rs index 9303c0da504f366288f6f06cb33c54abbd125321..7d7066c8af691e7f7a8fe5cd8bfb7dec21d57e9b 100644 --- a/substrate/frame/democracy/src/tests.rs +++ b/substrate/frame/democracy/src/tests.rs @@ -108,20 +108,9 @@ impl pallet_scheduler::Config for Test { type Preimages = (); } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type MaxLocks = ConstU32<10>; - type Balance = u64; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ConstU64<1>; type AccountStore = System; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } parameter_types! { pub static PreimageByteDeposit: u64 = 0; diff --git a/substrate/frame/election-provider-multi-phase/Cargo.toml b/substrate/frame/election-provider-multi-phase/Cargo.toml index 43e3e7079d2fa78aa1e3515b41df87446ac5b370..941d720f2c6ca869cb8fdae55a27f009ad56e95a 100644 --- a/substrate/frame/election-provider-multi-phase/Cargo.toml +++ b/substrate/frame/election-provider-multi-phase/Cargo.toml @@ -15,40 +15,40 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", -] } -scale-info = { version = "2.11.1", default-features = false, features = [ +], workspace = true } +scale-info = { features = [ "derive", -] } +], workspace = true } log = { workspace = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } +frame-support = { workspace = true } +frame-system = { workspace = true } -sp-io = { path = "../../primitives/io", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-npos-elections = { path = "../../primitives/npos-elections", default-features = false } -sp-arithmetic = { path = "../../primitives/arithmetic", default-features = false } -frame-election-provider-support = { path = "../election-provider-support", default-features = false } +sp-io = { workspace = true } +sp-std = { workspace = true } +sp-core = { workspace = true } +sp-runtime = { workspace = true } +sp-npos-elections = { workspace = true } +sp-arithmetic = { workspace = true } +frame-election-provider-support = { workspace = true } # Optional imports for benchmarking -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -pallet-election-provider-support-benchmarking = { path = "../election-provider-support/benchmarking", default-features = false, optional = true } -rand = { version = "0.8.5", default-features = false, features = ["alloc", "small_rng"], optional = true } -strum = { version = "0.26.2", default-features = false, features = ["derive"], optional = true } +frame-benchmarking = { optional = true, workspace = true } +pallet-election-provider-support-benchmarking = { optional = true, workspace = true } +rand = { features = ["alloc", "small_rng"], optional = true, workspace = true } +strum = { features = ["derive"], optional = true, workspace = true } [dev-dependencies] -parking_lot = "0.12.1" -rand = "0.8.5" -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io" } -sp-npos-elections = { path = "../../primitives/npos-elections", default-features = false } -sp-tracing = { path = "../../primitives/tracing" } -pallet-balances = { path = "../balances" } -frame-benchmarking = { path = "../benchmarking" } +parking_lot = { workspace = true, default-features = true } +rand = { workspace = true, default-features = true } +sp-core = { workspace = true } +sp-io = { workspace = true, default-features = true } +sp-npos-elections = { workspace = true } +sp-tracing = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +frame-benchmarking = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/election-provider-multi-phase/src/mock.rs b/substrate/frame/election-provider-multi-phase/src/mock.rs index 92b87d92e99b16c959e9d719e91251da94fa7576..4532185b959c0ca59e6cfd4782f49b3773928b36 100644 --- a/substrate/frame/election-provider-multi-phase/src/mock.rs +++ b/substrate/frame/election-provider-multi-phase/src/mock.rs @@ -237,7 +237,6 @@ impl frame_system::Config for Runtime { const NORMAL_DISPATCH_RATIO: Perbill = Perbill::from_percent(75); parameter_types! { - pub const ExistentialDeposit: u64 = 1; pub BlockWeights: frame_system::limits::BlockWeights = frame_system::limits::BlockWeights ::with_sensible_defaults( Weight::from_parts(2u64 * constants::WEIGHT_REF_TIME_PER_SECOND, u64::MAX), @@ -245,20 +244,9 @@ parameter_types! { ); } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Runtime { - type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } #[derive(Default, Eq, PartialEq, Debug, Clone, Copy)] diff --git a/substrate/frame/election-provider-multi-phase/test-staking-e2e/Cargo.toml b/substrate/frame/election-provider-multi-phase/test-staking-e2e/Cargo.toml index fc696e04d689f706a4afa4459ea2b8f885ca22d4..77ecbb1af98f17a6f59351966ff855d5dcde9bbd 100644 --- a/substrate/frame/election-provider-multi-phase/test-staking-e2e/Cargo.toml +++ b/substrate/frame/election-provider-multi-phase/test-staking-e2e/Cargo.toml @@ -16,30 +16,30 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dev-dependencies] -parking_lot = "0.12.1" -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } -scale-info = { version = "2.11.1", features = ["derive"] } +parking_lot = { workspace = true, default-features = true } +codec = { features = ["derive"], workspace = true, default-features = true } +scale-info = { features = ["derive"], workspace = true, default-features = true } log = { workspace = true } -sp-runtime = { path = "../../../primitives/runtime" } -sp-io = { path = "../../../primitives/io" } -sp-std = { path = "../../../primitives/std" } -sp-staking = { path = "../../../primitives/staking" } -sp-core = { path = "../../../primitives/core" } -sp-npos-elections = { path = "../../../primitives/npos-elections", default-features = false } -sp-tracing = { path = "../../../primitives/tracing" } +sp-runtime = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-std = { workspace = true, default-features = true } +sp-staking = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-npos-elections = { workspace = true } +sp-tracing = { workspace = true, default-features = true } -frame-system = { path = "../../system" } -frame-support = { path = "../../support" } -frame-election-provider-support = { path = "../../election-provider-support" } +frame-system = { workspace = true, default-features = true } +frame-support = { workspace = true, default-features = true } +frame-election-provider-support = { workspace = true, default-features = true } -pallet-election-provider-multi-phase = { path = ".." } -pallet-staking = { path = "../../staking" } -pallet-nomination-pools = { path = "../../nomination-pools" } -pallet-bags-list = { path = "../../bags-list" } -pallet-balances = { path = "../../balances" } -pallet-timestamp = { path = "../../timestamp" } -pallet-session = { path = "../../session" } +pallet-election-provider-multi-phase = { workspace = true, default-features = true } +pallet-staking = { workspace = true, default-features = true } +pallet-nomination-pools = { workspace = true, default-features = true } +pallet-bags-list = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +pallet-timestamp = { workspace = true, default-features = true } +pallet-session = { workspace = true, default-features = true } [features] try-runtime = [ diff --git a/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/lib.rs b/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/lib.rs index 2b1f1335c6fe888c3ff756b00327b74d5ba9f279..aaffbb6681cd26b0bfb6af7c7a8d9e27fe5f06fa 100644 --- a/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/lib.rs +++ b/substrate/frame/election-provider-multi-phase/test-staking-e2e/src/lib.rs @@ -22,6 +22,7 @@ pub(crate) const LOG_TARGET: &str = "tests::e2e-epm"; use frame_support::{assert_err, assert_noop, assert_ok}; use mock::*; +use pallet_timestamp::Now; use sp_core::Get; use sp_runtime::Perbill; @@ -46,7 +47,7 @@ fn log_current_time() { Session::current_index(), Staking::current_era(), ElectionProviderMultiPhase::current_phase(), - Timestamp::now() + Now::::get() ); } @@ -209,7 +210,7 @@ fn continuous_slashes_below_offending_threshold() { // failed due to election minimum score. if start_next_active_era(pool_state.clone()).is_err() { assert!(ElectionProviderMultiPhase::current_phase().is_emergency()); - break + break; } active_validator_set = Session::validators(); 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 e5987ec33f06c3263edca88cf0fe7fbdda4ddcf5..bb1bdb31420565a104fb58b553b211411d7a3520 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 @@ -19,7 +19,7 @@ use frame_support::{ assert_ok, parameter_types, traits, - traits::{Hooks, UnfilteredDispatchable}, + traits::{Hooks, UnfilteredDispatchable, VariantCountOf}, weights::constants, }; use frame_system::EnsureRoot; @@ -102,20 +102,14 @@ parameter_types! { ); } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Runtime { - type MaxLocks = traits::ConstU32<1024>; - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type MaxFreezes = traits::ConstU32<1>; + type MaxFreezes = VariantCountOf; type RuntimeHoldReason = RuntimeHoldReason; type RuntimeFreezeReason = RuntimeFreezeReason; type FreezeIdentifier = RuntimeFreezeReason; - type WeightInfo = (); } impl pallet_timestamp::Config for Runtime { @@ -235,7 +229,6 @@ parameter_types! { pub const SessionsPerEra: sp_staking::SessionIndex = 2; pub static BondingDuration: sp_staking::EraIndex = 28; pub const SlashDeferDuration: sp_staking::EraIndex = 7; // 1/4 the bonding duration. - pub HistoryDepth: u32 = 84; } impl pallet_bags_list::Config for Runtime { @@ -291,15 +284,11 @@ const MAX_QUOTA_NOMINATIONS: u32 = 16; /// Disabling factor set explicitly to byzantine threshold pub(crate) const SLASHING_DISABLING_FACTOR: usize = 3; +#[derive_impl(pallet_staking::config_preludes::TestDefaultConfig)] impl pallet_staking::Config for Runtime { type Currency = Balances; type CurrencyBalance = Balance; type UnixTime = Timestamp; - type CurrencyToVote = (); - type RewardRemainder = (); - type RuntimeEvent = RuntimeEvent; - type Slash = (); // burn slashes - type Reward = (); // rewards are minted from the void type SessionsPerEra = SessionsPerEra; type BondingDuration = BondingDuration; type SlashDeferDuration = SlashDeferDuration; @@ -314,12 +303,10 @@ impl pallet_staking::Config for Runtime { type NominationsQuota = pallet_staking::FixedNominationsQuota; type TargetList = pallet_staking::UseValidatorsMap; type MaxUnlockingChunks = MaxUnlockingChunks; - type MaxControllersInDeprecationBatch = ConstU32<100>; - type HistoryDepth = HistoryDepth; type EventListeners = Pools; type WeightInfo = pallet_staking::weights::SubstrateWeight; - type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; + type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; } impl frame_system::offchain::SendTransactionTypes for Runtime diff --git a/substrate/frame/election-provider-support/Cargo.toml b/substrate/frame/election-provider-support/Cargo.toml index 1c63f90720f7b010fb584dc44f2e84ad78c61021..012392ffc59d9644181902ac3f5afbb6d444868f 100644 --- a/substrate/frame/election-provider-support/Cargo.toml +++ b/substrate/frame/election-provider-support/Cargo.toml @@ -15,21 +15,21 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-election-provider-solution-type = { path = "solution-type" } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-arithmetic = { path = "../../primitives/arithmetic", default-features = false } -sp-npos-elections = { path = "../../primitives/npos-elections", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } +frame-election-provider-solution-type = { workspace = true, default-features = true } +frame-support = { workspace = true } +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] -rand = { version = "0.8.5", features = ["small_rng"] } -sp-io = { path = "../../primitives/io" } -sp-npos-elections = { path = "../../primitives/npos-elections" } +rand = { features = ["small_rng"], workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-npos-elections = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/election-provider-support/benchmarking/Cargo.toml b/substrate/frame/election-provider-support/benchmarking/Cargo.toml index c2e644cfefab99145b839bf1c57917369a5f5cb2..ecf41ff9663bb94fb9feffa1991d6a90438d3952 100644 --- a/substrate/frame/election-provider-support/benchmarking/Cargo.toml +++ b/substrate/frame/election-provider-support/benchmarking/Cargo.toml @@ -15,15 +15,15 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", -] } -frame-benchmarking = { path = "../../benchmarking", default-features = false, optional = true } -frame-election-provider-support = { path = "..", default-features = false } -frame-system = { path = "../../system", default-features = false } -sp-npos-elections = { path = "../../../primitives/npos-elections", default-features = false } -sp-runtime = { path = "../../../primitives/runtime", default-features = false } -sp-std = { path = "../../../primitives/std", default-features = false } +], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +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"] diff --git a/substrate/frame/election-provider-support/solution-type/Cargo.toml b/substrate/frame/election-provider-support/solution-type/Cargo.toml index 0b631bd7bb035345a909a8911f4511f05d1b4f9b..a254f6c9b5b723065530fe53b4e045e1dfe94b92 100644 --- a/substrate/frame/election-provider-support/solution-type/Cargo.toml +++ b/substrate/frame/election-provider-support/solution-type/Cargo.toml @@ -20,14 +20,14 @@ proc-macro = true [dependencies] syn = { features = ["full", "visit"], workspace = true } quote = { workspace = true } -proc-macro2 = "1.0.56" -proc-macro-crate = "3.0.0" +proc-macro2 = { workspace = true } +proc-macro-crate = { workspace = true } [dev-dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12" } -scale-info = "2.11.1" -sp-arithmetic = { path = "../../../primitives/arithmetic" } +codec = { workspace = true, default-features = true } +scale-info = { workspace = true, default-features = true } +sp-arithmetic = { workspace = true, default-features = true } # used by generate_solution_type: -frame-election-provider-support = { path = ".." } -frame-support = { path = "../../support" } -trybuild = "1.0.88" +frame-election-provider-support = { workspace = true, default-features = true } +frame-support = { workspace = true, default-features = true } +trybuild = { workspace = true } diff --git a/substrate/frame/election-provider-support/solution-type/fuzzer/Cargo.toml b/substrate/frame/election-provider-support/solution-type/fuzzer/Cargo.toml index 98da507384fd956e21a01cf075556bbe0b6b916b..2c7a7aea1ca2b16982a69ed1e7af838256734056 100644 --- a/substrate/frame/election-provider-support/solution-type/fuzzer/Cargo.toml +++ b/substrate/frame/election-provider-support/solution-type/fuzzer/Cargo.toml @@ -16,19 +16,19 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -clap = { version = "4.5.3", features = ["derive"] } -honggfuzz = "0.5" -rand = { version = "0.8", features = ["small_rng", "std"] } +clap = { features = ["derive"], workspace = true } +honggfuzz = { workspace = true } +rand = { features = ["small_rng", "std"], workspace = true, default-features = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-election-provider-solution-type = { path = ".." } -frame-election-provider-support = { path = "../.." } -sp-arithmetic = { path = "../../../../primitives/arithmetic" } -sp-runtime = { path = "../../../../primitives/runtime" } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } +frame-election-provider-solution-type = { workspace = true, default-features = true } +frame-election-provider-support = { workspace = true, default-features = true } +sp-arithmetic = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } # used by generate_solution_type: -sp-npos-elections = { path = "../../../../primitives/npos-elections", default-features = false } -frame-support = { path = "../../../support" } +sp-npos-elections = { workspace = true } +frame-support = { workspace = true, default-features = true } [[bin]] name = "compact" diff --git a/substrate/frame/elections-phragmen/Cargo.toml b/substrate/frame/elections-phragmen/Cargo.toml index dbcb740518b1379f54cd4265973b445f53109b7b..b53118b6b6fd2d070427615968fbfa43ad0bf920 100644 --- a/substrate/frame/elections-phragmen/Cargo.toml +++ b/substrate/frame/elections-phragmen/Cargo.toml @@ -16,26 +16,26 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", -] } +], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-npos-elections = { path = "../../primitives/npos-elections", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -sp-staking = { path = "../../primitives/staking", default-features = false } +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +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] -pallet-balances = { path = "../balances" } -sp-core = { path = "../../primitives/core" } -sp-tracing = { path = "../../primitives/tracing" } -substrate-test-utils = { path = "../../test-utils" } +pallet-balances = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +substrate-test-utils = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/elections-phragmen/src/benchmarking.rs b/substrate/frame/elections-phragmen/src/benchmarking.rs index 55bb1b968fa1b11d0a34761b920b97bd7b20bae1..8e762f667b2a6a0d3b58916e93e91bb8fc56a67b 100644 --- a/substrate/frame/elections-phragmen/src/benchmarking.rs +++ b/substrate/frame/elections-phragmen/src/benchmarking.rs @@ -56,7 +56,7 @@ fn default_stake(num_votes: u32) -> BalanceOf { /// Get the current number of candidates. fn candidate_count() -> u32 { - >::decode_len().unwrap_or(0usize) as u32 + Candidates::::decode_len().unwrap_or(0usize) as u32 } /// Add `c` new candidates. @@ -67,7 +67,7 @@ fn submit_candidates( (0..c) .map(|i| { let account = endowed_account::(prefix, i); - >::submit_candidacy( + Elections::::submit_candidacy( RawOrigin::Signed(account.clone()).into(), candidate_count::(), ) @@ -96,7 +96,7 @@ fn submit_voter( votes: Vec, stake: BalanceOf, ) -> DispatchResultWithPostInfo { - >::vote(RawOrigin::Signed(caller).into(), votes, stake) + Elections::::vote(RawOrigin::Signed(caller).into(), votes, stake) } /// create `num_voter` voters who randomly vote for at most `votes` of `all_candidates` if @@ -121,28 +121,28 @@ fn distribute_voters( /// members, or members and runners-up. fn fill_seats_up_to(m: u32) -> Result, &'static str> { let _ = submit_candidates_with_self_vote::(m, "fill_seats_up_to")?; - assert_eq!(>::candidates().len() as u32, m, "wrong number of candidates."); - >::do_phragmen(); - assert_eq!(>::candidates().len(), 0, "some candidates remaining."); + assert_eq!(Candidates::::get().len() as u32, m, "wrong number of candidates."); + Elections::::do_phragmen(); + assert_eq!(Candidates::::get().len(), 0, "some candidates remaining."); assert_eq!( - >::members().len() + >::runners_up().len(), + Members::::get().len() + RunnersUp::::get().len(), m as usize, "wrong number of members and runners-up", ); - Ok(>::members() + Ok(Members::::get() .into_iter() .map(|m| m.who) - .chain(>::runners_up().into_iter().map(|r| r.who)) + .chain(RunnersUp::::get().into_iter().map(|r| r.who)) .collect()) } /// removes all the storage items to reverse any genesis state. fn clean() { - >::kill(); - >::kill(); - >::kill(); + Members::::kill(); + Candidates::::kill(); + RunnersUp::::kill(); #[allow(deprecated)] - >::remove_all(None); + Voting::::remove_all(None); } benchmarks! { @@ -180,14 +180,14 @@ benchmarks! { // original votes. let mut votes = all_candidates.iter().skip(1).cloned().collect::>(); - submit_voter::(caller.clone(), votes.clone(), stake / >::from(10u32))?; + submit_voter::(caller.clone(), votes.clone(), stake / BalanceOf::::from(10u32))?; // new votes. votes = all_candidates; - assert!(votes.len() > >::get(caller.clone()).votes.len()); + assert!(votes.len() > Voting::::get(caller.clone()).votes.len()); whitelist!(caller); - }: vote(RawOrigin::Signed(caller), votes, stake / >::from(10u32)) + }: vote(RawOrigin::Signed(caller), votes, stake / BalanceOf::::from(10u32)) vote_less { let v in 2 .. T::MaxVotesPerVoter::get(); @@ -205,7 +205,7 @@ benchmarks! { // new votes. votes = votes.into_iter().skip(1).collect::>(); - assert!(votes.len() < >::get(caller.clone()).votes.len()); + assert!(votes.len() < Voting::::get(caller.clone()).votes.len()); whitelist!(caller); }: vote(RawOrigin::Signed(caller), votes, stake) @@ -294,7 +294,7 @@ benchmarks! { let members_and_runners_up = fill_seats_up_to::(m)?; let bailing = members_and_runners_up[0].clone(); - assert!(>::is_member(&bailing)); + assert!(Elections::::is_member(&bailing)); whitelist!(bailing); }: renounce_candidacy(RawOrigin::Signed(bailing.clone()), Renouncing::Member) @@ -318,7 +318,7 @@ benchmarks! { let members_and_runners_up = fill_seats_up_to::(m)?; let bailing = members_and_runners_up[T::DesiredMembers::get() as usize + 1].clone(); - assert!(>::is_runner_up(&bailing)); + assert!(Elections::::is_runner_up(&bailing)); whitelist!(bailing); }: renounce_candidacy(RawOrigin::Signed(bailing.clone()), Renouncing::RunnerUp) @@ -345,11 +345,11 @@ benchmarks! { clean::(); let _ = fill_seats_up_to::(m)?; - let removing = as_lookup::(>::members_ids()[0].clone()); + let removing = as_lookup::(Elections::::members_ids()[0].clone()); }: remove_member(RawOrigin::Root, removing, true, false) verify { // must still have enough members. - assert_eq!(>::members().len() as u32, T::DesiredMembers::get()); + assert_eq!(Members::::get().len() as u32, T::DesiredMembers::get()); #[cfg(test)] { // reset members in between benchmark tests. @@ -371,15 +371,15 @@ benchmarks! { distribute_voters::(all_candidates, v, T::MaxVotesPerVoter::get() as usize)?; // all candidates leave. - >::kill(); + Candidates::::kill(); // now everyone is defunct - assert!(>::iter().all(|(_, v)| >::is_defunct_voter(&v.votes))); - assert_eq!(>::iter().count() as u32, v); + assert!(Voting::::iter().all(|(_, v)| Elections::::is_defunct_voter(&v.votes))); + assert_eq!(Voting::::iter().count() as u32, v); let root = RawOrigin::Root; }: _(root, v, d) verify { - assert_eq!(>::iter().count() as u32, v - d); + assert_eq!(Voting::::iter().count() as u32, v - d); } election_phragmen { @@ -404,12 +404,12 @@ benchmarks! { let all_candidates = submit_candidates_with_self_vote::(c, "candidates")?; let _ = distribute_voters::(all_candidates, v.saturating_sub(c), votes_per_voter as usize)?; }: { - >::on_initialize(T::TermDuration::get()); + Elections::::on_initialize(T::TermDuration::get()); } verify { - assert_eq!(>::members().len() as u32, T::DesiredMembers::get().min(c)); + assert_eq!(Members::::get().len() as u32, T::DesiredMembers::get().min(c)); assert_eq!( - >::runners_up().len() as u32, + RunnersUp::::get().len() as u32, T::DesiredRunnersUp::get().min(c.saturating_sub(T::DesiredMembers::get())), ); diff --git a/substrate/frame/elections-phragmen/src/lib.rs b/substrate/frame/elections-phragmen/src/lib.rs index b4be07030efbbf3d52405320830f86f524c9b0ad..c6eca40c47182321d5846d38f07408767fddd6f0 100644 --- a/substrate/frame/elections-phragmen/src/lib.rs +++ b/substrate/frame/elections-phragmen/src/lib.rs @@ -377,9 +377,9 @@ pub mod pallet { ); ensure!(!votes.is_empty(), Error::::NoVotes); - let candidates_count = >::decode_len().unwrap_or(0); - let members_count = >::decode_len().unwrap_or(0); - let runners_up_count = >::decode_len().unwrap_or(0); + let candidates_count = Candidates::::decode_len().unwrap_or(0); + let members_count = Members::::decode_len().unwrap_or(0); + let runners_up_count = RunnersUp::::decode_len().unwrap_or(0); // can never submit a vote of there are no members, and cannot submit more votes than // all potential vote targets. @@ -393,7 +393,7 @@ pub mod pallet { // Reserve bond. let new_deposit = Self::deposit_of(votes.len()); - let Voter { deposit: old_deposit, .. } = >::get(&who); + let Voter { deposit: old_deposit, .. } = Voting::::get(&who); match new_deposit.cmp(&old_deposit) { Ordering::Greater => { // Must reserve a bit more. @@ -455,7 +455,7 @@ pub mod pallet { ) -> DispatchResult { let who = ensure_signed(origin)?; - let actual_count = >::decode_len().unwrap_or(0) as u32; + let actual_count = Candidates::::decode_len().unwrap_or(0) as u32; ensure!(actual_count <= candidate_count, Error::::InvalidWitnessData); ensure!( actual_count <= ::MaxCandidates::get(), @@ -470,7 +470,7 @@ pub mod pallet { T::Currency::reserve(&who, T::CandidacyBond::get()) .map_err(|_| Error::::InsufficientCandidateFunds)?; - >::mutate(|c| c.insert(index, (who, T::CandidacyBond::get()))); + Candidates::::mutate(|c| c.insert(index, (who, T::CandidacyBond::get()))); Ok(()) } @@ -509,7 +509,7 @@ pub mod pallet { Self::deposit_event(Event::Renounced { candidate: who }); }, Renouncing::RunnerUp => { - >::try_mutate::<_, Error, _>(|runners_up| { + RunnersUp::::try_mutate::<_, Error, _>(|runners_up| { let index = runners_up .iter() .position(|SeatHolder { who: r, .. }| r == &who) @@ -523,7 +523,7 @@ pub mod pallet { })?; }, Renouncing::Candidate(count) => { - >::try_mutate::<_, Error, _>(|candidates| { + Candidates::::try_mutate::<_, Error, _>(|candidates| { ensure!(count >= candidates.len() as u32, Error::::InvalidWitnessData); let index = candidates .binary_search_by(|(c, _)| c.cmp(&who)) @@ -599,7 +599,7 @@ pub mod pallet { ) -> DispatchResult { let _ = ensure_root(origin)?; - >::iter() + Voting::::iter() .take(num_voters as usize) .filter(|(_, x)| Self::is_defunct_voter(&x.votes)) .take(num_defunct as usize) @@ -682,7 +682,6 @@ pub mod pallet { /// /// Invariant: Always sorted based on account id. #[pallet::storage] - #[pallet::getter(fn members)] pub type Members = StorageValue<_, Vec>>, ValueQuery>; @@ -691,7 +690,6 @@ pub mod pallet { /// Invariant: Always sorted based on rank (worse to best). Upon removal of a member, the /// last (i.e. _best_) runner-up will be replaced. #[pallet::storage] - #[pallet::getter(fn runners_up)] pub type RunnersUp = StorageValue<_, Vec>>, ValueQuery>; @@ -702,19 +700,16 @@ pub mod pallet { /// /// Invariant: Always sorted based on account id. #[pallet::storage] - #[pallet::getter(fn candidates)] pub type Candidates = StorageValue<_, Vec<(T::AccountId, BalanceOf)>, ValueQuery>; /// The total number of vote rounds that have happened, excluding the upcoming one. #[pallet::storage] - #[pallet::getter(fn election_rounds)] pub type ElectionRounds = StorageValue<_, u32, ValueQuery>; /// Votes and locked stake of a particular voter. /// /// TWOX-NOTE: SAFE as `AccountId` is a crypto hash. #[pallet::storage] - #[pallet::getter(fn voting)] pub type Voting = StorageMap<_, Twox64Concat, T::AccountId, Voter>, ValueQuery>; @@ -768,7 +763,7 @@ pub mod pallet { // they have any lock. NOTE: this means that we will still try to remove a lock // once this genesis voter is removed, and for now it is okay because // remove_lock is noop if lock is not there. - >::insert( + Voting::::insert( &member, Voter { votes: vec![member.clone()], stake: *stake, deposit: Zero::zero() }, ); @@ -811,7 +806,7 @@ impl Pallet { // - `Ok(Option(replacement))` if member was removed and replacement was replaced. // - `Ok(None)` if member was removed but no replacement was found // - `Err(_)` if who is not a member. - let maybe_replacement = >::try_mutate::<_, Error, _>(|members| { + let maybe_replacement = Members::::try_mutate::<_, Error, _>(|members| { let remove_index = members .binary_search_by(|m| m.who.cmp(who)) .map_err(|_| Error::::NotMember)?; @@ -831,7 +826,7 @@ impl Pallet { T::Currency::unreserve(who, removed.deposit); } - let maybe_next_best = >::mutate(|r| r.pop()).map(|next_best| { + let maybe_next_best = RunnersUp::::mutate(|r| r.pop()).map(|next_best| { // defensive-only: Members and runners-up are disjoint. This will always be err and // give us an index to insert. if let Err(index) = members.binary_search_by(|m| m.who.cmp(&next_best.who)) { @@ -847,7 +842,7 @@ impl Pallet { })?; let remaining_member_ids_sorted = - Self::members().into_iter().map(|x| x.who).collect::>(); + Members::::get().into_iter().map(|x| x.who).collect::>(); let outgoing = &[who.clone()]; let maybe_current_prime = T::ChangeMembers::get_prime(); let return_value = match maybe_replacement { @@ -884,7 +879,7 @@ impl Pallet { /// Check if `who` is a candidate. It returns the insert index if the element does not exists as /// an error. fn is_candidate(who: &T::AccountId) -> Result<(), usize> { - Self::candidates().binary_search_by(|c| c.0.cmp(who)).map(|_| ()) + Candidates::::get().binary_search_by(|c| c.0.cmp(who)).map(|_| ()) } /// Check if `who` is a voter. It may or may not be a _current_ one. @@ -894,17 +889,17 @@ impl Pallet { /// Check if `who` is currently an active member. fn is_member(who: &T::AccountId) -> bool { - Self::members().binary_search_by(|m| m.who.cmp(who)).is_ok() + Members::::get().binary_search_by(|m| m.who.cmp(who)).is_ok() } /// Check if `who` is currently an active runner-up. fn is_runner_up(who: &T::AccountId) -> bool { - Self::runners_up().iter().any(|r| &r.who == who) + RunnersUp::::get().iter().any(|r| &r.who == who) } /// Get the members' account ids. pub(crate) fn members_ids() -> Vec { - Self::members().into_iter().map(|m| m.who).collect::>() + Members::::get().into_iter().map(|m| m.who).collect::>() } /// Get a concatenation of previous members and runners-up and their deposits. @@ -912,10 +907,10 @@ impl Pallet { /// These accounts are essentially treated as candidates. fn implicit_candidates_with_deposit() -> Vec<(T::AccountId, BalanceOf)> { // invariant: these two are always without duplicates. - Self::members() + Members::::get() .into_iter() .map(|m| (m.who, m.deposit)) - .chain(Self::runners_up().into_iter().map(|r| (r.who, r.deposit))) + .chain(RunnersUp::::get().into_iter().map(|r| (r.who, r.deposit))) .collect::>() } @@ -932,7 +927,7 @@ impl Pallet { /// Remove a certain someone as a voter. fn do_remove_voter(who: &T::AccountId) { - let Voter { deposit, .. } = >::take(who); + let Voter { deposit, .. } = Voting::::take(who); // remove storage, lock and unreserve. T::Currency::remove_lock(T::PalletId::get(), who); @@ -952,7 +947,7 @@ impl Pallet { let desired_runners_up = T::DesiredRunnersUp::get() as usize; let num_to_elect = desired_runners_up + desired_seats; - let mut candidates_and_deposit = Self::candidates(); + let mut candidates_and_deposit = Candidates::::get(); // add all the previous members and runners-up as candidates as well. candidates_and_deposit.append(&mut Self::implicit_candidates_with_deposit()); @@ -1011,12 +1006,12 @@ impl Pallet { sp_npos_elections::seq_phragmen(num_to_elect, candidate_ids, voters_and_votes, None) .map(|ElectionResult:: { winners, assignments: _ }| { // this is already sorted by id. - let old_members_ids_sorted = >::take() + let old_members_ids_sorted = Members::::take() .into_iter() .map(|m| m.who) .collect::>(); // this one needs a sort by id. - let mut old_runners_up_ids_sorted = >::take() + let mut old_runners_up_ids_sorted = RunnersUp::::take() .into_iter() .map(|r| r.who) .collect::>(); @@ -1122,7 +1117,7 @@ impl Pallet { // fetch deposits from the one recorded one. This will make sure that a // candidate who submitted candidacy before a change to candidacy deposit will // have the correct amount recorded. - >::put( + Members::::put( new_members_sorted_by_id .iter() .map(|(who, stake)| SeatHolder { @@ -1132,7 +1127,7 @@ impl Pallet { }) .collect::>(), ); - >::put( + RunnersUp::::put( new_runners_up_sorted_by_rank .into_iter() .map(|(who, stake)| SeatHolder { @@ -1144,10 +1139,10 @@ impl Pallet { ); // clean candidates. - >::kill(); + Candidates::::kill(); Self::deposit_event(Event::NewTerm { new_members: new_members_sorted_by_id }); - >::mutate(|v| *v += 1); + ElectionRounds::::mutate(|v| *v += 1); }) .map_err(|e| { log::error!(target: LOG_TARGET, "Failed to run election [{:?}].", e,); @@ -1294,11 +1289,11 @@ impl Pallet { } fn candidates_ids() -> Vec { - Pallet::::candidates().iter().map(|(x, _)| x).cloned().collect::>() + Candidates::::get().iter().map(|(x, _)| x).cloned().collect::>() } fn runners_up_ids() -> Vec { - Pallet::::runners_up().into_iter().map(|r| r.who).collect::>() + RunnersUp::::get().into_iter().map(|r| r.who).collect::>() } } @@ -1310,7 +1305,7 @@ mod tests { assert_noop, assert_ok, derive_impl, dispatch::DispatchResultWithPostInfo, parameter_types, - traits::{ConstU32, ConstU64, OnInitialize}, + traits::{ConstU32, OnInitialize}, }; use frame_system::ensure_signed; use sp_runtime::{testing::Header, BuildStorage}; @@ -1322,20 +1317,9 @@ mod tests { type AccountData = pallet_balances::AccountData; } + #[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type Balance = u64; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ConstU64<1>; type AccountStore = frame_system::Pallet; - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } frame_support::parameter_types! { @@ -1511,22 +1495,22 @@ mod tests { } fn candidate_ids() -> Vec { - Elections::candidates().into_iter().map(|(c, _)| c).collect::>() + Candidates::::get().into_iter().map(|(c, _)| c).collect::>() } fn candidate_deposit(who: &u64) -> u64 { - Elections::candidates() + Candidates::::get() .into_iter() .find_map(|(c, d)| if c == *who { Some(d) } else { None }) .unwrap_or_default() } fn voter_deposit(who: &u64) -> u64 { - Elections::voting(who).deposit + Voting::::get(who).deposit } fn runners_up_ids() -> Vec { - Elections::runners_up().into_iter().map(|r| r.who).collect::>() + RunnersUp::::get().into_iter().map(|r| r.who).collect::>() } fn members_ids() -> Vec { @@ -1534,11 +1518,14 @@ mod tests { } fn members_and_stake() -> Vec<(u64, u64)> { - Elections::members().into_iter().map(|m| (m.who, m.stake)).collect::>() + elections_phragmen::Members::::get() + .into_iter() + .map(|m| (m.who, m.stake)) + .collect::>() } fn runners_up_and_stake() -> Vec<(u64, u64)> { - Elections::runners_up() + RunnersUp::::get() .into_iter() .map(|r| (r.who, r.stake)) .collect::>() @@ -1573,7 +1560,7 @@ mod tests { } fn submit_candidacy(origin: RuntimeOrigin) -> sp_runtime::DispatchResult { - Elections::submit_candidacy(origin, Elections::candidates().len() as u32) + Elections::submit_candidacy(origin, Candidates::::get().len() as u32) } fn vote(origin: RuntimeOrigin, votes: Vec, stake: u64) -> DispatchResultWithPostInfo { @@ -1597,13 +1584,13 @@ mod tests { assert_eq!(::VotingBondFactor::get(), 0); assert_eq!(::CandidacyBond::get(), 3); assert_eq!(::TermDuration::get(), 5); - assert_eq!(Elections::election_rounds(), 0); + assert_eq!(ElectionRounds::::get(), 0); - assert!(Elections::members().is_empty()); - assert!(Elections::runners_up().is_empty()); + assert!(elections_phragmen::Members::::get().is_empty()); + assert!(RunnersUp::::get().is_empty()); assert!(candidate_ids().is_empty()); - assert_eq!(>::decode_len(), None); + assert_eq!(Candidates::::decode_len(), None); assert!(Elections::is_candidate(&1).is_err()); assert!(all_voters().is_empty()); @@ -1618,7 +1605,7 @@ mod tests { .build_and_execute(|| { System::set_block_number(1); assert_eq!( - Elections::members(), + elections_phragmen::Members::::get(), vec![ SeatHolder { who: 1, stake: 10, deposit: 0 }, SeatHolder { who: 2, stake: 20, deposit: 0 } @@ -1626,11 +1613,11 @@ mod tests { ); assert_eq!( - Elections::voting(1), + Voting::::get(1), Voter { stake: 10u64, votes: vec![1], deposit: 0 } ); assert_eq!( - Elections::voting(2), + Voting::::get(2), Voter { stake: 20u64, votes: vec![2], deposit: 0 } ); @@ -1650,19 +1637,19 @@ mod tests { System::set_block_number(1); assert_eq!( - Elections::voting(1), + Voting::::get(1), Voter { stake: 10u64, votes: vec![1], deposit: 0 } ); assert_eq!( - Elections::voting(2), + Voting::::get(2), Voter { stake: 20u64, votes: vec![2], deposit: 0 } ); assert_ok!(Elections::remove_voter(RuntimeOrigin::signed(1))); assert_ok!(Elections::remove_voter(RuntimeOrigin::signed(2))); - assert_eq!(Elections::voting(1), Default::default()); - assert_eq!(Elections::voting(2), Default::default()); + assert_eq!(Voting::::get(1), Default::default()); + assert_eq!(Voting::::get(2), Default::default()); }) } @@ -1673,7 +1660,7 @@ mod tests { .build_and_execute(|| { System::set_block_number(1); assert_eq!( - Elections::members(), + elections_phragmen::Members::::get(), vec![ SeatHolder { who: 1, stake: 10, deposit: 0 }, SeatHolder { who: 2, stake: 20, deposit: 0 }, @@ -1681,11 +1668,11 @@ mod tests { ); assert_eq!( - Elections::voting(1), + Voting::::get(1), Voter { stake: 10u64, votes: vec![1], deposit: 0 } ); assert_eq!( - Elections::voting(2), + Voting::::get(2), Voter { stake: 20u64, votes: vec![2], deposit: 0 } ); @@ -1729,17 +1716,17 @@ mod tests { ExtBuilder::default().term_duration(0).build_and_execute(|| { assert_eq!(::TermDuration::get(), 0); assert_eq!(::DesiredMembers::get(), 2); - assert_eq!(Elections::election_rounds(), 0); + assert_eq!(ElectionRounds::::get(), 0); assert!(members_ids().is_empty()); - assert!(Elections::runners_up().is_empty()); + assert!(RunnersUp::::get().is_empty()); assert!(candidate_ids().is_empty()); System::set_block_number(5); Elections::on_initialize(System::block_number()); assert!(members_ids().is_empty()); - assert!(Elections::runners_up().is_empty()); + assert!(RunnersUp::::get().is_empty()); assert!(candidate_ids().is_empty()); }); } @@ -1780,14 +1767,14 @@ mod tests { ExtBuilder::default().build_and_execute(|| { assert_ok!(submit_candidacy(RuntimeOrigin::signed(5))); assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); - assert_eq!(Elections::candidates(), vec![(5, 3)]); + assert_eq!(Candidates::::get(), vec![(5, 3)]); // a runtime upgrade changes the bond. CANDIDACY_BOND.with(|v| *v.borrow_mut() = 4); assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); - assert_eq!(Elections::candidates(), vec![(4, 4), (5, 3)]); + assert_eq!(Candidates::::get(), vec![(4, 4), (5, 3)]); // once elected, they each hold their candidacy bond, no more. System::set_block_number(5); @@ -1796,7 +1783,7 @@ mod tests { assert_eq!(balances(&4), (34, 6)); assert_eq!(balances(&5), (45, 5)); assert_eq!( - Elections::members(), + elections_phragmen::Members::::get(), vec![ SeatHolder { who: 4, stake: 34, deposit: 4 }, SeatHolder { who: 5, stake: 45, deposit: 3 }, @@ -1845,7 +1832,7 @@ mod tests { Elections::on_initialize(System::block_number()); assert_eq!(members_ids(), vec![5]); - assert!(Elections::runners_up().is_empty()); + assert!(RunnersUp::::get().is_empty()); assert!(candidate_ids().is_empty()); assert_noop!(submit_candidacy(RuntimeOrigin::signed(5)), Error::::MemberSubmit); @@ -1971,7 +1958,7 @@ mod tests { // 2 + 1 assert_eq!(balances(&2), (17, 3)); - assert_eq!(Elections::voting(&2).deposit, 3); + assert_eq!(Voting::::get(&2).deposit, 3); assert_eq!(has_lock(&2), 10); assert_eq!(locked_stake_of(&2), 10); @@ -1979,7 +1966,7 @@ mod tests { assert_ok!(vote(RuntimeOrigin::signed(2), vec![5, 4], 15)); // 2 + 2 assert_eq!(balances(&2), (16, 4)); - assert_eq!(Elections::voting(&2).deposit, 4); + assert_eq!(Voting::::get(&2).deposit, 4); assert_eq!(has_lock(&2), 15); assert_eq!(locked_stake_of(&2), 15); @@ -1987,7 +1974,7 @@ mod tests { assert_ok!(vote(RuntimeOrigin::signed(2), vec![5, 3], 18)); // 2 + 2 assert_eq!(balances(&2), (16, 4)); - assert_eq!(Elections::voting(&2).deposit, 4); + assert_eq!(Voting::::get(&2).deposit, 4); assert_eq!(has_lock(&2), 16); assert_eq!(locked_stake_of(&2), 16); @@ -1995,7 +1982,7 @@ mod tests { assert_ok!(vote(RuntimeOrigin::signed(2), vec![4], 12)); // 2 + 1 assert_eq!(balances(&2), (17, 3)); - assert_eq!(Elections::voting(&2).deposit, 3); + assert_eq!(Voting::::get(&2).deposit, 3); assert_eq!(has_lock(&2), 12); assert_eq!(locked_stake_of(&2), 12); }); @@ -2273,9 +2260,9 @@ mod tests { assert_eq!(votes_of(&4), vec![4]); assert_eq!(candidate_ids(), vec![3, 4, 5]); - assert_eq!(>::decode_len().unwrap(), 3); + assert_eq!(Candidates::::decode_len().unwrap(), 3); - assert_eq!(Elections::election_rounds(), 0); + assert_eq!(ElectionRounds::::get(), 0); System::set_block_number(5); Elections::on_initialize(System::block_number()); @@ -2284,13 +2271,13 @@ mod tests { // votes for 5 assert_eq!(balances(&2), (18, 2)); assert_eq!(members_and_stake(), vec![(3, 25), (5, 18)]); - assert!(Elections::runners_up().is_empty()); + assert!(RunnersUp::::get().is_empty()); assert_eq_uvec!(all_voters(), vec![2, 3, 4]); assert!(candidate_ids().is_empty()); - assert_eq!(>::decode_len(), None); + assert_eq!(Candidates::::decode_len(), None); - assert_eq!(Elections::election_rounds(), 1); + assert_eq!(ElectionRounds::::get(), 1); }); } @@ -2353,7 +2340,7 @@ mod tests { Elections::on_initialize(System::block_number()); assert_eq!(members_and_stake(), vec![(5, 45)]); - assert_eq!(Elections::election_rounds(), 1); + assert_eq!(ElectionRounds::::get(), 1); // but now it has a valid target. assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); @@ -2363,7 +2350,7 @@ mod tests { // candidate 4 is affected by an old vote. assert_eq!(members_and_stake(), vec![(4, 28), (5, 45)]); - assert_eq!(Elections::election_rounds(), 2); + assert_eq!(ElectionRounds::::get(), 2); assert_eq_uvec!(all_voters(), vec![3, 5]); }); } @@ -2384,7 +2371,7 @@ mod tests { System::set_block_number(5); Elections::on_initialize(System::block_number()); - assert_eq!(Elections::election_rounds(), 1); + assert_eq!(ElectionRounds::::get(), 1); assert_eq!(members_ids(), vec![4, 5]); }); } @@ -2399,7 +2386,7 @@ mod tests { Elections::on_initialize(System::block_number()); assert!(candidate_ids().is_empty()); - assert_eq!(Elections::election_rounds(), 1); + assert_eq!(ElectionRounds::::get(), 1); assert!(members_ids().is_empty()); System::assert_last_event(RuntimeEvent::Elections(super::Event::NewTerm { @@ -2553,7 +2540,7 @@ mod tests { Elections::on_initialize(System::block_number()); assert_eq!(members_ids(), vec![4, 5]); - assert_eq!(Elections::election_rounds(), 1); + assert_eq!(ElectionRounds::::get(), 1); assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); assert_ok!(vote(RuntimeOrigin::signed(2), vec![2], 20)); @@ -2597,7 +2584,7 @@ mod tests { assert_eq!(runners_up_and_stake(), vec![(2, 15), (3, 25)]); // no new candidates but old members and runners-up are always added. assert!(candidate_ids().is_empty()); - assert_eq!(Elections::election_rounds(), b / 5); + assert_eq!(ElectionRounds::::get(), b / 5); assert_eq_uvec!(all_voters(), vec![2, 3, 4, 5]); }; @@ -2621,7 +2608,7 @@ mod tests { System::set_block_number(5); Elections::on_initialize(System::block_number()); assert_eq!(members_ids(), vec![4, 5]); - assert_eq!(Elections::election_rounds(), 1); + assert_eq!(ElectionRounds::::get(), 1); // a new candidate assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); @@ -2630,7 +2617,7 @@ mod tests { assert_ok!(Elections::remove_member(RuntimeOrigin::root(), 4, true, true)); assert_eq!(balances(&4), (35, 2)); // slashed - assert_eq!(Elections::election_rounds(), 2); // new election round + assert_eq!(ElectionRounds::::get(), 2); // new election round assert_eq!(members_ids(), vec![3, 5]); // new members }); } @@ -2647,14 +2634,14 @@ mod tests { assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); assert_ok!(vote(RuntimeOrigin::signed(5), vec![5], 50)); - assert_eq!(>::decode_len().unwrap(), 3); + assert_eq!(Candidates::::decode_len().unwrap(), 3); - assert_eq!(Elections::election_rounds(), 0); + assert_eq!(ElectionRounds::::get(), 0); System::set_block_number(5); Elections::on_initialize(System::block_number()); assert_eq!(members_ids(), vec![3, 5]); - assert_eq!(Elections::election_rounds(), 1); + assert_eq!(ElectionRounds::::get(), 1); assert_ok!(Elections::remove_voter(RuntimeOrigin::signed(2))); assert_ok!(Elections::remove_voter(RuntimeOrigin::signed(3))); @@ -2665,7 +2652,7 @@ mod tests { System::set_block_number(10); Elections::on_initialize(System::block_number()); assert!(members_ids().is_empty()); - assert_eq!(Elections::election_rounds(), 2); + assert_eq!(ElectionRounds::::get(), 2); }); } @@ -2730,7 +2717,7 @@ mod tests { Elections::on_initialize(System::block_number()); assert_eq_uvec!(members_ids(), vec![3, 4]); - assert_eq!(Elections::election_rounds(), 1); + assert_eq!(ElectionRounds::::get(), 1); }); } @@ -3175,13 +3162,13 @@ mod tests { .desired_members(0) .desired_runners_up(0) .build_and_execute(|| { - assert_eq!(Elections::candidates().len(), 0); + assert_eq!(Candidates::::get().len(), 0); assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); - assert_eq!(Elections::candidates().len(), 3); + assert_eq!(Candidates::::get().len(), 3); assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); @@ -3193,7 +3180,7 @@ mod tests { assert_eq!(members_ids().len(), 0); assert_eq!(runners_up_ids().len(), 0); assert_eq!(all_voters().len(), 3); - assert_eq!(Elections::candidates().len(), 0); + assert_eq!(Candidates::::get().len(), 0); }); // not interested in members @@ -3201,13 +3188,13 @@ mod tests { .desired_members(0) .desired_runners_up(2) .build_and_execute(|| { - assert_eq!(Elections::candidates().len(), 0); + assert_eq!(Candidates::::get().len(), 0); assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); - assert_eq!(Elections::candidates().len(), 3); + assert_eq!(Candidates::::get().len(), 3); assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); @@ -3219,7 +3206,7 @@ mod tests { assert_eq!(members_ids().len(), 0); assert_eq!(runners_up_ids(), vec![3, 4]); assert_eq!(all_voters().len(), 3); - assert_eq!(Elections::candidates().len(), 0); + assert_eq!(Candidates::::get().len(), 0); }); // not interested in runners-up @@ -3227,13 +3214,13 @@ mod tests { .desired_members(2) .desired_runners_up(0) .build_and_execute(|| { - assert_eq!(Elections::candidates().len(), 0); + assert_eq!(Candidates::::get().len(), 0); assert_ok!(submit_candidacy(RuntimeOrigin::signed(4))); assert_ok!(submit_candidacy(RuntimeOrigin::signed(3))); assert_ok!(submit_candidacy(RuntimeOrigin::signed(2))); - assert_eq!(Elections::candidates().len(), 3); + assert_eq!(Candidates::::get().len(), 3); assert_ok!(vote(RuntimeOrigin::signed(4), vec![4], 40)); assert_ok!(vote(RuntimeOrigin::signed(3), vec![3], 30)); @@ -3245,7 +3232,7 @@ mod tests { assert_eq!(members_ids(), vec![3, 4]); assert_eq!(runners_up_ids().len(), 0); assert_eq!(all_voters().len(), 3); - assert_eq!(Elections::candidates().len(), 0); + assert_eq!(Candidates::::get().len(), 0); }); } diff --git a/substrate/frame/elections-phragmen/src/migrations/v3.rs b/substrate/frame/elections-phragmen/src/migrations/v3.rs index cdca1138ebbd2f9de20ebcfaf9e39fb313850347..b0092d6c07bb647f077fa336201e48f575ae9b9b 100644 --- a/substrate/frame/elections-phragmen/src/migrations/v3.rs +++ b/substrate/frame/elections-phragmen/src/migrations/v3.rs @@ -116,16 +116,16 @@ pub fn apply( /// Migrate from the old legacy voting bond (fixed) to the new one (per-vote dynamic). pub fn migrate_voters_to_recorded_deposit(old_deposit: V::Balance) { - >::translate::<(V::Balance, Vec), _>(|_who, (stake, votes)| { + Voting::::translate::<(V::Balance, Vec), _>(|_who, (stake, votes)| { Some(Voter { votes, stake, deposit: old_deposit }) }); - log::info!(target: LOG_TARGET, "migrated {} voter accounts.", >::iter().count()); + log::info!(target: LOG_TARGET, "migrated {} voter accounts.", Voting::::iter().count()); } /// Migrate all candidates to recorded deposit. pub fn migrate_candidates_to_recorded_deposit(old_deposit: V::Balance) { - let _ = >::translate::, _>(|maybe_old_candidates| { + let _ = Candidates::::translate::, _>(|maybe_old_candidates| { maybe_old_candidates.map(|old_candidates| { log::info!(target: LOG_TARGET, "migrated {} candidate accounts.", old_candidates.len()); old_candidates.into_iter().map(|c| (c, old_deposit)).collect::>() @@ -135,7 +135,7 @@ pub fn migrate_candidates_to_recorded_deposit(old_deposit: /// Migrate all members to recorded deposit. pub fn migrate_members_to_recorded_deposit(old_deposit: V::Balance) { - let _ = >::translate::, _>(|maybe_old_members| { + let _ = Members::::translate::, _>(|maybe_old_members| { maybe_old_members.map(|old_members| { log::info!(target: LOG_TARGET, "migrated {} member accounts.", old_members.len()); old_members @@ -148,7 +148,7 @@ pub fn migrate_members_to_recorded_deposit(old_deposit: V: /// Migrate all runners-up to recorded deposit. pub fn migrate_runners_up_to_recorded_deposit(old_deposit: V::Balance) { - let _ = >::translate::, _>( + let _ = RunnersUp::::translate::, _>( |maybe_old_runners_up| { maybe_old_runners_up.map(|old_runners_up| { log::info!( diff --git a/substrate/frame/examples/Cargo.toml b/substrate/frame/examples/Cargo.toml index 45c7440eb89135eca98cf00a4aaf5d6ad2c094ca..0bb42517eb46748e53c79873b41117d3795f3bd2 100644 --- a/substrate/frame/examples/Cargo.toml +++ b/substrate/frame/examples/Cargo.toml @@ -16,15 +16,15 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -pallet-default-config-example = { path = "default-config", default-features = false } -pallet-dev-mode = { path = "dev-mode", default-features = false } -pallet-example-basic = { path = "basic", default-features = false } -pallet-example-frame-crate = { path = "frame-crate", default-features = false } -pallet-example-kitchensink = { path = "kitchensink", default-features = false } -pallet-example-offchain-worker = { path = "offchain-worker", default-features = false } -pallet-example-split = { path = "split", default-features = false } -pallet-example-single-block-migrations = { path = "single-block-migrations", default-features = false } -pallet-example-tasks = { path = "tasks", default-features = false } +pallet-default-config-example = { workspace = true } +pallet-dev-mode = { workspace = true } +pallet-example-basic = { workspace = true } +pallet-example-frame-crate = { workspace = true } +pallet-example-kitchensink = { workspace = true } +pallet-example-offchain-worker = { workspace = true } +pallet-example-split = { workspace = true } +pallet-example-single-block-migrations = { workspace = true } +pallet-example-tasks = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/examples/basic/Cargo.toml b/substrate/frame/examples/basic/Cargo.toml index ba9f9eca27d79c854dd67a8d81130062f3d1f70d..b34d9efc15b7fef9285eb7ecf741f677d47e472a 100644 --- a/substrate/frame/examples/basic/Cargo.toml +++ b/substrate/frame/examples/basic/Cargo.toml @@ -8,6 +8,7 @@ homepage = "https://substrate.io" repository.workspace = true description = "FRAME example pallet" readme = "README.md" +publish = false [lints] workspace = true @@ -16,19 +17,19 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } +codec = { workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../../benchmarking", default-features = false, optional = true } -frame-support = { path = "../../support", default-features = false } -frame-system = { path = "../../system", default-features = false } -pallet-balances = { path = "../../balances", default-features = false } -sp-io = { path = "../../../primitives/io", default-features = false } -sp-runtime = { path = "../../../primitives/runtime", default-features = false } -sp-std = { path = "../../../primitives/std", default-features = false } +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-balances = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -sp-core = { path = "../../../primitives/core", default-features = false } +sp-core = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/examples/basic/src/tests.rs b/substrate/frame/examples/basic/src/tests.rs index d351b27eecde3c506e17339f9f7300d522fcc87f..505cd6f906de23bb5045834125201cc51c613217 100644 --- a/substrate/frame/examples/basic/src/tests.rs +++ b/substrate/frame/examples/basic/src/tests.rs @@ -71,20 +71,9 @@ impl frame_system::Config for Test { type MaxConsumers = frame_support::traits::ConstU32<16>; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type Balance = u64; - type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; - type ExistentialDeposit = ConstU64<1>; type AccountStore = System; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } impl Config for Test { diff --git a/substrate/frame/examples/default-config/Cargo.toml b/substrate/frame/examples/default-config/Cargo.toml index 0ad5b56cb6faa473d337f54fe7eaedaf31a70d9d..8a0d14edbdbf386c64a675ad33885de632d753a3 100644 --- a/substrate/frame/examples/default-config/Cargo.toml +++ b/substrate/frame/examples/default-config/Cargo.toml @@ -8,6 +8,7 @@ homepage = "https://substrate.io" repository.workspace = true description = "FRAME example pallet demonstrating derive_impl / default_config in action" readme = "README.md" +publish = false [lints] workspace = true @@ -16,15 +17,15 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } +codec = { workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-support = { path = "../../support", default-features = false } -frame-system = { path = "../../system", default-features = false } +scale-info = { features = ["derive"], workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } -sp-io = { path = "../../../primitives/io", default-features = false } -sp-runtime = { path = "../../../primitives/runtime", default-features = false } -sp-std = { path = "../../../primitives/std", default-features = false } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/examples/dev-mode/Cargo.toml b/substrate/frame/examples/dev-mode/Cargo.toml index d7570f570946f1df05665ad8804e62ad9c18030a..1dd033d7e071e29027109f624cbc613f542e9575 100644 --- a/substrate/frame/examples/dev-mode/Cargo.toml +++ b/substrate/frame/examples/dev-mode/Cargo.toml @@ -16,18 +16,18 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } +codec = { workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-support = { path = "../../support", default-features = false } -frame-system = { path = "../../system", default-features = false } -pallet-balances = { path = "../../balances", default-features = false } -sp-io = { path = "../../../primitives/io", default-features = false } -sp-runtime = { path = "../../../primitives/runtime", default-features = false } -sp-std = { path = "../../../primitives/std", default-features = false } +scale-info = { features = ["derive"], workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-balances = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -sp-core = { path = "../../../primitives/core", default-features = false } +sp-core = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/examples/dev-mode/src/tests.rs b/substrate/frame/examples/dev-mode/src/tests.rs index e8a18ec13fe912497e32a821e4f10d75582609e1..637864b87bc43d9e4e55cd9fe4f054cf5efd1ca8 100644 --- a/substrate/frame/examples/dev-mode/src/tests.rs +++ b/substrate/frame/examples/dev-mode/src/tests.rs @@ -18,7 +18,7 @@ //! Tests for pallet-dev-mode. use crate::*; -use frame_support::{assert_ok, derive_impl, traits::ConstU64}; +use frame_support::{assert_ok, derive_impl}; use sp_core::H256; use sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, @@ -65,20 +65,9 @@ impl frame_system::Config for Test { type MaxConsumers = frame_support::traits::ConstU32<16>; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type Balance = u64; - type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; - type ExistentialDeposit = ConstU64<1>; type AccountStore = System; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeFreezeReason; } impl Config for Test { diff --git a/substrate/frame/examples/frame-crate/Cargo.toml b/substrate/frame/examples/frame-crate/Cargo.toml index 29984bab3e0ffc5ac881eb086d91820c01e7d504..e5137526026e6f69d11408541686039a9f804c62 100644 --- a/substrate/frame/examples/frame-crate/Cargo.toml +++ b/substrate/frame/examples/frame-crate/Cargo.toml @@ -16,10 +16,10 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { workspace = true } +scale-info = { features = ["derive"], workspace = true } -frame = { package = "polkadot-sdk-frame", path = "../..", default-features = false, features = ["experimental", "runtime"] } +frame = { features = ["experimental", "runtime"], workspace = true } [features] diff --git a/substrate/frame/examples/kitchensink/Cargo.toml b/substrate/frame/examples/kitchensink/Cargo.toml index db3e22daa01bd044cae876aabeac25543e814dcb..b3869dff94142de172340ce7f02b701389d1b5a5 100644 --- a/substrate/frame/examples/kitchensink/Cargo.toml +++ b/substrate/frame/examples/kitchensink/Cargo.toml @@ -16,23 +16,23 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } +codec = { workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } -frame-support = { path = "../../support", default-features = false, features = ["experimental"] } -frame-system = { path = "../../system", default-features = false } +frame-support = { features = ["experimental"], workspace = true } +frame-system = { workspace = true } -sp-io = { path = "../../../primitives/io", default-features = false } -sp-runtime = { path = "../../../primitives/runtime", default-features = false } -sp-std = { path = "../../../primitives/std", default-features = false } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } -frame-benchmarking = { path = "../../benchmarking", default-features = false, optional = true } +frame-benchmarking = { optional = true, workspace = true } -pallet-balances = { path = "../../balances", default-features = false } +pallet-balances = { workspace = true } [dev-dependencies] -sp-core = { path = "../../../primitives/core", default-features = false } +sp-core = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/examples/kitchensink/src/tests.rs b/substrate/frame/examples/kitchensink/src/tests.rs index 1205fefc422983d2b6f621b601a96b786353f83a..7cf95497bf06408b0aae5543513a81a3316ddeaa 100644 --- a/substrate/frame/examples/kitchensink/src/tests.rs +++ b/substrate/frame/examples/kitchensink/src/tests.rs @@ -18,7 +18,7 @@ //! Tests for pallet-example-kitchensink. use crate::*; -use frame_support::{assert_ok, derive_impl, parameter_types, traits::ConstU64}; +use frame_support::{assert_ok, derive_impl, parameter_types, traits::VariantCountOf}; use sp_runtime::BuildStorage; // Reexport crate as its pallet name for construct_runtime. use crate as pallet_example_kitchensink; @@ -43,20 +43,14 @@ impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type Balance = u64; - type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; - type ExistentialDeposit = ConstU64<1>; type AccountStore = System; type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); + type FreezeIdentifier = RuntimeFreezeReason; + type MaxFreezes = VariantCountOf; + type RuntimeHoldReason = RuntimeHoldReason; + type RuntimeFreezeReason = RuntimeFreezeReason; } parameter_types! { diff --git a/substrate/frame/examples/multi-block-migrations/Cargo.toml b/substrate/frame/examples/multi-block-migrations/Cargo.toml index 61bb2bc61b4e3758fc47c413f35ac5420bbfb4ef..91d0a71bb34153eacaff87356336ebcf10db3674 100644 --- a/substrate/frame/examples/multi-block-migrations/Cargo.toml +++ b/substrate/frame/examples/multi-block-migrations/Cargo.toml @@ -13,14 +13,14 @@ publish = false targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -pallet-migrations = { path = "../../migrations", default-features = false } -frame-support = { path = "../../support", default-features = false } -frame-system = { path = "../../system", default-features = false } -frame-benchmarking = { path = "../../benchmarking", default-features = false, optional = true } -log = { version = "0.4.20", default-features = false } -scale-info = { version = "2.10.0", default-features = false } -sp-io = { path = "../../../primitives/io", default-features = false } +codec = { workspace = true } +pallet-migrations = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +frame-benchmarking = { optional = true, workspace = true } +log = { workspace = true } +scale-info = { workspace = true } +sp-io = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/examples/offchain-worker/Cargo.toml b/substrate/frame/examples/offchain-worker/Cargo.toml index 23ce79c34402da91cea1f1e02ae7ebd90dc6e5d3..f8ccd1f04e47534857894a6a5a1c497d48eb446b 100644 --- a/substrate/frame/examples/offchain-worker/Cargo.toml +++ b/substrate/frame/examples/offchain-worker/Cargo.toml @@ -8,6 +8,7 @@ homepage = "https://substrate.io" repository.workspace = true description = "FRAME example pallet for offchain worker" readme = "README.md" +publish = false [lints] workspace = true @@ -16,17 +17,17 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -lite-json = { version = "0.2.0", default-features = false } +codec = { workspace = true } +lite-json = { workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-support = { path = "../../support", default-features = false } -frame-system = { path = "../../system", default-features = false } -sp-core = { path = "../../../primitives/core", default-features = false } -sp-io = { path = "../../../primitives/io", default-features = false } -sp-keystore = { path = "../../../primitives/keystore", optional = true, default-features = false } -sp-runtime = { path = "../../../primitives/runtime", default-features = false } -sp-std = { path = "../../../primitives/std", default-features = false } +scale-info = { features = ["derive"], workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +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"] diff --git a/substrate/frame/examples/single-block-migrations/Cargo.toml b/substrate/frame/examples/single-block-migrations/Cargo.toml index 080500f629671837316e724b6825493c3fcb4b67..a6cf020ce535d96cb81b9f93955bbbf795a62e34 100644 --- a/substrate/frame/examples/single-block-migrations/Cargo.toml +++ b/substrate/frame/examples/single-block-migrations/Cargo.toml @@ -13,20 +13,20 @@ publish = false targets = ["x86_64-unknown-linux-gnu"] [dependencies] -docify = "0.2.8" -log = { version = "0.4.21", default-features = false } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-support = { path = "../../support", default-features = false } -frame-executive = { path = "../../executive", default-features = false } -frame-system = { path = "../../system", default-features = false } -frame-try-runtime = { path = "../../try-runtime", default-features = false, optional = true } -pallet-balances = { path = "../../balances", default-features = false } -sp-std = { path = "../../../primitives/std", default-features = false } -sp-runtime = { path = "../../../primitives/runtime", default-features = false } -sp-core = { path = "../../../primitives/core", default-features = false } -sp-io = { path = "../../../primitives/io", default-features = false } -sp-version = { path = "../../../primitives/version", default-features = false } +docify = { workspace = true } +log = { workspace = true } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } +frame-support = { workspace = true } +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 } +sp-version = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/examples/single-block-migrations/src/mock.rs b/substrate/frame/examples/single-block-migrations/src/mock.rs index 68594cc4ad727a18f97b5d8b55381d36d1e7aeed..f4cf81ea6474f2971c08b1174e276fe0b7b9a0f0 100644 --- a/substrate/frame/examples/single-block-migrations/src/mock.rs +++ b/substrate/frame/examples/single-block-migrations/src/mock.rs @@ -18,7 +18,7 @@ #![cfg(any(all(feature = "try-runtime", test), doc))] use crate::*; -use frame_support::{derive_impl, traits::ConstU64, weights::constants::ParityDbWeight}; +use frame_support::{derive_impl, weights::constants::ParityDbWeight}; // Re-export crate as its pallet name for construct_runtime. use crate as pallet_example_storage_migration; @@ -41,20 +41,9 @@ impl frame_system::Config for MockRuntime { type DbWeight = ParityDbWeight; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for MockRuntime { - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeFreezeReason; - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type Balance = u64; - type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; - type ExistentialDeposit = ConstU64<1>; type AccountStore = System; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); } impl Config for MockRuntime {} diff --git a/substrate/frame/examples/split/Cargo.toml b/substrate/frame/examples/split/Cargo.toml index 6cb4d7ddd6c06951b749d796746a7f5a63ee343f..d8a8c6869ab5f78b16a793e544face8866d24b8d 100644 --- a/substrate/frame/examples/split/Cargo.toml +++ b/substrate/frame/examples/split/Cargo.toml @@ -8,6 +8,7 @@ homepage = "https://substrate.io" repository.workspace = true description = "FRAME example split pallet" readme = "README.md" +publish = false [lints] workspace = true @@ -16,20 +17,20 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } +codec = { workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } -frame-support = { path = "../../support", default-features = false } -frame-system = { path = "../../system", default-features = false } +frame-support = { workspace = true } +frame-system = { workspace = true } -sp-io = { path = "../../../primitives/io", default-features = false } -sp-std = { path = "../../../primitives/std", default-features = false } +sp-io = { workspace = true } +sp-std = { workspace = true } -frame-benchmarking = { path = "../../benchmarking", default-features = false, optional = true } +frame-benchmarking = { optional = true, workspace = true } [dev-dependencies] -sp-core = { path = "../../../primitives/core", default-features = false } +sp-core = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/examples/tasks/Cargo.toml b/substrate/frame/examples/tasks/Cargo.toml index 95246ef3f6643aafe215bb4bacf0e2e2598149ae..1ca62fd89943ec729af9a2c059b1b434fe274ce8 100644 --- a/substrate/frame/examples/tasks/Cargo.toml +++ b/substrate/frame/examples/tasks/Cargo.toml @@ -6,6 +6,7 @@ edition.workspace = true license.workspace = true repository.workspace = true description = "Pallet to demonstrate the usage of Tasks to recognize and execute service work" +publish = false [lints] workspace = true @@ -14,19 +15,19 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } +codec = { workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } -frame-support = { path = "../../support", default-features = false } -frame-system = { path = "../../system", default-features = false } +frame-support = { workspace = true } +frame-system = { workspace = true } -sp-io = { path = "../../../primitives/io", default-features = false } -sp-runtime = { path = "../../../primitives/runtime", default-features = false } -sp-std = { path = "../../../primitives/std", default-features = false } -sp-core = { default-features = false, path = "../../../primitives/core" } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } +sp-core = { workspace = true } -frame-benchmarking = { path = "../../benchmarking", default-features = false, optional = true } +frame-benchmarking = { optional = true, workspace = true } [features] default = ["std"] diff --git a/substrate/frame/executive/Cargo.toml b/substrate/frame/executive/Cargo.toml index 4cce0fa9f9504ae48ca1929f87311896b81ca5cf..0f9741eec180d172c24434d587d723735551148c 100644 --- a/substrate/frame/executive/Cargo.toml +++ b/substrate/frame/executive/Cargo.toml @@ -16,29 +16,29 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -aquamarine = "0.5.0" -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +aquamarine = { workspace = true } +codec = { features = [ "derive", -] } +], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -frame-try-runtime = { path = "../try-runtime", default-features = false, optional = true } -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -sp-tracing = { path = "../../primitives/tracing", default-features = false } +scale-info = { features = ["derive"], workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +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] -array-bytes = "6.2.2" -pallet-balances = { path = "../balances" } -pallet-transaction-payment = { path = "../transaction-payment" } -sp-core = { path = "../../primitives/core" } -sp-inherents = { path = "../../primitives/inherents" } -sp-io = { path = "../../primitives/io" } -sp-version = { path = "../../primitives/version" } +array-bytes = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +pallet-transaction-payment = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-inherents = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-version = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/executive/src/tests.rs b/substrate/frame/executive/src/tests.rs index e3721f7b6dcbac24be073515d78fbf0f1d2658b8..69a970a89d93070fec01a3b80867e1ff529d014c 100644 --- a/substrate/frame/executive/src/tests.rs +++ b/substrate/frame/executive/src/tests.rs @@ -36,7 +36,7 @@ use frame_support::{ migrations::MultiStepMigrator, pallet_prelude::*, parameter_types, - traits::{fungible, ConstU8, Currency, IsInherent}, + traits::{fungible, ConstU8, Currency, IsInherent, VariantCount, VariantCountOf}, weights::{ConstantMultiplier, IdentityFee, RuntimeDbWeight, Weight, WeightMeter, WeightToFee}, }; use frame_system::{pallet_prelude::*, ChainContext, LastRuntimeUpgrade, LastRuntimeUpgradeInfo}; @@ -325,12 +325,24 @@ impl frame_system::Config for Runtime { type MultiBlockMigrator = MockedModeGetter; } +#[derive(Encode, Decode, Copy, Clone, Eq, PartialEq, MaxEncodedLen, TypeInfo, RuntimeDebug)] +pub enum FreezeReasonId { + Foo, +} + +impl VariantCount for FreezeReasonId { + const VARIANT_COUNT: u32 = 1; +} + type Balance = u64; #[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Runtime { type Balance = Balance; type AccountStore = System; + type RuntimeFreezeReason = FreezeReasonId; + type FreezeIdentifier = FreezeReasonId; + type MaxFreezes = VariantCountOf; } parameter_types! { @@ -637,8 +649,8 @@ fn block_weight_limit_enforced() { assert!(res.is_ok()); assert_eq!( >::block_weight().total(), - //--------------------- on_initialize + block_execution + extrinsic_base weight - Weight::from_parts((encoded_len + 5) * (nonce + 1), 0) + base_block_weight, + //--------------------- on_initialize + block_execution + extrinsic_base weight + extrinsic len + Weight::from_parts((encoded_len + 5) * (nonce + 1), (nonce + 1)* encoded_len) + base_block_weight, ); assert_eq!( >::extrinsic_index(), @@ -686,9 +698,10 @@ fn block_weight_and_size_is_stored_per_tx() { ::BlockWeights::get() .get(DispatchClass::Normal) .base_extrinsic; + // Check we account for all extrinsic weight and their len. assert_eq!( >::block_weight().total(), - base_block_weight + 3u64 * extrinsic_weight, + base_block_weight + 3u64 * extrinsic_weight + 3u64 * Weight::from_parts(0, len as u64), ); assert_eq!(>::all_extrinsics_len(), 3 * len); @@ -743,8 +756,12 @@ fn validate_unsigned() { fn can_not_pay_for_tx_fee_on_full_lock() { let mut t = new_test_ext(1); t.execute_with(|| { - as fungible::MutateFreeze>::set_freeze(&(), &1, 110) - .unwrap(); + as fungible::MutateFreeze>::set_freeze( + &FreezeReasonId::Foo, + &1, + 110, + ) + .unwrap(); let xt = TestXt::new( RuntimeCall::System(frame_system::Call::remark { remark: vec![1u8] }), sign_extra(1, 0, 0), diff --git a/substrate/frame/fast-unstake/Cargo.toml b/substrate/frame/fast-unstake/Cargo.toml index 5b7121e2eae3788fdf37c0467871f0233dd62393..59676ad39951951c6046bb6de303ee7ec9c0b21f 100644 --- a/substrate/frame/fast-unstake/Cargo.toml +++ b/substrate/frame/fast-unstake/Cargo.toml @@ -15,31 +15,31 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } +codec = { workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } +frame-support = { workspace = true } +frame-system = { workspace = true } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -sp-staking = { path = "../../primitives/staking", default-features = false } -frame-election-provider-support = { path = "../election-provider-support", default-features = false } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } +sp-staking = { workspace = true } +frame-election-provider-support = { workspace = true } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } +frame-benchmarking = { optional = true, workspace = true } -docify = "0.2.8" +docify = { workspace = true } [dev-dependencies] -pallet-staking-reward-curve = { path = "../staking/reward-curve" } -sp-core = { path = "../../primitives/core", default-features = false } -substrate-test-utils = { path = "../../test-utils" } -sp-tracing = { path = "../../primitives/tracing" } -pallet-staking = { path = "../staking" } -pallet-balances = { path = "../balances" } -pallet-timestamp = { path = "../timestamp" } +pallet-staking-reward-curve = { workspace = true, default-features = true } +sp-core = { workspace = true } +substrate-test-utils = { workspace = true } +sp-tracing = { workspace = true, default-features = true } +pallet-staking = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +pallet-timestamp = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/fast-unstake/src/mock.rs b/substrate/frame/fast-unstake/src/mock.rs index 9238a085141df2a4230f5b96aa6ec80426197a46..7ce7fee1410782a2166f7e696f2f0cad71746b40 100644 --- a/substrate/frame/fast-unstake/src/mock.rs +++ b/substrate/frame/fast-unstake/src/mock.rs @@ -60,20 +60,11 @@ parameter_types! { pub static ExistentialDeposit: Balance = 1; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Runtime { - type MaxLocks = ConstU32<128>; - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } pallet_staking_reward_curve::build! { @@ -113,35 +104,17 @@ impl frame_election_provider_support::ElectionProvider for MockElection { } } +#[derive_impl(pallet_staking::config_preludes::TestDefaultConfig)] impl pallet_staking::Config for Runtime { type Currency = Balances; - type CurrencyBalance = Balance; type UnixTime = pallet_timestamp::Pallet; - type CurrencyToVote = (); - type RewardRemainder = (); - type RuntimeEvent = RuntimeEvent; - type Slash = (); - type Reward = (); - type SessionsPerEra = (); - type SlashDeferDuration = (); type AdminOrigin = frame_system::EnsureRoot; type BondingDuration = BondingDuration; - type SessionInterface = (); type EraPayout = pallet_staking::ConvertCurve; - type NextNewSession = (); - type HistoryDepth = ConstU32<84>; - type MaxExposurePageSize = ConstU32<64>; type ElectionProvider = MockElection; type GenesisElectionProvider = Self::ElectionProvider; type VoterList = pallet_staking::UseNominatorsAndValidatorsMap; type TargetList = pallet_staking::UseValidatorsMap; - type NominationsQuota = pallet_staking::FixedNominationsQuota<16>; - type MaxUnlockingChunks = ConstU32<32>; - type MaxControllersInDeprecationBatch = ConstU32<100>; - type EventListeners = (); - type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; - type WeightInfo = (); - type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; } parameter_types! { diff --git a/substrate/frame/glutton/Cargo.toml b/substrate/frame/glutton/Cargo.toml index 730c4e70935c0be3cb840087011a37ca9668b317..58faecde62939f50d6b901ec9a5f3fa32ee8eda6 100644 --- a/substrate/frame/glutton/Cargo.toml +++ b/substrate/frame/glutton/Cargo.toml @@ -16,20 +16,21 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -blake2 = { version = "0.10.4", default-features = false } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +blake2 = { workspace = true } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } log = { workspace = true } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +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] -pallet-balances = { path = "../balances" } +pallet-balances = { workspace = true, default-features = true } [features] default = ["std"] @@ -43,6 +44,7 @@ std = [ "pallet-balances/std", "scale-info/std", "sp-core/std", + "sp-inherents/std", "sp-io/std", "sp-runtime/std", "sp-std/std", diff --git a/substrate/frame/glutton/README.md b/substrate/frame/glutton/README.md index 89dbe26ec7a9d7eb0ad379f0526a770b4ba45a28..43642df19104a709bdab08661848774ff955fb48 100644 --- a/substrate/frame/glutton/README.md +++ b/substrate/frame/glutton/README.md @@ -7,6 +7,7 @@ The `Glutton` pallet gets the name from its property to consume vast amounts of resources. It can be used to push para-chains and their relay-chains to the limits. This is good for testing out theoretical limits in a practical way. -The `Glutton` can be set to consume a fraction of the available unused weight of a chain. It accomplishes this by -utilizing the `on_idle` hook and consuming a specific ration of the remaining weight. The rations can be set via -`set_compute` and `set_storage`. Initially the `Glutton` needs to be initialized once with `initialize_pallet`. +The `Glutton` can be set to consume a fraction of the available block length and unused weight of a chain. It +accomplishes this by filling the block length up to a ration and utilizing the `on_idle` hook to consume a +specific ration of the remaining weight. The rations can be set via `set_compute`, `set_storage` and `set_block_length`. +Initially the `Glutton` needs to be initialized once with `initialize_pallet`. diff --git a/substrate/frame/glutton/src/lib.rs b/substrate/frame/glutton/src/lib.rs index 344a70becaeb9eb35cb17c640977f4c8401684ab..5427173b486bab7dfbc830d6af130bf8bccf7e6a 100644 --- a/substrate/frame/glutton/src/lib.rs +++ b/substrate/frame/glutton/src/lib.rs @@ -89,6 +89,11 @@ pub mod pallet { /// The storage limit. storage: FixedU64, }, + /// The block length limit has been updated. + BlockLengthLimitSet { + /// The block length limit. + block_length: FixedU64, + }, } #[pallet::error] @@ -116,6 +121,13 @@ pub mod pallet { #[pallet::storage] pub(crate) type Storage = StorageValue<_, FixedU64, ValueQuery>; + /// The proportion of the `block length` to consume on each block. + /// + /// `1.0` is mapped to `100%`. Must be at most [`crate::RESOURCE_HARD_LIMIT`]. Setting this to + /// over `1.0` could stall the chain. + #[pallet::storage] + pub(crate) type Length = StorageValue<_, FixedU64, ValueQuery>; + /// Storage map used for wasting proof size. /// /// It contains no meaningful data - hence the name "Trash". The maximal number of entries is @@ -146,6 +158,8 @@ pub mod pallet { pub storage: FixedU64, /// The amount of trash data for wasting proof size. pub trash_data_count: u32, + /// The block length limit. + pub block_length: FixedU64, #[serde(skip)] /// The required configuration field. pub _config: sp_std::marker::PhantomData, @@ -170,6 +184,9 @@ pub mod pallet { assert!(self.storage <= RESOURCE_HARD_LIMIT, "Storage limit is insane"); >::put(self.storage); + + assert!(self.block_length <= RESOURCE_HARD_LIMIT, "Block length limit is insane"); + >::put(self.block_length); } } @@ -208,6 +225,40 @@ pub mod pallet { } } + #[pallet::inherent] + impl ProvideInherent for Pallet { + type Call = Call; + type Error = sp_inherents::MakeFatalError<()>; + + const INHERENT_IDENTIFIER: InherentIdentifier = *b"bloated0"; + + fn create_inherent(_data: &InherentData) -> Option { + let max_block_length = *T::BlockLength::get().max.get(DispatchClass::Mandatory); + let bloat_size = Length::::get().saturating_mul_int(max_block_length) as usize; + let amount_trash = bloat_size / VALUE_SIZE; + let garbage = TrashData::::iter() + .map(|(_k, v)| v) + .collect::>() + .into_iter() + .cycle() + .take(amount_trash) + .collect::>(); + + Some(Call::bloat { garbage }) + } + + fn is_inherent(call: &Self::Call) -> bool { + matches!(call, Call::bloat { .. }) + } + + fn check_inherent(call: &Self::Call, _: &InherentData) -> Result<(), Self::Error> { + match call { + Call::bloat { .. } => Ok(()), + _ => unreachable!("other calls are not inherents"), + } + } + } + #[pallet::call(weight = T::WeightInfo)] impl Pallet { /// Initialize the pallet. Should be called once, if no genesis state was provided. @@ -277,6 +328,31 @@ pub mod pallet { Self::deposit_event(Event::StorageLimitSet { storage }); Ok(()) } + + /// Increase the block size by including the specified garbage bytes. + #[pallet::call_index(3)] + #[pallet::weight((0, DispatchClass::Mandatory))] + pub fn bloat(_origin: OriginFor, _garbage: Vec<[u8; VALUE_SIZE]>) -> DispatchResult { + Ok(()) + } + + /// Set how much of the block length should be filled with trash data on each block. + /// + /// `1.0` means that all block should be filled. If set to `1.0`, storage proof size will + /// be close to zero. + /// + /// Only callable by Root or `AdminOrigin`. + #[pallet::call_index(4)] + #[pallet::weight({1})] + pub fn set_block_length(origin: OriginFor, block_length: FixedU64) -> DispatchResult { + T::AdminOrigin::ensure_origin_or_root(origin)?; + + ensure!(block_length <= RESOURCE_HARD_LIMIT, Error::::InsaneLimit); + Length::::set(block_length); + + Self::deposit_event(Event::BlockLengthLimitSet { block_length }); + Ok(()) + } } impl Pallet { diff --git a/substrate/frame/glutton/src/mock.rs b/substrate/frame/glutton/src/mock.rs index 132ef5cfbcbbabb077b7968cc0ae1451bcd06bc7..7163d7c46781f331222ee6dbbc9cf4807b2ecb1e 100644 --- a/substrate/frame/glutton/src/mock.rs +++ b/substrate/frame/glutton/src/mock.rs @@ -50,10 +50,14 @@ pub fn new_test_ext() -> sp_io::TestExternalities { ext } -/// Set the `compute` and `storage` limits. +/// Set the `compute`, `storage` and `block_length` limits. /// /// `1.0` corresponds to `100%`. -pub fn set_limits(compute: f64, storage: f64) { +pub fn set_limits(compute: f64, storage: f64, block_length: f64) { assert_ok!(Glutton::set_compute(RuntimeOrigin::root(), FixedU64::from_float(compute))); assert_ok!(Glutton::set_storage(RuntimeOrigin::root(), FixedU64::from_float(storage))); + assert_ok!(Glutton::set_block_length( + RuntimeOrigin::root(), + FixedU64::from_float(block_length) + )); } diff --git a/substrate/frame/glutton/src/tests.rs b/substrate/frame/glutton/src/tests.rs index b72d5272772540e5106af8cec248170cfcf910d6..81d228f39a9363961dd7e64cc952414d07ab1a33 100644 --- a/substrate/frame/glutton/src/tests.rs +++ b/substrate/frame/glutton/src/tests.rs @@ -123,6 +123,43 @@ fn setting_compute_respects_limit() { }); } +#[test] +fn setting_block_length_works() { + new_test_ext().execute_with(|| { + assert_eq!(Compute::::get(), Zero::zero()); + + assert_ok!(Glutton::set_block_length(RuntimeOrigin::root(), FixedU64::from_float(0.3))); + assert_eq!(Length::::get(), FixedU64::from_float(0.3)); + System::assert_last_event( + Event::BlockLengthLimitSet { block_length: FixedU64::from_float(0.3) }.into(), + ); + + assert_noop!( + Glutton::set_block_length(RuntimeOrigin::signed(1), FixedU64::from_float(0.5)), + DispatchError::BadOrigin + ); + assert_noop!( + Glutton::set_block_length(RuntimeOrigin::none(), FixedU64::from_float(0.5)), + DispatchError::BadOrigin + ); + }); +} + +#[test] +fn setting_block_length_respects_limit() { + new_test_ext().execute_with(|| { + // < 1000% is fine + assert_ok!(Glutton::set_block_length(RuntimeOrigin::root(), FixedU64::from_float(9.99)),); + // == 1000% is fine + assert_ok!(Glutton::set_block_length(RuntimeOrigin::root(), FixedU64::from_u32(10)),); + // > 1000% is not + assert_noop!( + Glutton::set_block_length(RuntimeOrigin::root(), FixedU64::from_float(10.01)), + Error::::InsaneLimit + ); + }); +} + #[test] fn setting_storage_works() { new_test_ext().execute_with(|| { @@ -163,7 +200,7 @@ fn setting_storage_respects_limit() { #[test] fn on_idle_works() { new_test_ext().execute_with(|| { - set_limits(One::one(), One::one()); + set_limits(One::one(), One::one(), One::one()); Glutton::on_idle(1, Weight::from_parts(20_000_000, 0)); }); @@ -173,7 +210,7 @@ fn on_idle_works() { #[test] fn on_idle_weight_high_proof_is_close_enough_works() { new_test_ext().execute_with(|| { - set_limits(One::one(), One::one()); + set_limits(One::one(), One::one(), One::one()); let should = Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND, WEIGHT_PROOF_SIZE_PER_MB * 5); let got = Glutton::on_idle(1, should); @@ -196,7 +233,7 @@ fn on_idle_weight_high_proof_is_close_enough_works() { #[test] fn on_idle_weight_low_proof_is_close_enough_works() { new_test_ext().execute_with(|| { - set_limits(One::one(), One::one()); + set_limits(One::one(), One::one(), One::one()); let should = Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND, WEIGHT_PROOF_SIZE_PER_KB * 20); let got = Glutton::on_idle(1, should); @@ -224,7 +261,7 @@ fn on_idle_weight_over_unity_is_close_enough_works() { let max_block = Weight::from_parts(500 * WEIGHT_REF_TIME_PER_MILLIS, 5 * WEIGHT_PROOF_SIZE_PER_MB); // But now we tell it to consume more than that. - set_limits(1.75, 1.5); + set_limits(1.75, 1.5, 0.0); let want = Weight::from_parts( (1.75 * max_block.ref_time() as f64) as u64, (1.5 * max_block.proof_size() as f64) as u64, diff --git a/substrate/frame/grandpa/Cargo.toml b/substrate/frame/grandpa/Cargo.toml index 37048b06608f613f0e0c724314b7fb2093dec619..e08af3a5e91b31a00b6fd8d6f5a9f7764e7c8993 100644 --- a/substrate/frame/grandpa/Cargo.toml +++ b/substrate/frame/grandpa/Cargo.toml @@ -16,33 +16,33 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive", "serde"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -pallet-authorship = { path = "../authorship", default-features = false } -pallet-session = { path = "../session", default-features = false } -sp-application-crypto = { path = "../../primitives/application-crypto", default-features = false, features = ["serde"] } -sp-consensus-grandpa = { path = "../../primitives/consensus/grandpa", default-features = false, features = ["serde"] } -sp-core = { path = "../../primitives/core", default-features = false, features = ["serde"] } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false, features = ["serde"] } -sp-session = { path = "../../primitives/session", default-features = false } -sp-staking = { path = "../../primitives/staking", default-features = false, features = ["serde"] } -sp-std = { path = "../../primitives/std", default-features = false } +scale-info = { features = ["derive", "serde"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-authorship = { workspace = true } +pallet-session = { workspace = true } +sp-application-crypto = { features = ["serde"], workspace = true } +sp-consensus-grandpa = { features = ["serde"], workspace = true } +sp-core = { features = ["serde"], workspace = true } +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 = { version = "0.16.2", features = ["derive-codec"] } -frame-benchmarking = { path = "../benchmarking" } -frame-election-provider-support = { path = "../election-provider-support" } -pallet-balances = { path = "../balances" } -pallet-offences = { path = "../offences" } -pallet-staking = { path = "../staking" } -pallet-staking-reward-curve = { path = "../staking/reward-curve" } -pallet-timestamp = { path = "../timestamp" } -sp-keyring = { path = "../../primitives/keyring" } +finality-grandpa = { features = ["derive-codec"], workspace = true, default-features = true } +frame-benchmarking = { workspace = true, default-features = true } +frame-election-provider-support = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +pallet-offences = { workspace = true, default-features = true } +pallet-staking = { workspace = true, default-features = true } +pallet-staking-reward-curve = { workspace = true, default-features = true } +pallet-timestamp = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/grandpa/src/mock.rs b/substrate/frame/grandpa/src/mock.rs index 38b5536bc598b33520575b038dd220e962bd7215..5ba7da7f9fda2a6e0d30f1b04b7aac1e808c55cb 100644 --- a/substrate/frame/grandpa/src/mock.rs +++ b/substrate/frame/grandpa/src/mock.rs @@ -108,20 +108,11 @@ impl pallet_authorship::Config for Test { type EventHandler = (); } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; type Balance = u128; - type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; type ExistentialDeposit = ConstU128<1>; type AccountStore = System; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } impl pallet_timestamp::Config for Test { @@ -159,35 +150,22 @@ impl onchain::Config for OnChainSeqPhragmen { type Bounds = ElectionsBoundsOnChain; } +#[derive_impl(pallet_staking::config_preludes::TestDefaultConfig)] impl pallet_staking::Config for Test { - type RewardRemainder = (); - type CurrencyToVote = (); - type RuntimeEvent = RuntimeEvent; type Currency = Balances; type CurrencyBalance = ::Balance; - type Slash = (); - type Reward = (); type SessionsPerEra = SessionsPerEra; type BondingDuration = BondingDuration; - type SlashDeferDuration = (); type AdminOrigin = frame_system::EnsureRoot; type SessionInterface = Self; type UnixTime = pallet_timestamp::Pallet; type EraPayout = pallet_staking::ConvertCurve; - type MaxExposurePageSize = ConstU32<64>; type NextNewSession = Session; type ElectionProvider = onchain::OnChainExecution; type GenesisElectionProvider = Self::ElectionProvider; type VoterList = pallet_staking::UseNominatorsAndValidatorsMap; type TargetList = pallet_staking::UseValidatorsMap; type NominationsQuota = pallet_staking::FixedNominationsQuota<16>; - type MaxUnlockingChunks = ConstU32<32>; - type MaxControllersInDeprecationBatch = ConstU32<100>; - type HistoryDepth = ConstU32<84>; - type EventListeners = (); - type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; - type WeightInfo = (); - type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; } impl pallet_offences::Config for Test { diff --git a/substrate/frame/identity/Cargo.toml b/substrate/frame/identity/Cargo.toml index 987e418048d3629b0f2c042d898fe7e2d925a22c..d0b796cd75d351ba2e5df0d791d932babad11c08 100644 --- a/substrate/frame/identity/Cargo.toml +++ b/substrate/frame/identity/Cargo.toml @@ -16,21 +16,21 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive", "max-encoded-len"] } -enumflags2 = { version = "0.7.7" } +codec = { features = ["derive", "max-encoded-len"], workspace = true } +enumflags2 = { workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -pallet-balances = { path = "../balances" } -sp-core = { path = "../../primitives/core" } -sp-keystore = { path = "../../primitives/keystore" } +pallet-balances = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/identity/src/tests.rs b/substrate/frame/identity/src/tests.rs index b1a953d487ce29bdd27360d61e22d163656ad7db..09edd5de79bb2ff9ba483dbd03c6b24ad59a28de 100644 --- a/substrate/frame/identity/src/tests.rs +++ b/substrate/frame/identity/src/tests.rs @@ -61,20 +61,9 @@ impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type Balance = u64; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ConstU64<1>; type AccountStore = System; - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } parameter_types! { diff --git a/substrate/frame/im-online/Cargo.toml b/substrate/frame/im-online/Cargo.toml index 78192a81d7b461d0c834662b8bd0e4c50ea31333..85cbcb3941b17b8675049196d8d60ad201e40916 100644 --- a/substrate/frame/im-online/Cargo.toml +++ b/substrate/frame/im-online/Cargo.toml @@ -16,22 +16,22 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive", "serde"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -pallet-authorship = { path = "../authorship", default-features = false } -sp-application-crypto = { path = "../../primitives/application-crypto", default-features = false, features = ["serde"] } -sp-core = { path = "../../primitives/core", default-features = false, features = ["serde"] } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false, features = ["serde"] } -sp-staking = { path = "../../primitives/staking", default-features = false, features = ["serde"] } -sp-std = { path = "../../primitives/std", default-features = false } +scale-info = { features = ["derive", "serde"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-authorship = { workspace = true } +sp-application-crypto = { features = ["serde"], workspace = true } +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 = { path = "../session" } +pallet-session = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/indices/Cargo.toml b/substrate/frame/indices/Cargo.toml index 248bae003ed856a828ce82863ad2fadfb7f0a927..20c3863ff99b0743100c9d3354a9e5efb43ffc71 100644 --- a/substrate/frame/indices/Cargo.toml +++ b/substrate/frame/indices/Cargo.toml @@ -16,19 +16,19 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-keyring = { path = "../../primitives/keyring", optional = true, default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +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 = { path = "../balances" } +pallet-balances = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/indices/src/mock.rs b/substrate/frame/indices/src/mock.rs index 7a8ff98f6d4ae507f1af99a713390528c8a9d0f0..72bbc6dab4a42b7c3556aa986a770ff3fbf24bdc 100644 --- a/substrate/frame/indices/src/mock.rs +++ b/substrate/frame/indices/src/mock.rs @@ -42,20 +42,9 @@ impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type Balance = u64; - type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; - type ExistentialDeposit = ConstU64<1>; type AccountStore = System; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } impl Config for Test { diff --git a/substrate/frame/insecure-randomness-collective-flip/Cargo.toml b/substrate/frame/insecure-randomness-collective-flip/Cargo.toml index c2ec14cb4bc77c5668750684ae983b41ac46e780..0da0d5373953b7703c095e86a9dbf2ec09fba2a6 100644 --- a/substrate/frame/insecure-randomness-collective-flip/Cargo.toml +++ b/substrate/frame/insecure-randomness-collective-flip/Cargo.toml @@ -16,17 +16,17 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -safe-mix = { version = "1.0", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +codec = { features = ["derive"], workspace = true } +safe-mix = { workspace = true } +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 = { path = "../../primitives/core" } -sp-io = { path = "../../primitives/io" } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/lottery/Cargo.toml b/substrate/frame/lottery/Cargo.toml index be59e5ec8935102bd03782f7c745775c46bacc18..34d1728e42ed0df444530cd4cdd6f039f2e12da4 100644 --- a/substrate/frame/lottery/Cargo.toml +++ b/substrate/frame/lottery/Cargo.toml @@ -15,21 +15,21 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", -] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +], workspace = true } +scale-info = { features = ["derive"], workspace = true } +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 = { path = "../support/test" } -pallet-balances = { path = "../balances" } -sp-core = { path = "../../primitives/core" } -sp-io = { path = "../../primitives/io" } +frame-support-test = { workspace = true } +pallet-balances = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/lottery/src/mock.rs b/substrate/frame/lottery/src/mock.rs index 596e1a9d837d16486e8a2017b0ab679a02bc2dd6..d2c442e2ac6e5acd0b096308ebed02ad9fe0f78e 100644 --- a/substrate/frame/lottery/src/mock.rs +++ b/substrate/frame/lottery/src/mock.rs @@ -22,7 +22,7 @@ use crate as pallet_lottery; use frame_support::{ derive_impl, parameter_types, - traits::{ConstU32, ConstU64, OnFinalize, OnInitialize}, + traits::{ConstU32, OnFinalize, OnInitialize}, }; use frame_support_test::TestRandomness; use frame_system::EnsureRoot; @@ -49,20 +49,9 @@ impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type Balance = u64; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ConstU64<1>; type AccountStore = System; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } parameter_types! { diff --git a/substrate/frame/membership/Cargo.toml b/substrate/frame/membership/Cargo.toml index 9f19c40973687a41936372f6e116eb2dc8417306..35b0eeaa7141985c31ab857931e300da050aafcd 100644 --- a/substrate/frame/membership/Cargo.toml +++ b/substrate/frame/membership/Cargo.toml @@ -16,16 +16,16 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } +codec = { workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive", "serde"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false, features = ["serde"] } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false, features = ["serde"] } -sp-std = { path = "../../primitives/std", default-features = false } +scale-info = { features = ["derive", "serde"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +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"] diff --git a/substrate/frame/membership/src/lib.rs b/substrate/frame/membership/src/lib.rs index aa6be6497eea697235f71c2927b1adf6044052bd..8deb4fc022f37dec2af285a7ab6b173992fbf33c 100644 --- a/substrate/frame/membership/src/lib.rs +++ b/substrate/frame/membership/src/lib.rs @@ -24,7 +24,7 @@ #![cfg_attr(not(feature = "std"), no_std)] use frame_support::{ - traits::{ChangeMembers, Contains, Get, InitializeMembers, SortedMembers}, + traits::{ChangeMembers, Contains, ContainsLengthBound, Get, InitializeMembers, SortedMembers}, BoundedVec, }; use sp_runtime::traits::{StaticLookup, UniqueSaturatedInto}; @@ -361,6 +361,17 @@ impl, I: 'static> Contains for Pallet { } } +impl ContainsLengthBound for Pallet { + fn min_len() -> usize { + 0 + } + + /// Implementation uses a parameter type so calling is cost-free. + fn max_len() -> usize { + T::MaxMembers::get() as usize + } +} + impl, I: 'static> SortedMembers for Pallet { fn sorted_members() -> Vec { Self::members().to_vec() diff --git a/substrate/frame/merkle-mountain-range/Cargo.toml b/substrate/frame/merkle-mountain-range/Cargo.toml index 0d73c567cf4e16babb1488d0ad6e5d43c11639d8..27ba77e5a62a9c6d2c31639aac5824ab0e8383cc 100644 --- a/substrate/frame/merkle-mountain-range/Cargo.toml +++ b/substrate/frame/merkle-mountain-range/Cargo.toml @@ -15,22 +15,22 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } +codec = { workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-mmr-primitives = { path = "../../primitives/merkle-mountain-range", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +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 = "6.2.2" -env_logger = "0.11" -itertools = "0.11" +array-bytes = { workspace = true, default-features = true } +env_logger = { workspace = true } +itertools = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/message-queue/Cargo.toml b/substrate/frame/message-queue/Cargo.toml index e44cbeb1550ccfdb0daf8e871e924df261a59227..5ced1a4e08ff9a4d6fe328f7db76eef23f7c69f1 100644 --- a/substrate/frame/message-queue/Cargo.toml +++ b/substrate/frame/message-queue/Cargo.toml @@ -12,28 +12,28 @@ description = "FRAME pallet to queue and process messages" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } serde = { optional = true, features = ["derive"], workspace = true, default-features = true } log = { workspace = true } -environmental = { version = "1.1.4", default-features = false } +environmental = { workspace = true } -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -sp-arithmetic = { path = "../../primitives/arithmetic", default-features = false } -sp-weights = { path = "../../primitives/weights", default-features = false } +sp-core = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } +sp-arithmetic = { workspace = true } +sp-weights = { workspace = true } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } [dev-dependencies] -sp-crypto-hashing = { path = "../../primitives/crypto/hashing" } -sp-tracing = { path = "../../primitives/tracing" } -rand = "0.8.5" -rand_distr = "0.4.3" +sp-crypto-hashing = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +rand = { workspace = true, default-features = true } +rand_distr = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/metadata-hash-extension/Cargo.toml b/substrate/frame/metadata-hash-extension/Cargo.toml index 13d4bd0c2ea909700dda8d1ec621892c4a728724..10d90bba0911bc1830a29ede8c9dbe78e9e45716 100644 --- a/substrate/frame/metadata-hash-extension/Cargo.toml +++ b/substrate/frame/metadata-hash-extension/Cargo.toml @@ -9,23 +9,23 @@ repository.workspace = true description = "FRAME signed extension for verifying the metadata hash" [dependencies] -array-bytes = "6.2.2" -codec = { package = "parity-scale-codec", version = "3.6.1", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive", "serde"] } -sp-runtime = { path = "../../primitives/runtime", default-features = false, features = ["serde"] } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -log = { workspace = true, default-features = false } -docify = "0.2.8" +array-bytes = { workspace = true, default-features = true } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive", "serde"], workspace = true } +sp-runtime = { features = ["serde"], workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +log = { workspace = true } +docify = { workspace = true } [dev-dependencies] -substrate-wasm-builder = { path = "../../utils/wasm-builder", features = ["metadata-hash"] } -substrate-test-runtime-client = { path = "../../test-utils/runtime/client" } -sp-api = { path = "../../primitives/api" } -sp-transaction-pool = { path = "../../primitives/transaction-pool" } -merkleized-metadata = "0.1.0" -frame-metadata = { version = "16.0.0", features = ["current"] } -sp-tracing = { path = "../../primitives/tracing" } +substrate-wasm-builder = { features = ["metadata-hash"], workspace = true, default-features = true } +substrate-test-runtime-client = { workspace = true } +sp-api = { workspace = true, default-features = true } +sp-transaction-pool = { workspace = true, default-features = true } +merkleized-metadata = { workspace = true } +frame-metadata = { features = ["current"], workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/migrations/Cargo.toml b/substrate/frame/migrations/Cargo.toml index 69e910a4e4f6e56b2b848f9b0f402da40d73f77d..5a946d3aa05816ef258ef3ce47c65bbf2fdc08d2 100644 --- a/substrate/frame/migrations/Cargo.toml +++ b/substrate/frame/migrations/Cargo.toml @@ -11,28 +11,28 @@ repository.workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -docify = "0.2.8" -impl-trait-for-tuples = "0.2.2" -log = "0.4.21" -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +docify = { workspace = true } +impl-trait-for-tuples = { workspace = true } +log = { workspace = true, default-features = true } +scale-info = { features = ["derive"], workspace = true } -frame-benchmarking = { default-features = false, optional = true, path = "../benchmarking" } -frame-support = { default-features = false, path = "../support" } -frame-system = { default-features = false, path = "../system" } -sp-core = { path = "../../primitives/core", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } +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] -frame-executive = { path = "../executive" } -sp-api = { path = "../../primitives/api", features = ["std"] } -sp-block-builder = { path = "../../primitives/block-builder", features = ["std"] } -sp-io = { path = "../../primitives/io", features = ["std"] } -sp-tracing = { path = "../../primitives/tracing", features = ["std"] } -sp-version = { path = "../../primitives/version", features = ["std"] } +frame-executive = { workspace = true, default-features = true } +sp-api = { features = ["std"], workspace = true, default-features = true } +sp-block-builder = { features = ["std"], workspace = true, default-features = true } +sp-io = { features = ["std"], workspace = true, default-features = true } +sp-tracing = { features = ["std"], workspace = true, default-features = true } +sp-version = { features = ["std"], workspace = true, default-features = true } -pretty_assertions = "1.3.0" +pretty_assertions = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/mixnet/Cargo.toml b/substrate/frame/mixnet/Cargo.toml index 44a567d668fb3c3452b4492831b0be66595a7c05..f3bea3d2914752930a4164b8c19ab6ce0c444018 100644 --- a/substrate/frame/mixnet/Cargo.toml +++ b/substrate/frame/mixnet/Cargo.toml @@ -16,19 +16,19 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive", "max-encoded-len"] } -frame-benchmarking = { default-features = false, optional = true, path = "../benchmarking" } -frame-support = { default-features = false, path = "../support" } -frame-system = { default-features = false, path = "../system" } +codec = { features = ["derive", "max-encoded-len"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } serde = { features = ["derive"], workspace = true } -sp-application-crypto = { default-features = false, path = "../../primitives/application-crypto" } -sp-arithmetic = { default-features = false, path = "../../primitives/arithmetic" } -sp-io = { default-features = false, path = "../../primitives/io" } -sp-mixnet = { default-features = false, path = "../../primitives/mixnet" } -sp-runtime = { default-features = false, path = "../../primitives/runtime" } -sp-std = { default-features = false, path = "../../primitives/std" } +sp-application-crypto = { workspace = true } +sp-arithmetic = { workspace = true } +sp-io = { workspace = true } +sp-mixnet = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/multisig/Cargo.toml b/substrate/frame/multisig/Cargo.toml index 649a7100325f931e940760688710f88a1fbb6154..329b2e8824e2449ae99ad55f9a6796fd35f1c044 100644 --- a/substrate/frame/multisig/Cargo.toml +++ b/substrate/frame/multisig/Cargo.toml @@ -16,20 +16,20 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +codec = { workspace = true } +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +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 } [dev-dependencies] -pallet-balances = { path = "../balances" } +pallet-balances = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/nft-fractionalization/Cargo.toml b/substrate/frame/nft-fractionalization/Cargo.toml index e2a7e34c637b430dbda56f1690938c1cde2b100e..f0613581257e9418e38990e6f74a45065d076493 100644 --- a/substrate/frame/nft-fractionalization/Cargo.toml +++ b/substrate/frame/nft-fractionalization/Cargo.toml @@ -16,22 +16,22 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } +codec = { workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -pallet-assets = { path = "../assets", default-features = false } -pallet-nfts = { path = "../nfts", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-assets = { workspace = true } +pallet-nfts = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -pallet-balances = { path = "../balances" } -sp-core = { path = "../../primitives/core" } -sp-io = { path = "../../primitives/io" } -sp-std = { path = "../../primitives/std" } +pallet-balances = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-std = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/nft-fractionalization/src/mock.rs b/substrate/frame/nft-fractionalization/src/mock.rs index 82a608816260041d6887af80334b423de1c4f744..50b41b5fc64e101713f326444c2efaa326093fde 100644 --- a/substrate/frame/nft-fractionalization/src/mock.rs +++ b/substrate/frame/nft-fractionalization/src/mock.rs @@ -57,20 +57,9 @@ impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type Balance = u64; - type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; - type ExistentialDeposit = ConstU64<1>; type AccountStore = System; - type WeightInfo = (); - type MaxLocks = (); - type MaxReserves = ConstU32<50>; - type ReserveIdentifier = [u8; 8]; - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeFreezeReason; - type FreezeIdentifier = (); - type MaxFreezes = (); } impl pallet_assets::Config for Test { diff --git a/substrate/frame/nfts/Cargo.toml b/substrate/frame/nfts/Cargo.toml index 5c5c011c94ea27467e5b8bbd18fda890a181acf2..a1eef3226ecf7ac1b7f5ae91fa471854691dd7fc 100644 --- a/substrate/frame/nfts/Cargo.toml +++ b/substrate/frame/nfts/Cargo.toml @@ -16,21 +16,21 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -enumflags2 = { version = "0.7.7" } +codec = { workspace = true } +enumflags2 = { workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-core = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -pallet-balances = { path = "../balances" } -sp-keystore = { path = "../../primitives/keystore" } +pallet-balances = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/nfts/runtime-api/Cargo.toml b/substrate/frame/nfts/runtime-api/Cargo.toml index 6bee98fb51e0c908dfb70d28891e91cb55a7c6ea..731f5f5ae7767f918d5cd6f775f4a48c2cc7d6ac 100644 --- a/substrate/frame/nfts/runtime-api/Cargo.toml +++ b/substrate/frame/nfts/runtime-api/Cargo.toml @@ -16,10 +16,10 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -pallet-nfts = { path = "..", default-features = false } -sp-api = { path = "../../../primitives/api", default-features = false } -sp-std = { path = "../../../primitives/std", default-features = false } +codec = { features = ["derive"], workspace = true } +pallet-nfts = { workspace = true } +sp-api = { workspace = true } +sp-std = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/nfts/src/benchmarking.rs b/substrate/frame/nfts/src/benchmarking.rs index 8792af675fc16de7c18f07312aa74e4bab46d3db..80860bc5a53c432685abd7144e92b85e0c697edf 100644 --- a/substrate/frame/nfts/src/benchmarking.rs +++ b/substrate/frame/nfts/src/benchmarking.rs @@ -30,11 +30,7 @@ use frame_support::{ BoundedVec, }; use frame_system::{pallet_prelude::BlockNumberFor, RawOrigin as SystemOrigin}; -use sp_io::crypto::{sr25519_generate, sr25519_sign}; -use sp_runtime::{ - traits::{Bounded, IdentifyAccount, One}, - AccountId32, MultiSignature, MultiSigner, -}; +use sp_runtime::traits::{Bounded, One}; use sp_std::prelude::*; use crate::Pallet as Nfts; @@ -229,12 +225,6 @@ fn make_filled_vec(value: u16, length: usize) -> Vec { } benchmarks_instance_pallet! { - where_clause { - where - T::OffchainSignature: From, - T::AccountId: From, - } - create { let collection = T::Helper::collection(0); let origin = T::CreateOrigin::try_successful_origin(&collection) @@ -800,8 +790,7 @@ benchmarks_instance_pallet! { mint_pre_signed { let n in 0 .. T::MaxAttributesPerCall::get() as u32; - let caller_public = sr25519_generate(0.into(), None); - let caller = MultiSigner::Sr25519(caller_public).into_account().into(); + let (caller_public, caller) = T::Helper::signer(); T::Currency::make_free_balance_be(&caller, DepositBalanceOf::::max_value()); let caller_lookup = T::Lookup::unlookup(caller.clone()); @@ -830,7 +819,7 @@ benchmarks_instance_pallet! { mint_price: Some(DepositBalanceOf::::min_value()), }; let message = Encode::encode(&mint_data); - let signature = MultiSignature::Sr25519(sr25519_sign(0.into(), &caller_public, &message).unwrap()); + let signature = T::Helper::sign(&caller_public, &message); let target: T::AccountId = account("target", 0, SEED); T::Currency::make_free_balance_be(&target, DepositBalanceOf::::max_value()); @@ -848,8 +837,7 @@ benchmarks_instance_pallet! { let item_owner: T::AccountId = account("item_owner", 0, SEED); let item_owner_lookup = T::Lookup::unlookup(item_owner.clone()); - let signer_public = sr25519_generate(0.into(), None); - let signer: T::AccountId = MultiSigner::Sr25519(signer_public).into_account().into(); + let (signer_public, signer) = T::Helper::signer(); T::Currency::make_free_balance_be(&item_owner, DepositBalanceOf::::max_value()); @@ -876,7 +864,7 @@ benchmarks_instance_pallet! { deadline: One::one(), }; let message = Encode::encode(&pre_signed_data); - let signature = MultiSignature::Sr25519(sr25519_sign(0.into(), &signer_public, &message).unwrap()); + let signature = T::Helper::sign(&signer_public, &message); frame_system::Pallet::::set_block_number(One::one()); }: _(SystemOrigin::Signed(item_owner.clone()), pre_signed_data, signature.into(), signer.clone()) diff --git a/substrate/frame/nfts/src/lib.rs b/substrate/frame/nfts/src/lib.rs index 615720268fed611bbf7effa1f4b71eca0df4a7e7..0406cac6e2c983da4e7ef3db9e4fd506c1803506 100644 --- a/substrate/frame/nfts/src/lib.rs +++ b/substrate/frame/nfts/src/lib.rs @@ -84,18 +84,42 @@ pub mod pallet { pub struct Pallet(PhantomData<(T, I)>); #[cfg(feature = "runtime-benchmarks")] - pub trait BenchmarkHelper { + pub trait BenchmarkHelper { fn collection(i: u16) -> CollectionId; fn item(i: u16) -> ItemId; + fn signer() -> (Public, AccountId); + fn sign(signer: &Public, message: &[u8]) -> Signature; } #[cfg(feature = "runtime-benchmarks")] - impl, ItemId: From> BenchmarkHelper for () { + impl + BenchmarkHelper< + CollectionId, + ItemId, + sp_runtime::MultiSigner, + sp_runtime::AccountId32, + sp_runtime::MultiSignature, + > for () + where + CollectionId: From, + ItemId: From, + { fn collection(i: u16) -> CollectionId { i.into() } fn item(i: u16) -> ItemId { i.into() } + fn signer() -> (sp_runtime::MultiSigner, sp_runtime::AccountId32) { + let public = sp_io::crypto::sr25519_generate(0.into(), None); + let account = sp_runtime::MultiSigner::Sr25519(public).into_account(); + (public.into(), account) + } + fn sign(signer: &sp_runtime::MultiSigner, message: &[u8]) -> sp_runtime::MultiSignature { + sp_runtime::MultiSignature::Sr25519( + sp_io::crypto::sr25519_sign(0.into(), &signer.clone().try_into().unwrap(), message) + .unwrap(), + ) + } } #[pallet::config] @@ -206,7 +230,13 @@ pub mod pallet { #[cfg(feature = "runtime-benchmarks")] /// A set of helper functions for benchmarking. - type Helper: BenchmarkHelper; + type Helper: BenchmarkHelper< + Self::CollectionId, + Self::ItemId, + Self::OffchainPublic, + Self::AccountId, + Self::OffchainSignature, + >; /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; diff --git a/substrate/frame/nfts/src/mock.rs b/substrate/frame/nfts/src/mock.rs index 51cfd5f244bcdb14fcdb1f66cff245df9030185f..5b589f591ca347a670becdc9557f24ec1a4e8520 100644 --- a/substrate/frame/nfts/src/mock.rs +++ b/substrate/frame/nfts/src/mock.rs @@ -53,20 +53,9 @@ impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type Balance = u64; - type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; - type ExistentialDeposit = ConstU64<1>; type AccountStore = System; - type WeightInfo = (); - type MaxLocks = (); - type MaxReserves = ConstU32<50>; - type ReserveIdentifier = [u8; 8]; - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } parameter_types! { diff --git a/substrate/frame/nis/Cargo.toml b/substrate/frame/nis/Cargo.toml index 1e3a0609c46bbfc40b044eae839f9bd0303e0178..418c906e2b66cfae53d475ff0007336cbe93b5ea 100644 --- a/substrate/frame/nis/Cargo.toml +++ b/substrate/frame/nis/Cargo.toml @@ -16,19 +16,19 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-arithmetic = { path = "../../primitives/arithmetic", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-arithmetic = { workspace = true } +sp-core = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -pallet-balances = { path = "../balances" } -sp-io = { path = "../../primitives/io" } +pallet-balances = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/node-authorization/Cargo.toml b/substrate/frame/node-authorization/Cargo.toml index 17ed16d2623368826f1ad93c6b4f5032775319cf..d16e9bc6ead6c3c4e17cd56e27ff504716725436 100644 --- a/substrate/frame/node-authorization/Cargo.toml +++ b/substrate/frame/node-authorization/Cargo.toml @@ -15,15 +15,15 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +scale-info = { features = ["derive"], workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-core = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/nomination-pools/Cargo.toml b/substrate/frame/nomination-pools/Cargo.toml index bf4e01a3184793d638b1c87f5984a517a18e2ceb..535d5252435f38d3dd85fd0d8c923b29c2e00f34 100644 --- a/substrate/frame/nomination-pools/Cargo.toml +++ b/substrate/frame/nomination-pools/Cargo.toml @@ -16,30 +16,30 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] # parity -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", -] } -scale-info = { version = "2.11.1", default-features = false, features = [ +], workspace = true } +scale-info = { features = [ "derive", -] } +], workspace = true } # FRAME -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -sp-staking = { path = "../../primitives/staking", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } +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 } log = { workspace = true } # Optional: use for testing and/or fuzzing -pallet-balances = { path = "../balances", optional = true, default-features = false } -sp-tracing = { path = "../../primitives/tracing", optional = true, default-features = false } +pallet-balances = { optional = true, workspace = true } +sp-tracing = { optional = true, workspace = true } [dev-dependencies] -pallet-balances = { path = "../balances" } -sp-tracing = { path = "../../primitives/tracing" } +pallet-balances = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/nomination-pools/benchmarking/Cargo.toml b/substrate/frame/nomination-pools/benchmarking/Cargo.toml index 3f9463a9c429b93da7cf5945a6ebd2ac46077196..1516f0154b88f91153e1c4872a297b56eb1bcb7b 100644 --- a/substrate/frame/nomination-pools/benchmarking/Cargo.toml +++ b/substrate/frame/nomination-pools/benchmarking/Cargo.toml @@ -17,31 +17,31 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] # parity -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } # FRAME -frame-benchmarking = { path = "../../benchmarking", default-features = false } -frame-election-provider-support = { path = "../../election-provider-support", default-features = false } -frame-support = { path = "../../support", default-features = false } -frame-system = { path = "../../system", default-features = false } -pallet-bags-list = { path = "../../bags-list", default-features = false } -pallet-staking = { path = "../../staking", default-features = false } -pallet-delegated-staking = { path = "../../delegated-staking", default-features = false } -pallet-nomination-pools = { path = "..", default-features = false } +frame-benchmarking = { workspace = true } +frame-election-provider-support = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-bags-list = { workspace = true } +pallet-staking = { workspace = true } +pallet-delegated-staking = { workspace = true } +pallet-nomination-pools = { workspace = true } # Substrate Primitives -sp-runtime = { path = "../../../primitives/runtime", default-features = false } -sp-runtime-interface = { path = "../../../primitives/runtime-interface", default-features = false } -sp-staking = { path = "../../../primitives/staking", default-features = false } -sp-std = { path = "../../../primitives/std", default-features = false } +sp-runtime = { workspace = true } +sp-runtime-interface = { workspace = true } +sp-staking = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -pallet-balances = { path = "../../balances", default-features = false } -pallet-timestamp = { path = "../../timestamp" } -pallet-staking-reward-curve = { path = "../../staking/reward-curve" } -sp-core = { path = "../../../primitives/core" } -sp-io = { path = "../../../primitives/io" } +pallet-balances = { workspace = true } +pallet-timestamp = { workspace = true, default-features = true } +pallet-staking-reward-curve = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/nomination-pools/benchmarking/src/mock.rs b/substrate/frame/nomination-pools/benchmarking/src/mock.rs index 7cbb61e00a31a3a657831119546aa40dc385bae7..15d9e2c56031fe1e47b7b0cef3139ca177ddeb67 100644 --- a/substrate/frame/nomination-pools/benchmarking/src/mock.rs +++ b/substrate/frame/nomination-pools/benchmarking/src/mock.rs @@ -17,7 +17,13 @@ use crate::VoterBagsListInstance; use frame_election_provider_support::VoteWeight; -use frame_support::{derive_impl, pallet_prelude::*, parameter_types, traits::ConstU64, PalletId}; +use frame_support::{ + derive_impl, + pallet_prelude::*, + parameter_types, + traits::{ConstU64, VariantCountOf}, + PalletId, +}; use sp_runtime::{ traits::{Convert, IdentityLookup}, BuildStorage, FixedU128, Perbill, @@ -45,20 +51,16 @@ impl pallet_timestamp::Config for Runtime { parameter_types! { pub const ExistentialDeposit: Balance = 10; } + +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Runtime { - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type WeightInfo = (); type FreezeIdentifier = RuntimeFreezeReason; - type MaxFreezes = ConstU32<1>; + type MaxFreezes = VariantCountOf; type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = (); + type RuntimeFreezeReason = RuntimeFreezeReason; } pallet_staking_reward_curve::build! { @@ -74,36 +76,19 @@ pallet_staking_reward_curve::build! { parameter_types! { pub const RewardCurve: &'static sp_runtime::curve::PiecewiseLinear<'static> = &I_NPOS; } +#[derive_impl(pallet_staking::config_preludes::TestDefaultConfig)] impl pallet_staking::Config for Runtime { type Currency = Balances; type CurrencyBalance = Balance; type UnixTime = pallet_timestamp::Pallet; - type CurrencyToVote = (); - type RewardRemainder = (); - type RuntimeEvent = RuntimeEvent; - type Slash = (); - type Reward = (); - type SessionsPerEra = (); - type SlashDeferDuration = (); type AdminOrigin = frame_system::EnsureRoot; - type BondingDuration = ConstU32<3>; - type SessionInterface = (); type EraPayout = pallet_staking::ConvertCurve; - type NextNewSession = (); - type MaxExposurePageSize = ConstU32<64>; type ElectionProvider = frame_election_provider_support::NoElection<(AccountId, BlockNumber, Staking, ())>; type GenesisElectionProvider = Self::ElectionProvider; type VoterList = VoterList; type TargetList = pallet_staking::UseValidatorsMap; - type NominationsQuota = pallet_staking::FixedNominationsQuota<16>; - type MaxControllersInDeprecationBatch = ConstU32<100>; - type MaxUnlockingChunks = ConstU32<32>; - type HistoryDepth = ConstU32<84>; type EventListeners = (Pools, DelegatedStaking); - type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; - type WeightInfo = (); - type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; } parameter_types! { diff --git a/substrate/frame/nomination-pools/fuzzer/Cargo.toml b/substrate/frame/nomination-pools/fuzzer/Cargo.toml index c0d63a2685937a10e6a53288403099bc78ed1fa9..7c45dcef256fb9b91ec04d309794cf5cd61cda91 100644 --- a/substrate/frame/nomination-pools/fuzzer/Cargo.toml +++ b/substrate/frame/nomination-pools/fuzzer/Cargo.toml @@ -17,18 +17,18 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -honggfuzz = "0.5.54" +honggfuzz = { workspace = true } -pallet-nomination-pools = { path = "..", features = ["fuzzing"] } +pallet-nomination-pools = { features = ["fuzzing"], workspace = true, default-features = true } -frame-system = { path = "../../system" } -frame-support = { path = "../../support" } +frame-system = { workspace = true, default-features = true } +frame-support = { workspace = true, default-features = true } -sp-runtime = { path = "../../../primitives/runtime" } -sp-io = { path = "../../../primitives/io" } -sp-tracing = { path = "../../../primitives/tracing" } +sp-runtime = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } -rand = { version = "0.8.5", features = ["small_rng"] } +rand = { features = ["small_rng"], workspace = true, default-features = true } log = { workspace = true, default-features = true } [[bin]] diff --git a/substrate/frame/nomination-pools/runtime-api/Cargo.toml b/substrate/frame/nomination-pools/runtime-api/Cargo.toml index a0ddac9e045675aefe7b8139e0048f3399663da8..2b217e021455fddac8fc1c7efe5719901c7f1d9f 100644 --- a/substrate/frame/nomination-pools/runtime-api/Cargo.toml +++ b/substrate/frame/nomination-pools/runtime-api/Cargo.toml @@ -16,10 +16,10 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -sp-api = { path = "../../../primitives/api", default-features = false } -sp-std = { path = "../../../primitives/std", default-features = false } -pallet-nomination-pools = { path = "..", default-features = false } +codec = { features = ["derive"], workspace = true } +sp-api = { workspace = true } +sp-std = { workspace = true } +pallet-nomination-pools = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/nomination-pools/src/mock.rs b/substrate/frame/nomination-pools/src/mock.rs index 93fe6aa56054d9ec65b91884673d30d1651ca35d..6c0082073f6827a5d264281bc29e08b708233e35 100644 --- a/substrate/frame/nomination-pools/src/mock.rs +++ b/substrate/frame/nomination-pools/src/mock.rs @@ -18,7 +18,8 @@ use super::*; use crate::{self as pools}; use frame_support::{ - assert_ok, derive_impl, ord_parameter_types, parameter_types, traits::fungible::Mutate, + assert_ok, derive_impl, ord_parameter_types, parameter_types, + traits::{fungible::Mutate, VariantCountOf}, PalletId, }; use frame_system::{EnsureSignedBy, RawOrigin}; @@ -251,20 +252,14 @@ parameter_types! { pub static ExistentialDeposit: Balance = 5; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Runtime { - type MaxLocks = frame_support::traits::ConstU32<1024>; - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type WeightInfo = (); type FreezeIdentifier = RuntimeFreezeReason; - type MaxFreezes = ConstU32<1>; - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); + type MaxFreezes = VariantCountOf; + type RuntimeFreezeReason = RuntimeFreezeReason; } pub struct BalanceToU256; diff --git a/substrate/frame/nomination-pools/test-delegate-stake/Cargo.toml b/substrate/frame/nomination-pools/test-delegate-stake/Cargo.toml index ea8eb20696931f8c45edc6f67e4d5af49412eccd..ea50dd6d732d30007afee75108cb3d62616712f8 100644 --- a/substrate/frame/nomination-pools/test-delegate-stake/Cargo.toml +++ b/substrate/frame/nomination-pools/test-delegate-stake/Cargo.toml @@ -16,26 +16,26 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dev-dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } -scale-info = { version = "2.11.1", features = ["derive"] } +codec = { features = ["derive"], workspace = true, default-features = true } +scale-info = { features = ["derive"], workspace = true, default-features = true } -sp-runtime = { path = "../../../primitives/runtime" } -sp-io = { path = "../../../primitives/io" } -sp-std = { path = "../../../primitives/std" } -sp-staking = { path = "../../../primitives/staking" } -sp-core = { path = "../../../primitives/core" } +sp-runtime = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-std = { workspace = true, default-features = true } +sp-staking = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } -frame-system = { path = "../../system" } -frame-support = { path = "../../support" } -frame-election-provider-support = { path = "../../election-provider-support" } +frame-system = { workspace = true, default-features = true } +frame-support = { workspace = true, default-features = true } +frame-election-provider-support = { workspace = true, default-features = true } -pallet-timestamp = { path = "../../timestamp" } -pallet-balances = { path = "../../balances" } -pallet-staking = { path = "../../staking" } -pallet-delegated-staking = { path = "../../delegated-staking" } -pallet-bags-list = { path = "../../bags-list" } -pallet-staking-reward-curve = { path = "../../staking/reward-curve" } -pallet-nomination-pools = { path = ".." } +pallet-timestamp = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +pallet-staking = { workspace = true, default-features = true } +pallet-delegated-staking = { workspace = true, default-features = true } +pallet-bags-list = { workspace = true, default-features = true } +pallet-staking-reward-curve = { workspace = true, default-features = true } +pallet-nomination-pools = { workspace = true, default-features = true } -sp-tracing = { path = "../../../primitives/tracing" } +sp-tracing = { workspace = true, default-features = true } log = { workspace = true, default-features = true } diff --git a/substrate/frame/nomination-pools/test-delegate-stake/src/mock.rs b/substrate/frame/nomination-pools/test-delegate-stake/src/mock.rs index 820f2b7718ce4ee0d977a096aa132f87536bd8ee..ed47932a323bf14335d5bb74fec03cfa749625e3 100644 --- a/substrate/frame/nomination-pools/test-delegate-stake/src/mock.rs +++ b/substrate/frame/nomination-pools/test-delegate-stake/src/mock.rs @@ -20,7 +20,7 @@ use frame_support::{ assert_ok, derive_impl, pallet_prelude::*, parameter_types, - traits::{ConstU64, ConstU8}, + traits::{ConstU64, ConstU8, VariantCountOf}, PalletId, }; use frame_system::EnsureRoot; @@ -63,20 +63,15 @@ parameter_types! { pub static ExistentialDeposit: Balance = 5; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Runtime { - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type WeightInfo = (); type FreezeIdentifier = RuntimeFreezeReason; - type MaxFreezes = ConstU32<1>; + type MaxFreezes = VariantCountOf; type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = (); + type RuntimeFreezeReason = RuntimeFreezeReason; } pallet_staking_reward_curve::build! { @@ -95,36 +90,20 @@ parameter_types! { pub static BondingDuration: u32 = 3; } +#[derive_impl(pallet_staking::config_preludes::TestDefaultConfig)] impl pallet_staking::Config for Runtime { type Currency = Balances; - type CurrencyBalance = Balance; type UnixTime = pallet_timestamp::Pallet; - type CurrencyToVote = (); - type RewardRemainder = (); - type RuntimeEvent = RuntimeEvent; - type Slash = (); - type Reward = (); - type SessionsPerEra = (); - type SlashDeferDuration = (); type AdminOrigin = frame_system::EnsureRoot; type BondingDuration = BondingDuration; - type SessionInterface = (); type EraPayout = pallet_staking::ConvertCurve; - type NextNewSession = (); - type MaxExposurePageSize = ConstU32<64>; type ElectionProvider = frame_election_provider_support::NoElection<(AccountId, BlockNumber, Staking, ())>; type GenesisElectionProvider = Self::ElectionProvider; type VoterList = VoterList; type TargetList = pallet_staking::UseValidatorsMap; - type NominationsQuota = pallet_staking::FixedNominationsQuota<16>; - type MaxUnlockingChunks = ConstU32<32>; - type MaxControllersInDeprecationBatch = ConstU32<100>; - type HistoryDepth = ConstU32<84>; type EventListeners = (Pools, DelegatedStaking); type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; - type WeightInfo = (); - type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; } parameter_types! { diff --git a/substrate/frame/nomination-pools/test-transfer-stake/Cargo.toml b/substrate/frame/nomination-pools/test-transfer-stake/Cargo.toml index 5f9bc9af3a214eb3d82da11786c93bf462565a26..8bc5676cfe91640dcc8cf1fb6bd895db41a0f5a2 100644 --- a/substrate/frame/nomination-pools/test-transfer-stake/Cargo.toml +++ b/substrate/frame/nomination-pools/test-transfer-stake/Cargo.toml @@ -16,25 +16,25 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dev-dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } -scale-info = { version = "2.11.1", features = ["derive"] } +codec = { features = ["derive"], workspace = true, default-features = true } +scale-info = { features = ["derive"], workspace = true, default-features = true } -sp-runtime = { path = "../../../primitives/runtime" } -sp-io = { path = "../../../primitives/io" } -sp-std = { path = "../../../primitives/std" } -sp-staking = { path = "../../../primitives/staking" } -sp-core = { path = "../../../primitives/core" } +sp-runtime = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-std = { workspace = true, default-features = true } +sp-staking = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } -frame-system = { path = "../../system" } -frame-support = { path = "../../support" } -frame-election-provider-support = { path = "../../election-provider-support" } +frame-system = { workspace = true, default-features = true } +frame-support = { workspace = true, default-features = true } +frame-election-provider-support = { workspace = true, default-features = true } -pallet-timestamp = { path = "../../timestamp" } -pallet-balances = { path = "../../balances" } -pallet-staking = { path = "../../staking" } -pallet-bags-list = { path = "../../bags-list" } -pallet-staking-reward-curve = { path = "../../staking/reward-curve" } -pallet-nomination-pools = { path = ".." } +pallet-timestamp = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +pallet-staking = { workspace = true, default-features = true } +pallet-bags-list = { workspace = true, default-features = true } +pallet-staking-reward-curve = { workspace = true, default-features = true } +pallet-nomination-pools = { workspace = true, default-features = true } -sp-tracing = { path = "../../../primitives/tracing" } +sp-tracing = { workspace = true, default-features = true } log = { workspace = true, default-features = true } diff --git a/substrate/frame/nomination-pools/test-transfer-stake/src/mock.rs b/substrate/frame/nomination-pools/test-transfer-stake/src/mock.rs index eb9d463424c8e74089563d6dc2004ddb4a9ef2e5..d913c5fe6948cb5a0fae1d5ccf8e533e5ddb8cc7 100644 --- a/substrate/frame/nomination-pools/test-transfer-stake/src/mock.rs +++ b/substrate/frame/nomination-pools/test-transfer-stake/src/mock.rs @@ -20,7 +20,7 @@ use frame_support::{ assert_ok, derive_impl, pallet_prelude::*, parameter_types, - traits::{ConstU64, ConstU8}, + traits::{ConstU64, ConstU8, VariantCountOf}, PalletId, }; use sp_runtime::{ @@ -56,20 +56,14 @@ parameter_types! { pub static ExistentialDeposit: Balance = 5; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Runtime { - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type WeightInfo = (); type FreezeIdentifier = RuntimeFreezeReason; - type MaxFreezes = ConstU32<1>; - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); + type MaxFreezes = VariantCountOf; + type RuntimeFreezeReason = RuntimeFreezeReason; } pallet_staking_reward_curve::build! { @@ -88,36 +82,20 @@ parameter_types! { pub static BondingDuration: u32 = 3; } +#[derive_impl(pallet_staking::config_preludes::TestDefaultConfig)] impl pallet_staking::Config for Runtime { type Currency = Balances; - type CurrencyBalance = Balance; type UnixTime = pallet_timestamp::Pallet; - type CurrencyToVote = (); - type RewardRemainder = (); - type RuntimeEvent = RuntimeEvent; - type Slash = (); - type Reward = (); - type SessionsPerEra = (); - type SlashDeferDuration = (); type AdminOrigin = frame_system::EnsureRoot; type BondingDuration = BondingDuration; - type SessionInterface = (); type EraPayout = pallet_staking::ConvertCurve; - type NextNewSession = (); - type MaxExposurePageSize = ConstU32<64>; type ElectionProvider = frame_election_provider_support::NoElection<(AccountId, BlockNumber, Staking, ())>; type GenesisElectionProvider = Self::ElectionProvider; type VoterList = VoterList; type TargetList = pallet_staking::UseValidatorsMap; - type NominationsQuota = pallet_staking::FixedNominationsQuota<16>; - type MaxUnlockingChunks = ConstU32<32>; - type MaxControllersInDeprecationBatch = ConstU32<100>; - type HistoryDepth = ConstU32<84>; type EventListeners = Pools; type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; - type WeightInfo = (); - type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; } parameter_types! { diff --git a/substrate/frame/offences/Cargo.toml b/substrate/frame/offences/Cargo.toml index a59ef9334f0bc3cba6a92943a1cbbdbe4d3c94d1..51eb3e4f4381797202b8648e59a0378c56ae72e6 100644 --- a/substrate/frame/offences/Cargo.toml +++ b/substrate/frame/offences/Cargo.toml @@ -16,20 +16,20 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } serde = { optional = true, workspace = true, default-features = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -pallet-balances = { path = "../balances", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-staking = { path = "../../primitives/staking", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-balances = { workspace = true } +sp-runtime = { workspace = true } +sp-staking = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -sp-core = { path = "../../primitives/core" } -sp-io = { path = "../../primitives/io" } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/offences/benchmarking/Cargo.toml b/substrate/frame/offences/benchmarking/Cargo.toml index bbd918a2883f30afb82310424375eb3ed5b5a8e8..037812b3ed114a0f5d7f8111ba83fe9da4ca9dd1 100644 --- a/substrate/frame/offences/benchmarking/Cargo.toml +++ b/substrate/frame/offences/benchmarking/Cargo.toml @@ -16,29 +16,29 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../../benchmarking", default-features = false } -frame-election-provider-support = { path = "../../election-provider-support", default-features = false } -frame-support = { path = "../../support", default-features = false } -frame-system = { path = "../../system", default-features = false } -pallet-babe = { path = "../../babe", default-features = false } -pallet-balances = { path = "../../balances", default-features = false } -pallet-grandpa = { path = "../../grandpa", default-features = false } -pallet-im-online = { path = "../../im-online", default-features = false } -pallet-offences = { path = "..", default-features = false } -pallet-session = { path = "../../session", default-features = false } -pallet-staking = { path = "../../staking", default-features = false } -sp-runtime = { path = "../../../primitives/runtime", default-features = false } -sp-staking = { path = "../../../primitives/staking", default-features = false } -sp-std = { path = "../../../primitives/std", default-features = false } +codec = { workspace = true } +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { workspace = true } +frame-election-provider-support = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-babe = { workspace = true } +pallet-balances = { workspace = true } +pallet-grandpa = { workspace = true } +pallet-im-online = { workspace = true } +pallet-offences = { workspace = true } +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] -pallet-staking-reward-curve = { path = "../../staking/reward-curve" } -pallet-timestamp = { path = "../../timestamp" } -sp-core = { path = "../../../primitives/core" } -sp-io = { path = "../../../primitives/io" } +pallet-staking-reward-curve = { workspace = true, default-features = true } +pallet-timestamp = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/offences/benchmarking/src/mock.rs b/substrate/frame/offences/benchmarking/src/mock.rs index 6cbdde5785282875c01cfa44c897cfa6d134fd55..e243ad0e718eb85fadca375dbf9e883635653972 100644 --- a/substrate/frame/offences/benchmarking/src/mock.rs +++ b/substrate/frame/offences/benchmarking/src/mock.rs @@ -41,20 +41,10 @@ impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxLocks = ConstU32<128>; - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); type ExistentialDeposit = ConstU64<10>; type AccountStore = System; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } impl pallet_timestamp::Config for Test { @@ -134,35 +124,19 @@ impl onchain::Config for OnChainSeqPhragmen { type Bounds = ElectionsBounds; } +#[derive_impl(pallet_staking::config_preludes::TestDefaultConfig)] impl pallet_staking::Config for Test { type Currency = Balances; type CurrencyBalance = ::Balance; type UnixTime = pallet_timestamp::Pallet; - type CurrencyToVote = (); - type RewardRemainder = (); - type RuntimeEvent = RuntimeEvent; - type Slash = (); - type Reward = (); - type SessionsPerEra = (); - type SlashDeferDuration = (); type AdminOrigin = frame_system::EnsureRoot; - type BondingDuration = (); type SessionInterface = Self; type EraPayout = pallet_staking::ConvertCurve; type NextNewSession = Session; - type MaxExposurePageSize = ConstU32<64>; type ElectionProvider = onchain::OnChainExecution; type GenesisElectionProvider = Self::ElectionProvider; type VoterList = pallet_staking::UseNominatorsAndValidatorsMap; type TargetList = pallet_staking::UseValidatorsMap; - type NominationsQuota = pallet_staking::FixedNominationsQuota<16>; - type MaxUnlockingChunks = ConstU32<32>; - type MaxControllersInDeprecationBatch = ConstU32<100>; - type HistoryDepth = ConstU32<84>; - type EventListeners = (); - type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; - type WeightInfo = (); - type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; } impl pallet_im_online::Config for Test { diff --git a/substrate/frame/paged-list/Cargo.toml b/substrate/frame/paged-list/Cargo.toml index f550e694349468efcca9bacf51242d378b64ba64..f5a3a2e5bae196736f9a07943fdc78a42436bba8 100644 --- a/substrate/frame/paged-list/Cargo.toml +++ b/substrate/frame/paged-list/Cargo.toml @@ -15,19 +15,19 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -docify = "0.2.8" -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } - -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } - -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-metadata-ir = { path = "../../primitives/metadata-ir", default-features = false, optional = true } +codec = { features = ["derive"], workspace = true } +docify = { workspace = true } +scale-info = { features = ["derive"], workspace = true } + +frame-benchmarking = { optional = true, workspace = true } +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 } [features] default = ["std"] diff --git a/substrate/frame/paged-list/fuzzer/Cargo.toml b/substrate/frame/paged-list/fuzzer/Cargo.toml index 6ff07ba1ddd2fa3571e65a8e29c53e5ef324c0de..bfdacfd8dd03f0f31e901c63fcb9858923bbdd0a 100644 --- a/substrate/frame/paged-list/fuzzer/Cargo.toml +++ b/substrate/frame/paged-list/fuzzer/Cargo.toml @@ -17,9 +17,9 @@ name = "pallet-paged-list-fuzzer" path = "src/paged_list.rs" [dependencies] -arbitrary = "1.3.2" -honggfuzz = "0.5.49" +arbitrary = { workspace = true } +honggfuzz = { workspace = true } -frame-support = { path = "../../support", default-features = false, features = ["std"] } -sp-io = { path = "../../../primitives/io", default-features = false, features = ["std"] } -pallet-paged-list = { path = "..", default-features = false, features = ["std"] } +frame-support = { features = ["std"], workspace = true } +sp-io = { features = ["std"], workspace = true } +pallet-paged-list = { features = ["std"], workspace = true } diff --git a/substrate/frame/parameters/Cargo.toml b/substrate/frame/parameters/Cargo.toml index c4d6d189d2d2c2a33a428cdcf3290c629464662b..b993347d24637a5ffa84c238eeb6fb75bbcb9d64 100644 --- a/substrate/frame/parameters/Cargo.toml +++ b/substrate/frame/parameters/Cargo.toml @@ -8,24 +8,24 @@ authors = ["Acala Developers", "Parity Technologies "] edition.workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["max-encoded-len"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -paste = { version = "1.0.14", default-features = false } +codec = { features = ["max-encoded-len"], workspace = true } +scale-info = { features = ["derive"], workspace = true } +paste = { workspace = true } serde = { features = ["derive"], optional = true, workspace = true, default-features = true } -docify = "0.2.8" +docify = { workspace = true } -frame-support = { path = "../support", default-features = false, features = ["experimental"] } -frame-system = { path = "../system", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } +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] -sp-core = { path = "../../primitives/core", features = ["std"] } -sp-io = { path = "../../primitives/io", features = ["std"] } -pallet-example-basic = { path = "../examples/basic", features = ["std"] } -pallet-balances = { path = "../balances", features = ["std"] } +sp-core = { features = ["std"], workspace = true, default-features = true } +sp-io = { features = ["std"], workspace = true, default-features = true } +pallet-example-basic = { features = ["std"], workspace = true, default-features = true } +pallet-balances = { features = ["std"], workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/parameters/src/tests/mock.rs b/substrate/frame/parameters/src/tests/mock.rs index 6cfd7c8f30b8119ff1e1f0a63165c98afba1577b..53a3b3e394c4b7c5d8410ba6e1af758d78cbf8ae 100644 --- a/substrate/frame/parameters/src/tests/mock.rs +++ b/substrate/frame/parameters/src/tests/mock.rs @@ -37,7 +37,6 @@ impl frame_system::Config for Runtime { #[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Runtime { - type ReserveIdentifier = [u8; 8]; type AccountStore = System; } diff --git a/substrate/frame/parameters/src/tests/test_renamed.rs b/substrate/frame/parameters/src/tests/test_renamed.rs index cfc870fbe1096aeeab930d548e6455427962d62a..7c371c5e55f874c01fffde081bb65b551c75d5b3 100644 --- a/substrate/frame/parameters/src/tests/test_renamed.rs +++ b/substrate/frame/parameters/src/tests/test_renamed.rs @@ -39,7 +39,6 @@ impl frame_system::Config for Runtime { #[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Runtime { - type ReserveIdentifier = [u8; 8]; type AccountStore = System; } diff --git a/substrate/frame/preimage/Cargo.toml b/substrate/frame/preimage/Cargo.toml index d420accbd6d914816d00a57879d7187f0d0d4ead..ee572b189b231054c0bea0e429c7a4659e9aa301 100644 --- a/substrate/frame/preimage/Cargo.toml +++ b/substrate/frame/preimage/Cargo.toml @@ -12,20 +12,20 @@ description = "FRAME pallet for storing preimages of hashes" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false, optional = true } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +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] -pallet-balances = { path = "../balances" } -sp-core = { path = "../../primitives/core", default-features = false } +pallet-balances = { workspace = true, default-features = true } +sp-core = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/preimage/src/benchmarking.rs b/substrate/frame/preimage/src/benchmarking.rs index d0c3404f40a911cf32d620858b97652b242f2be8..f2b76a7999d6c61827624b3b9ca6d9e55a0341d9 100644 --- a/substrate/frame/preimage/src/benchmarking.rs +++ b/substrate/frame/preimage/src/benchmarking.rs @@ -116,7 +116,7 @@ benchmarks! { T::ManagerOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?, hash ) verify { - let ticket = TicketOf::::new(¬er, Footprint { count: 1, size: MAX_SIZE as u64 }).unwrap(); + let ticket = TicketOf::::new(¬er, Footprint { count: 1, size: MAX_SIZE as u64 }).unwrap().unwrap(); let s = RequestStatus::Requested { maybe_ticket: Some((noter, ticket)), count: 1, maybe_len: Some(MAX_SIZE) }; assert_eq!(RequestStatusFor::::get(&hash), Some(s)); } diff --git a/substrate/frame/preimage/src/lib.rs b/substrate/frame/preimage/src/lib.rs index 4e474685166631ba41eed644d3754a332a290663..dd323a12b8f8479ba5d419243c9585f79ac0385a 100644 --- a/substrate/frame/preimage/src/lib.rs +++ b/substrate/frame/preimage/src/lib.rs @@ -122,7 +122,9 @@ pub mod pallet { type ManagerOrigin: EnsureOrigin; /// A means of providing some cost while data is stored on-chain. - type Consideration: Consideration; + /// + /// Should never return a `None`, implying no cost for a non-empty preimage. + type Consideration: Consideration; } #[pallet::pallet] @@ -158,6 +160,8 @@ pub mod pallet { TooMany, /// Too few hashes were requested to be upgraded (i.e. zero). TooFew, + /// No ticket with a cost was returned by [`Config::Consideration`] to store the preimage. + NoCost, } /// A reason for this pallet placing a hold on funds. @@ -268,10 +272,10 @@ impl Pallet { // unreserve deposit T::Currency::unreserve(&who, amount); // take consideration - let Ok(ticket) = + let Ok(Some(ticket)) = T::Consideration::new(&who, Footprint::from_parts(1, len as usize)) - .defensive_proof("Unexpected inability to take deposit after unreserved") else { + defensive!("None ticket or inability to take deposit after unreserved"); return true }; RequestStatus::Unrequested { ticket: (who, ticket), len } @@ -282,12 +286,10 @@ impl Pallet { T::Currency::unreserve(&who, deposit); // take consideration if let Some(len) = maybe_len { - let Ok(ticket) = + let Ok(Some(ticket)) = T::Consideration::new(&who, Footprint::from_parts(1, len as usize)) - .defensive_proof( - "Unexpected inability to take deposit after unreserved", - ) else { + defensive!("None ticket or inability to take deposit after unreserved"); return true }; Some((who, ticket)) @@ -347,7 +349,8 @@ impl Pallet { RequestStatus::Requested { maybe_ticket: None, count: 1, maybe_len: Some(len) }, (None, Some(depositor)) => { let ticket = - T::Consideration::new(depositor, Footprint::from_parts(1, len as usize))?; + T::Consideration::new(depositor, Footprint::from_parts(1, len as usize))? + .ok_or(Error::::NoCost)?; RequestStatus::Unrequested { ticket: (depositor.clone(), ticket), len } }, }; diff --git a/substrate/frame/preimage/src/mock.rs b/substrate/frame/preimage/src/mock.rs index 903c34596aebacfd7116f1b172d54f9ed26f6426..9c72d09cae1463395aaebe1e06f95d5e22cced9f 100644 --- a/substrate/frame/preimage/src/mock.rs +++ b/substrate/frame/preimage/src/mock.rs @@ -22,7 +22,7 @@ use super::*; use crate as pallet_preimage; use frame_support::{ derive_impl, ord_parameter_types, parameter_types, - traits::{fungible::HoldConsideration, ConstU32, ConstU64}, + traits::{fungible::HoldConsideration, ConstU64}, }; use frame_system::EnsureSignedBy; use sp_core::H256; @@ -48,20 +48,10 @@ impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type Balance = u64; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); type ExistentialDeposit = ConstU64<5>; type AccountStore = System; - type WeightInfo = (); - type MaxLocks = (); - type MaxReserves = ConstU32<50>; - type ReserveIdentifier = [u8; 8]; - type FreezeIdentifier = (); - type MaxFreezes = ConstU32<1>; - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = (); } ord_parameter_types! { diff --git a/substrate/frame/proxy/Cargo.toml b/substrate/frame/proxy/Cargo.toml index fcebbb5f3e8a077c8505f333b073d384fb1646b2..6b4251e1bcc57b8017a6bb76c99fc3aea94d6345 100644 --- a/substrate/frame/proxy/Cargo.toml +++ b/substrate/frame/proxy/Cargo.toml @@ -16,19 +16,19 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["max-encoded-len"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +codec = { features = ["max-encoded-len"], workspace = true } +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -pallet-balances = { path = "../balances" } -pallet-utility = { path = "../utility" } -sp-core = { path = "../../primitives/core" } +pallet-balances = { workspace = true, default-features = true } +pallet-utility = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/ranked-collective/Cargo.toml b/substrate/frame/ranked-collective/Cargo.toml index 05ce76cad2bbe133a77e9c318ce8f32a57f3a659..be48d5cad4048b90e0b08971f6b005b125adaf59 100644 --- a/substrate/frame/ranked-collective/Cargo.toml +++ b/substrate/frame/ranked-collective/Cargo.toml @@ -16,18 +16,18 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-arithmetic = { path = "../../primitives/arithmetic", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -impl-trait-for-tuples = "0.2.2" +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +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] default = ["std"] diff --git a/substrate/frame/ranked-collective/src/lib.rs b/substrate/frame/ranked-collective/src/lib.rs index ceaf03de211008ee49bf4a4a1fc961bf8825971a..53d5f0c6662d760534e87bf6962aca491fe4e617 100644 --- a/substrate/frame/ranked-collective/src/lib.rs +++ b/substrate/frame/ranked-collective/src/lib.rs @@ -379,6 +379,7 @@ pub mod pallet { use super::*; use frame_support::{pallet_prelude::*, storage::KeyLenOf}; use frame_system::pallet_prelude::*; + use sp_runtime::traits::MaybeConvert; #[pallet::pallet] pub struct Pallet(PhantomData<(T, I)>); @@ -431,6 +432,14 @@ pub mod pallet { /// in the poll. type VoteWeight: Convert; + /// The maximum number of members for a given rank in the collective. + /// + /// The member at rank `x` contributes to the count at rank `x` and all ranks below it. + /// Therefore, the limit `m` at rank `x` sets the maximum total member count for rank `x` + /// and all ranks above. + /// The `None` indicates no member count limit for the given rank. + type MaxMemberCount: MaybeConvert; + /// Setup a member for benchmarking. #[cfg(feature = "runtime-benchmarks")] type BenchmarkSetup: BenchmarkSetup; @@ -511,6 +520,8 @@ pub mod pallet { NoPermission, /// The new member to exchange is the same as the old member SameMember, + /// The max member count for the rank has been reached. + TooManyMembers, } #[pallet::call] @@ -758,6 +769,9 @@ pub mod pallet { ensure!(!Members::::contains_key(&who), Error::::AlreadyMember); let index = MemberCount::::get(0); let count = index.checked_add(1).ok_or(Overflow)?; + if let Some(max) = T::MaxMemberCount::maybe_convert(0) { + ensure!(count <= max, Error::::TooManyMembers); + } Members::::insert(&who, MemberRecord { rank: 0 }); IdToIndex::::insert(0, &who, index); @@ -784,6 +798,11 @@ pub mod pallet { ensure!(max_rank >= rank, Error::::NoPermission); } let index = MemberCount::::get(rank); + let count = index.checked_add(1).ok_or(Overflow)?; + if let Some(max) = T::MaxMemberCount::maybe_convert(rank) { + ensure!(count <= max, Error::::TooManyMembers); + } + MemberCount::::insert(rank, index.checked_add(1).ok_or(Overflow)?); IdToIndex::::insert(rank, &who, index); IndexToId::::insert(rank, index, &who); diff --git a/substrate/frame/ranked-collective/src/tests.rs b/substrate/frame/ranked-collective/src/tests.rs index ad8b7d2a8018bb0566f9b851cf64433791a1c1ce..a7827bcc1aa379f6a28d0755feb555ad487f4426 100644 --- a/substrate/frame/ranked-collective/src/tests.rs +++ b/substrate/frame/ranked-collective/src/tests.rs @@ -27,7 +27,7 @@ use frame_support::{ }; use sp_core::Get; use sp_runtime::{ - traits::{ReduceBy, ReplaceWithDefault}, + traits::{MaybeConvert, ReduceBy, ReplaceWithDefault}, BuildStorage, }; @@ -148,6 +148,17 @@ impl> Convert for MinRankOfClass { } } +pub struct MaxMemberCount; +impl MaybeConvert for MaxMemberCount { + fn maybe_convert(a: Rank) -> Option { + if a == 11 { + Some(2) + } else { + None + } + } +} + parameter_types! { pub static MinRankOfClassDelta: Rank = 0; } @@ -179,6 +190,7 @@ impl Config for Test { type MinRankOfClass = MinRankOfClass; type MemberSwappedHandler = (); type VoteWeight = Geometric; + type MaxMemberCount = MaxMemberCount; #[cfg(feature = "runtime-benchmarks")] type BenchmarkSetup = (); } @@ -645,3 +657,32 @@ fn exchange_member_same_noops() { ); }); } + +#[test] +fn max_member_count_works() { + ExtBuilder::default().build_and_execute(|| { + assert_ok!(Club::do_add_member_to_rank(1, 10, false)); + assert_ok!(Club::do_add_member_to_rank(2, 10, false)); + assert_ok!(Club::do_add_member_to_rank(3, 10, false)); + assert_eq!(member_count(10), 3); + assert_eq!(member_count(11), 0); + + assert_ok!(Club::promote_member(RuntimeOrigin::root(), 1)); + assert_ok!(Club::promote_member(RuntimeOrigin::root(), 2)); + assert_noop!(Club::promote_member(RuntimeOrigin::root(), 3), Error::::TooManyMembers); + assert_eq!(member_count(10), 3); + assert_eq!(member_count(11), 2); + + assert_ok!(Club::demote_member(RuntimeOrigin::root(), 1)); + assert_ok!(Club::promote_member(RuntimeOrigin::root(), 3)); + assert_eq!(member_count(10), 3); + assert_eq!(member_count(11), 2); + + assert_ok!(Club::promote_member(RuntimeOrigin::root(), 2)); + assert_ok!(Club::promote_member(RuntimeOrigin::root(), 3)); + assert_noop!(Club::promote_member(RuntimeOrigin::root(), 1), Error::::TooManyMembers); + assert_eq!(member_count(10), 3); + assert_eq!(member_count(11), 2); + assert_eq!(member_count(12), 2); + }); +} diff --git a/substrate/frame/recovery/Cargo.toml b/substrate/frame/recovery/Cargo.toml index 2fd63597da9caf7ede188eb4a0e70a7d809bae05..3b3a382fe6dcf8ccde7d4681b835674149896715 100644 --- a/substrate/frame/recovery/Cargo.toml +++ b/substrate/frame/recovery/Cargo.toml @@ -16,18 +16,18 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -pallet-balances = { path = "../balances" } -sp-core = { path = "../../primitives/core" } +pallet-balances = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/recovery/src/mock.rs b/substrate/frame/recovery/src/mock.rs index bec7e02c128bbfc2c9975d881ac5210cd31aa56f..8e30cbe997e17b80e8ef74a598b15343e6affdef 100644 --- a/substrate/frame/recovery/src/mock.rs +++ b/substrate/frame/recovery/src/mock.rs @@ -47,20 +47,11 @@ parameter_types! { pub const ExistentialDeposit: u64 = 1; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; type Balance = u128; - type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } parameter_types! { diff --git a/substrate/frame/referenda/Cargo.toml b/substrate/frame/referenda/Cargo.toml index dde522ff89b59a647e87dd8436cb32bf1bb0274f..eb30fef7894b48a7a5f0685c76d96a88a0fdd43b 100644 --- a/substrate/frame/referenda/Cargo.toml +++ b/substrate/frame/referenda/Cargo.toml @@ -16,27 +16,27 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -assert_matches = { version = "1.5", optional = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +assert_matches = { optional = true, workspace = true } +codec = { features = [ "derive", -] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +], workspace = true } +scale-info = { features = ["derive"], workspace = true } serde = { features = ["derive"], optional = true, workspace = true, default-features = true } -sp-arithmetic = { path = "../../primitives/arithmetic", default-features = false } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +sp-arithmetic = { workspace = true } +frame-benchmarking = { optional = true, workspace = true } +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] -assert_matches = { version = "1.5" } -pallet-balances = { path = "../balances" } -pallet-preimage = { path = "../preimage" } -pallet-scheduler = { path = "../scheduler" } -sp-core = { path = "../../primitives/core" } +assert_matches = { workspace = true } +pallet-balances = { workspace = true, default-features = true } +pallet-preimage = { workspace = true, default-features = true } +pallet-scheduler = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/referenda/src/lib.rs b/substrate/frame/referenda/src/lib.rs index fbe27e1a4784733f517bb6ee3259ebdc4b1075b3..0cdf450d3b6c98e942e3613210f31eb34098b008 100644 --- a/substrate/frame/referenda/src/lib.rs +++ b/substrate/frame/referenda/src/lib.rs @@ -891,7 +891,8 @@ impl, I: 'static> Pallet { call: BoundedCallOf, ) { let now = frame_system::Pallet::::block_number(); - let earliest_allowed = now.saturating_add(track.min_enactment_period); + // Earliest allowed block is always at minimum the next block. + let earliest_allowed = now.saturating_add(track.min_enactment_period.max(One::one())); let desired = desired.evaluate(now); let ok = T::Scheduler::schedule_named( (ASSEMBLY_ID, "enactment", index).using_encoded(sp_io::hashing::blake2_256), diff --git a/substrate/frame/referenda/src/mock.rs b/substrate/frame/referenda/src/mock.rs index 135476d7cb1373ea1e7d3164e9df9d5b9dfc36ee..bf0fa4e1a12e17a90f2d35fd555d5805765b26be 100644 --- a/substrate/frame/referenda/src/mock.rs +++ b/substrate/frame/referenda/src/mock.rs @@ -83,20 +83,9 @@ impl pallet_scheduler::Config for Test { type OriginPrivilegeCmp = EqualPrivilegeOnly; type Preimages = Preimage; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type MaxLocks = ConstU32<10>; - type Balance = u64; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ConstU64<1>; type AccountStore = System; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } parameter_types! { pub static AlarmInterval: u64 = 1; @@ -123,7 +112,7 @@ impl TracksInfo for TestTracksInfo { type Id = u8; type RuntimeOrigin = ::PalletsOrigin; fn tracks() -> &'static [(Self::Id, TrackInfo)] { - static DATA: [(u8, TrackInfo); 2] = [ + static DATA: [(u8, TrackInfo); 3] = [ ( 0u8, TrackInfo { @@ -168,6 +157,28 @@ impl TracksInfo for TestTracksInfo { }, }, ), + ( + 2u8, + TrackInfo { + name: "none", + max_deciding: 3, + decision_deposit: 1, + prepare_period: 2, + decision_period: 2, + confirm_period: 1, + min_enactment_period: 0, + min_approval: Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(95), + ceil: Perbill::from_percent(100), + }, + min_support: Curve::LinearDecreasing { + length: Perbill::from_percent(100), + floor: Perbill::from_percent(90), + ceil: Perbill::from_percent(100), + }, + }, + ), ]; &DATA[..] } @@ -176,6 +187,7 @@ impl TracksInfo for TestTracksInfo { match system_origin { frame_system::RawOrigin::Root => Ok(0), frame_system::RawOrigin::None => Ok(1), + frame_system::RawOrigin::Signed(1) => Ok(2), _ => Err(()), } } else { diff --git a/substrate/frame/referenda/src/tests.rs b/substrate/frame/referenda/src/tests.rs index 52251fcbdbeed0ec5b8830e87a2a4c66bb265e39..3f859636f7cbb34d36d9fbafdfa05c189905d2c6 100644 --- a/substrate/frame/referenda/src/tests.rs +++ b/substrate/frame/referenda/src/tests.rs @@ -682,3 +682,27 @@ fn detects_incorrect_len() { ); }); } + +/// Ensures that `DispatchTime::After(0)` plus `min_enactment_period = 0` works. +#[test] +fn zero_enactment_delay_executes_proposal_at_next_block() { + ExtBuilder::default().build_and_execute(|| { + assert_eq!(Balances::free_balance(42), 0); + assert_ok!(Referenda::submit( + RuntimeOrigin::signed(1), + Box::new(RawOrigin::Signed(1).into()), + Preimage::bound( + pallet_balances::Call::transfer_keep_alive { dest: 42, value: 20 }.into() + ) + .unwrap(), + DispatchTime::After(0), + )); + assert_ok!(Referenda::place_decision_deposit(RuntimeOrigin::signed(1), 0)); + assert_eq!(ReferendumCount::::get(), 1); + set_tally(0, 100, 0); + + run_to(9); + + assert_eq!(Balances::free_balance(42), 20); + }); +} diff --git a/substrate/frame/remark/Cargo.toml b/substrate/frame/remark/Cargo.toml index d251aacfb5b2c204a29d3098b41cba4f0317b3ca..44cf5ebc3b492a0c414716402308d1b5f22214bd 100644 --- a/substrate/frame/remark/Cargo.toml +++ b/substrate/frame/remark/Cargo.toml @@ -16,19 +16,19 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { workspace = true } +scale-info = { features = ["derive"], workspace = true } serde = { optional = true, workspace = true, default-features = true } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-core = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -sp-core = { path = "../../primitives/core", default-features = false } +sp-core = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/root-offences/Cargo.toml b/substrate/frame/root-offences/Cargo.toml index e7317d737fac125e5ebbafa2be46b0426014bd6e..dde264f3949a16cb1667d5ba3c5312b2182a1870 100644 --- a/substrate/frame/root-offences/Cargo.toml +++ b/substrate/frame/root-offences/Cargo.toml @@ -16,27 +16,27 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } -pallet-session = { path = "../session", default-features = false, features = ["historical"] } -pallet-staking = { path = "../staking", default-features = false } +pallet-session = { features = ["historical"], workspace = true } +pallet-staking = { workspace = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-staking = { path = "../../primitives/staking", default-features = false } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-runtime = { workspace = true } +sp-staking = { workspace = true } [dev-dependencies] -pallet-balances = { path = "../balances" } -pallet-timestamp = { path = "../timestamp" } -pallet-staking-reward-curve = { path = "../staking/reward-curve" } +pallet-balances = { workspace = true, default-features = true } +pallet-timestamp = { workspace = true, default-features = true } +pallet-staking-reward-curve = { workspace = true, default-features = true } -sp-core = { path = "../../primitives/core" } -sp-io = { path = "../../primitives/io", default-features = false } -sp-std = { path = "../../primitives/std" } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true } +sp-std = { workspace = true, default-features = true } -frame-election-provider-support = { path = "../election-provider-support" } +frame-election-provider-support = { workspace = true, default-features = true } [features] runtime-benchmarks = [ diff --git a/substrate/frame/root-offences/src/mock.rs b/substrate/frame/root-offences/src/mock.rs index 7e7332c3f7e3b39ca9457c6da05c7eb66197d0c4..3c758b91d52fe851dd279a3e7e3bb3b9dd69ebe3 100644 --- a/substrate/frame/root-offences/src/mock.rs +++ b/substrate/frame/root-offences/src/mock.rs @@ -84,20 +84,9 @@ impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ConstU64<1>; type AccountStore = System; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } pallet_staking_reward_curve::build! { @@ -135,15 +124,11 @@ parameter_types! { pub static LedgerSlashPerEra: (BalanceOf, BTreeMap>) = (Zero::zero(), BTreeMap::new()); } +#[derive_impl(pallet_staking::config_preludes::TestDefaultConfig)] impl pallet_staking::Config for Test { type Currency = Balances; type CurrencyBalance = ::Balance; type UnixTime = Timestamp; - type CurrencyToVote = (); - type RewardRemainder = (); - type RuntimeEvent = RuntimeEvent; - type Slash = (); - type Reward = (); type SessionsPerEra = SessionsPerEra; type SlashDeferDuration = SlashDeferDuration; type AdminOrigin = frame_system::EnsureRoot; @@ -151,19 +136,10 @@ impl pallet_staking::Config for Test { type SessionInterface = Self; type EraPayout = pallet_staking::ConvertCurve; type NextNewSession = Session; - type MaxExposurePageSize = ConstU32<64>; type ElectionProvider = onchain::OnChainExecution; type GenesisElectionProvider = Self::ElectionProvider; type TargetList = pallet_staking::UseValidatorsMap; - type NominationsQuota = pallet_staking::FixedNominationsQuota<16>; - type MaxUnlockingChunks = ConstU32<32>; - type HistoryDepth = ConstU32<84>; - type MaxControllersInDeprecationBatch = ConstU32<100>; type VoterList = pallet_staking::UseNominatorsAndValidatorsMap; - type EventListeners = (); - type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; - type WeightInfo = (); - type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; } impl pallet_session::historical::Config for Test { diff --git a/substrate/frame/root-testing/Cargo.toml b/substrate/frame/root-testing/Cargo.toml index 74a3b8f479fa30df155de60d306251a7f8e7e694..38d91c8104b902eeaf742ab7fa20540ae0d1d598 100644 --- a/substrate/frame/root-testing/Cargo.toml +++ b/substrate/frame/root-testing/Cargo.toml @@ -16,14 +16,14 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-core = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [features] try-runtime = [ diff --git a/substrate/frame/safe-mode/Cargo.toml b/substrate/frame/safe-mode/Cargo.toml index 7ecbdb6eeda5b16d35be7a98885ba0a027fbb89a..749c4bcdc7000d7d772433e92c327284b686d410 100644 --- a/substrate/frame/safe-mode/Cargo.toml +++ b/substrate/frame/safe-mode/Cargo.toml @@ -15,26 +15,26 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -docify = "0.2.8" -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -sp-arithmetic = { path = "../../primitives/arithmetic", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -pallet-balances = { path = "../balances", default-features = false, optional = true } -pallet-utility = { path = "../utility", default-features = false, optional = true } -pallet-proxy = { path = "../proxy", default-features = false, optional = true } +codec = { features = ["derive"], workspace = true } +docify = { workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +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 } [dev-dependencies] -sp-core = { path = "../../primitives/core" } -sp-io = { path = "../../primitives/io" } -pallet-balances = { path = "../balances" } -pallet-utility = { path = "../utility" } -pallet-proxy = { path = "../proxy" } -frame-support = { path = "../support", features = ["experimental"] } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +pallet-utility = { workspace = true, default-features = true } +pallet-proxy = { workspace = true, default-features = true } +frame-support = { features = ["experimental"], workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/safe-mode/src/mock.rs b/substrate/frame/safe-mode/src/mock.rs index 0beb911267dc5265bdf14cd1f46afff27b422e55..ec1ad82495147dbfc3039fc32dd3cd1e280629ad 100644 --- a/substrate/frame/safe-mode/src/mock.rs +++ b/substrate/frame/safe-mode/src/mock.rs @@ -68,20 +68,10 @@ pub enum HoldReason { SafeMode, } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type Balance = u64; - type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; type ExistentialDeposit = ConstU64<2>; type AccountStore = System; - type WeightInfo = (); - type MaxLocks = (); - type MaxReserves = ConstU32<10>; - type ReserveIdentifier = [u8; 8]; - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeFreezeReason; - type FreezeIdentifier = (); - type MaxFreezes = ConstU32<0>; } impl pallet_utility::Config for Test { diff --git a/substrate/frame/salary/Cargo.toml b/substrate/frame/salary/Cargo.toml index 25911269a95ddd3b51e639f56c10a647d321ba77..c9b72da2e649fa9f04c32d95fde2b3102b239185 100644 --- a/substrate/frame/salary/Cargo.toml +++ b/substrate/frame/salary/Cargo.toml @@ -16,18 +16,18 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-arithmetic = { path = "../../primitives/arithmetic", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -pallet-ranked-collective = { path = "../ranked-collective", default-features = false, optional = true } +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +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] default = ["std"] diff --git a/substrate/frame/salary/src/tests/integration.rs b/substrate/frame/salary/src/tests/integration.rs index 124ab38c5651b1e3c57d0457952eda8cd5b92e98..69f218943aded41107a143d8eea7d1094333f86b 100644 --- a/substrate/frame/salary/src/tests/integration.rs +++ b/substrate/frame/salary/src/tests/integration.rs @@ -180,6 +180,7 @@ impl pallet_ranked_collective::Config for Test { type MinRankOfClass = MinRankOfClass; type MemberSwappedHandler = Salary; type VoteWeight = Geometric; + type MaxMemberCount = (); #[cfg(feature = "runtime-benchmarks")] type BenchmarkSetup = Salary; } diff --git a/substrate/frame/sassafras/Cargo.toml b/substrate/frame/sassafras/Cargo.toml index 2105ba13314762151c02b3fc880795798414d32c..ecd03c47db6898a41ec5c09ea078b79797cb16ed 100644 --- a/substrate/frame/sassafras/Cargo.toml +++ b/substrate/frame/sassafras/Cargo.toml @@ -17,21 +17,21 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } log = { workspace = true } -sp-consensus-sassafras = { path = "../../primitives/consensus/sassafras", default-features = false, features = ["serde"] } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +sp-consensus-sassafras = { features = ["serde"], workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -array-bytes = "6.2.2" -sp-core = { path = "../../primitives/core" } -sp-crypto-hashing = { path = "../../primitives/crypto/hashing" } +array-bytes = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-crypto-hashing = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/scheduler/Cargo.toml b/substrate/frame/scheduler/Cargo.toml index e851f876112e8829a7914b18f5695436040ebbb8..0a6b646fc8c3c41ac262758304e33a48a3a2b39d 100644 --- a/substrate/frame/scheduler/Cargo.toml +++ b/substrate/frame/scheduler/Cargo.toml @@ -13,22 +13,22 @@ readme = "README.md" workspace = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -sp-weights = { path = "../../primitives/weights", default-features = false } -docify = "0.2.8" +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +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 } [dev-dependencies] -pallet-preimage = { path = "../preimage" } -sp-core = { path = "../../primitives/core", default-features = false } -substrate-test-utils = { path = "../../test-utils" } +pallet-preimage = { workspace = true, default-features = true } +sp-core = { workspace = true } +substrate-test-utils = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/scored-pool/Cargo.toml b/substrate/frame/scored-pool/Cargo.toml index f25bd1f1769ba458c8ea8c88ac9d0e18ce8fde2e..69ecd527eb7c9d4491400e6815ce17511f43f41a 100644 --- a/substrate/frame/scored-pool/Cargo.toml +++ b/substrate/frame/scored-pool/Cargo.toml @@ -16,17 +16,17 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -pallet-balances = { path = "../balances" } -sp-core = { path = "../../primitives/core" } +pallet-balances = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/scored-pool/src/mock.rs b/substrate/frame/scored-pool/src/mock.rs index 9d2f5eb1099f819ad0db2ac1c6d1878a5d2df2da..7708c06e56bd8056b0b2ff89f5b383d3b4c180bf 100644 --- a/substrate/frame/scored-pool/src/mock.rs +++ b/substrate/frame/scored-pool/src/mock.rs @@ -52,20 +52,9 @@ impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type Balance = u64; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ConstU64<1>; type AccountStore = System; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } parameter_types! { diff --git a/substrate/frame/session/Cargo.toml b/substrate/frame/session/Cargo.toml index 42ea957ac1581fa8434d94a0737597d82f4b74e5..c7b499548bdb4cce9d5fb7a08a2e45f8fe635e61 100644 --- a/substrate/frame/session/Cargo.toml +++ b/substrate/frame/session/Cargo.toml @@ -16,21 +16,21 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -impl-trait-for-tuples = "0.2.2" +codec = { features = ["derive"], workspace = true } +impl-trait-for-tuples = { workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive", "serde"] } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -pallet-timestamp = { path = "../timestamp", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false, features = ["serde"] } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false, features = ["serde"] } -sp-session = { path = "../../primitives/session", default-features = false } -sp-staking = { path = "../../primitives/staking", default-features = false, features = ["serde"] } -sp-std = { path = "../../primitives/std", default-features = false } -sp-trie = { path = "../../primitives/trie", default-features = false, optional = true } -sp-state-machine = { path = "../../primitives/state-machine", default-features = false } +scale-info = { features = ["derive", "serde"], workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-timestamp = { workspace = true } +sp-core = { features = ["serde"], workspace = true } +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 } [features] default = ["historical", "std"] diff --git a/substrate/frame/session/benchmarking/Cargo.toml b/substrate/frame/session/benchmarking/Cargo.toml index a306f9015c02913da0f2ebf96a252a86f4333c51..ba7f7acfd9919f58e5fd3e3e2e50534d118ffde4 100644 --- a/substrate/frame/session/benchmarking/Cargo.toml +++ b/substrate/frame/session/benchmarking/Cargo.toml @@ -16,26 +16,26 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -rand = { version = "0.8.5", default-features = false, features = ["std_rng"] } -frame-benchmarking = { path = "../../benchmarking", default-features = false } -frame-support = { path = "../../support", default-features = false } -frame-system = { path = "../../system", default-features = false } -pallet-session = { path = "..", default-features = false } -pallet-staking = { path = "../../staking", default-features = false } -sp-runtime = { path = "../../../primitives/runtime", default-features = false } -sp-session = { path = "../../../primitives/session", default-features = false } -sp-std = { path = "../../../primitives/std", default-features = false } +codec = { workspace = true } +rand = { features = ["std_rng"], workspace = true } +frame-benchmarking = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-session = { workspace = true } +pallet-staking = { workspace = true } +sp-runtime = { workspace = true } +sp-session = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } -scale-info = "2.11.1" -frame-election-provider-support = { path = "../../election-provider-support" } -pallet-balances = { path = "../../balances" } -pallet-staking-reward-curve = { path = "../../staking/reward-curve" } -pallet-timestamp = { path = "../../timestamp" } -sp-core = { path = "../../../primitives/core" } -sp-io = { path = "../../../primitives/io" } +codec = { features = ["derive"], workspace = true, default-features = true } +scale-info = { workspace = true, default-features = true } +frame-election-provider-support = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +pallet-staking-reward-curve = { workspace = true, default-features = true } +pallet-timestamp = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/session/benchmarking/src/mock.rs b/substrate/frame/session/benchmarking/src/mock.rs index 5cba79ef5b9a2f556096f7a7117330b3a7d80c37..2aec58cceded2d186d9ead2ca2c4768e7cce1b90 100644 --- a/substrate/frame/session/benchmarking/src/mock.rs +++ b/substrate/frame/session/benchmarking/src/mock.rs @@ -54,20 +54,10 @@ impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); type ExistentialDeposit = ConstU64<10>; type AccountStore = System; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } impl pallet_timestamp::Config for Test { @@ -139,35 +129,19 @@ impl onchain::Config for OnChainSeqPhragmen { type Bounds = ElectionsBounds; } +#[derive_impl(pallet_staking::config_preludes::TestDefaultConfig)] impl pallet_staking::Config for Test { type Currency = Balances; type CurrencyBalance = ::Balance; type UnixTime = pallet_timestamp::Pallet; - type CurrencyToVote = (); - type RewardRemainder = (); - type RuntimeEvent = RuntimeEvent; - type Slash = (); - type Reward = (); - type SessionsPerEra = (); - type SlashDeferDuration = (); type AdminOrigin = frame_system::EnsureRoot; - type BondingDuration = (); type SessionInterface = Self; type EraPayout = pallet_staking::ConvertCurve; type NextNewSession = Session; - type MaxExposurePageSize = ConstU32<64>; type ElectionProvider = onchain::OnChainExecution; type GenesisElectionProvider = Self::ElectionProvider; - type MaxUnlockingChunks = ConstU32<32>; - type MaxControllersInDeprecationBatch = ConstU32<100>; - type HistoryDepth = ConstU32<84>; type VoterList = pallet_staking::UseNominatorsAndValidatorsMap; type TargetList = pallet_staking::UseValidatorsMap; - type NominationsQuota = pallet_staking::FixedNominationsQuota<16>; - type EventListeners = (); - type BenchmarkingConfig = pallet_staking::TestBenchmarkingConfig; - type WeightInfo = (); - type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; } impl crate::Config for Test {} diff --git a/substrate/frame/society/Cargo.toml b/substrate/frame/society/Cargo.toml index ed7fea523bffbd15a4da83e16f167ba239ecfca8..6582d47f194310250868fb8982685c3098197f33 100644 --- a/substrate/frame/society/Cargo.toml +++ b/substrate/frame/society/Cargo.toml @@ -17,24 +17,24 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] log = { workspace = true } -rand_chacha = { version = "0.3.1", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +rand_chacha = { workspace = true } +scale-info = { features = ["derive"], workspace = true } +codec = { features = ["derive"], workspace = true } -sp-std = { path = "../../primitives/std", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-arithmetic = { path = "../../primitives/arithmetic", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } +sp-std = { workspace = true } +sp-io = { workspace = true } +sp-arithmetic = { workspace = true } +sp-runtime = { workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } [dev-dependencies] -frame-support-test = { path = "../support/test" } -pallet-balances = { path = "../balances" } -sp-core = { path = "../../primitives/core" } -sp-crypto-hashing = { path = "../../primitives/crypto/hashing" } -sp-io = { path = "../../primitives/io" } +frame-support-test = { workspace = true } +pallet-balances = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-crypto-hashing = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/staking/Cargo.toml b/substrate/frame/staking/Cargo.toml index 22df746d667ab477dc576c6c085bbf1bf1675fb6..afae4652a4ef2ff954d1aa450ebbd453d095adbd 100644 --- a/substrate/frame/staking/Cargo.toml +++ b/substrate/frame/staking/Cargo.toml @@ -17,40 +17,40 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] serde = { features = ["alloc", "derive"], workspace = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", -] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive", "serde"] } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false, features = ["serde"] } -sp-staking = { path = "../../primitives/staking", default-features = false, features = ["serde"] } -sp-std = { path = "../../primitives/std", default-features = false } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -pallet-session = { path = "../session", default-features = false, features = [ +], workspace = true } +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 = [ "historical", -] } -pallet-authorship = { path = "../authorship", default-features = false } -sp-application-crypto = { path = "../../primitives/application-crypto", default-features = false, features = ["serde"] } -frame-election-provider-support = { path = "../election-provider-support", default-features = false } +], workspace = true } +pallet-authorship = { workspace = true } +sp-application-crypto = { features = ["serde"], workspace = true } +frame-election-provider-support = { workspace = true } log = { workspace = true } # Optional imports for benchmarking -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -rand_chacha = { version = "0.3.1", default-features = false, optional = true } +frame-benchmarking = { optional = true, workspace = true } +rand_chacha = { optional = true, workspace = true } [dev-dependencies] -pallet-balances = { path = "../balances" } -sp-tracing = { path = "../../primitives/tracing" } -sp-core = { path = "../../primitives/core" } -sp-npos-elections = { path = "../../primitives/npos-elections" } -pallet-timestamp = { path = "../timestamp" } -pallet-staking-reward-curve = { path = "reward-curve" } -pallet-bags-list = { path = "../bags-list" } -substrate-test-utils = { path = "../../test-utils" } -frame-benchmarking = { path = "../benchmarking" } -frame-election-provider-support = { path = "../election-provider-support" } -rand_chacha = { version = "0.3.1" } +pallet-balances = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-npos-elections = { workspace = true, default-features = true } +pallet-timestamp = { workspace = true, default-features = true } +pallet-staking-reward-curve = { workspace = true, default-features = true } +pallet-bags-list = { workspace = true, default-features = true } +substrate-test-utils = { workspace = true } +frame-benchmarking = { workspace = true, default-features = true } +frame-election-provider-support = { workspace = true, default-features = true } +rand_chacha = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/staking/reward-curve/Cargo.toml b/substrate/frame/staking/reward-curve/Cargo.toml index e2a2782db2da1527eff9d9948020fb72bd02e370..acb819c3169ec105954ea599331d29bb83e4c2cd 100644 --- a/substrate/frame/staking/reward-curve/Cargo.toml +++ b/substrate/frame/staking/reward-curve/Cargo.toml @@ -18,10 +18,10 @@ targets = ["x86_64-unknown-linux-gnu"] proc-macro = true [dependencies] -proc-macro-crate = "3.0.0" -proc-macro2 = "1.0.56" +proc-macro-crate = { workspace = true } +proc-macro2 = { workspace = true } quote = { workspace = true } syn = { features = ["full", "visit"], workspace = true } [dev-dependencies] -sp-runtime = { path = "../../../primitives/runtime" } +sp-runtime = { workspace = true, default-features = true } diff --git a/substrate/frame/staking/reward-fn/Cargo.toml b/substrate/frame/staking/reward-fn/Cargo.toml index 5169db5072e2fc80805605c3517d8c6e779e5620..5adbb8382da50c05cf38c2ebd9f952c1330224c8 100644 --- a/substrate/frame/staking/reward-fn/Cargo.toml +++ b/substrate/frame/staking/reward-fn/Cargo.toml @@ -18,7 +18,7 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] log = { workspace = true } -sp-arithmetic = { path = "../../../primitives/arithmetic", default-features = false } +sp-arithmetic = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/staking/runtime-api/Cargo.toml b/substrate/frame/staking/runtime-api/Cargo.toml index 19da2f24ff00e80321e20506b2fe13a0ddd71978..624279624bc8098f61d4f650cd8da151486bdb57 100644 --- a/substrate/frame/staking/runtime-api/Cargo.toml +++ b/substrate/frame/staking/runtime-api/Cargo.toml @@ -16,9 +16,9 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -sp-api = { default-features = false, path = "../../../primitives/api" } -sp-staking = { default-features = false, path = "../../../primitives/staking" } +codec = { features = ["derive"], workspace = true } +sp-api = { workspace = true } +sp-staking = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/staking/src/mock.rs b/substrate/frame/staking/src/mock.rs index 8c60dec65a81a123b5d1bd04b3ea8614ae1e9f0f..7e6a87955b08371dddbecc6e17477ed5808173ef 100644 --- a/substrate/frame/staking/src/mock.rs +++ b/substrate/frame/staking/src/mock.rs @@ -124,20 +124,12 @@ impl frame_system::Config for Test { type Block = Block; type AccountData = pallet_balances::AccountData; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { type MaxLocks = frame_support::traits::ConstU32<1024>; - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } sp_runtime::impl_opaque_keys! { @@ -269,19 +261,15 @@ impl OnStakingUpdate for EventListenerMock { // Disabling threshold for `UpToLimitDisablingStrategy` pub(crate) const DISABLING_LIMIT_FACTOR: usize = 3; +#[derive_impl(crate::config_preludes::TestDefaultConfig)] impl crate::pallet::pallet::Config for Test { type Currency = Balances; - type CurrencyBalance = ::Balance; type UnixTime = Timestamp; - type CurrencyToVote = (); type RewardRemainder = RewardRemainderMock; - type RuntimeEvent = RuntimeEvent; - type Slash = (); type Reward = MockReward; type SessionsPerEra = SessionsPerEra; type SlashDeferDuration = SlashDeferDuration; type AdminOrigin = EnsureOneOrRoot; - type BondingDuration = BondingDuration; type SessionInterface = Self; type EraPayout = ConvertCurve; type NextNewSession = Session; @@ -296,8 +284,6 @@ impl crate::pallet::pallet::Config for Test { type HistoryDepth = HistoryDepth; type MaxControllersInDeprecationBatch = MaxControllersInDeprecationBatch; type EventListeners = EventListenerMock; - type BenchmarkingConfig = TestBenchmarkingConfig; - type WeightInfo = (); type DisablingStrategy = pallet_staking::UpToLimitDisablingStrategy; } diff --git a/substrate/frame/staking/src/pallet/mod.rs b/substrate/frame/staking/src/pallet/mod.rs index 284a801a0f050eb79672feb2e1167e5d14f033a5..a76e47edf38039501fe0ac9d3434e13b3fdafe4c 100644 --- a/substrate/frame/staking/src/pallet/mod.rs +++ b/substrate/frame/staking/src/pallet/mod.rs @@ -86,9 +86,10 @@ pub mod pallet { Remove, } - #[pallet::config] + #[pallet::config(with_default)] pub trait Config: frame_system::Config { /// The staking balance. + #[pallet::no_default] type Currency: LockableCurrency< Self::AccountId, Moment = BlockNumberFor, @@ -109,6 +110,7 @@ pub mod pallet { /// /// It is guaranteed to start being called from the first `on_finalize`. Thus value at /// genesis is not used. + #[pallet::no_default] type UnixTime: UnixTime; /// Convert a balance into a number used for election calculation. This must fit into a @@ -117,9 +119,11 @@ pub mod pallet { /// in 128. /// Consequently, the backward convert is used convert the u128s from sp-elections back to a /// [`BalanceOf`]. + #[pallet::no_default_bounds] type CurrencyToVote: sp_staking::currency_to_vote::CurrencyToVote>; /// Something that provides the election functionality. + #[pallet::no_default] type ElectionProvider: ElectionProvider< AccountId = Self::AccountId, BlockNumber = BlockNumberFor, @@ -127,6 +131,7 @@ pub mod pallet { DataProvider = Pallet, >; /// Something that provides the election functionality at genesis. + #[pallet::no_default] type GenesisElectionProvider: ElectionProvider< AccountId = Self::AccountId, BlockNumber = BlockNumberFor, @@ -134,6 +139,7 @@ pub mod pallet { >; /// Something that defines the maximum number of nominations per nominator. + #[pallet::no_default_bounds] type NominationsQuota: NominationsQuota>; /// Number of eras to keep in history. @@ -161,17 +167,21 @@ pub mod pallet { /// Tokens have been minted and are unused for validator-reward. /// See [Era payout](./index.html#era-payout). + #[pallet::no_default_bounds] type RewardRemainder: OnUnbalanced>; /// The overarching event type. + #[pallet::no_default_bounds] type RuntimeEvent: From> + IsType<::RuntimeEvent>; /// Handler for the unbalanced reduction when slashing a staker. + #[pallet::no_default_bounds] type Slash: OnUnbalanced>; /// Handler for the unbalanced increment when rewarding a staker. /// NOTE: in most cases, the implementation of `OnUnbalanced` should modify the total /// issuance. + #[pallet::no_default_bounds] type Reward: OnUnbalanced>; /// Number of sessions per era. @@ -192,6 +202,7 @@ pub mod pallet { /// The origin which can manage less critical staking parameters that does not require root. /// /// Supported actions: (1) cancel deferred slash, (2) set minimum commission. + #[pallet::no_default] type AdminOrigin: EnsureOrigin; /// Interface for interacting with a session pallet. @@ -199,10 +210,12 @@ pub mod pallet { /// The payout for validators and the system for the current era. /// See [Era payout](./index.html#era-payout). + #[pallet::no_default] type EraPayout: EraPayout>; /// Something that can estimate the next session change, accurately or as a best effort /// guess. + #[pallet::no_default_bounds] type NextNewSession: EstimateNextNewSession>; /// The maximum size of each `T::ExposurePage`. @@ -230,6 +243,7 @@ pub mod pallet { /// staker. In case of `bags-list`, this always means using `rebag` and `putInFrontOf`. /// /// Invariant: what comes out of this list will always be a nominator. + #[pallet::no_default] type VoterList: SortedListProvider; /// WIP: This is a noop as of now, the actual business logic that's described below is going @@ -252,6 +266,7 @@ pub mod pallet { /// validators, they can chill at any point, and their approval stakes will still be /// recorded. This implies that what comes out of iterating this list MIGHT NOT BE AN ACTIVE /// VALIDATOR. + #[pallet::no_default] type TargetList: SortedListProvider>; /// The maximum number of `unlocking` chunks a [`StakingLedger`] can @@ -274,18 +289,66 @@ pub mod pallet { /// receives. /// /// WARNING: this only reports slashing and withdraw events for the time being. + #[pallet::no_default_bounds] type EventListeners: sp_staking::OnStakingUpdate>; - // `DisablingStragegy` controls how validators are disabled + /// `DisablingStragegy` controls how validators are disabled + #[pallet::no_default_bounds] type DisablingStrategy: DisablingStrategy; /// Some parameters of the benchmarking. + #[cfg(feature = "std")] + type BenchmarkingConfig: BenchmarkingConfig; + + #[cfg(not(feature = "std"))] + #[pallet::no_default] type BenchmarkingConfig: BenchmarkingConfig; /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; } + /// Default implementations of [`DefaultConfig`], which can be used to implement [`Config`]. + pub mod config_preludes { + use super::*; + use frame_support::{derive_impl, parameter_types, traits::ConstU32}; + pub struct TestDefaultConfig; + + #[derive_impl(frame_system::config_preludes::TestDefaultConfig, no_aggregated_types)] + impl frame_system::DefaultConfig for TestDefaultConfig {} + + parameter_types! { + pub const SessionsPerEra: SessionIndex = 3; + pub const BondingDuration: EraIndex = 3; + } + + #[frame_support::register_default_impl(TestDefaultConfig)] + impl DefaultConfig for TestDefaultConfig { + #[inject_runtime_type] + type RuntimeEvent = (); + type CurrencyBalance = u128; + type CurrencyToVote = (); + type NominationsQuota = crate::FixedNominationsQuota<16>; + type HistoryDepth = ConstU32<84>; + type RewardRemainder = (); + type Slash = (); + type Reward = (); + type SessionsPerEra = SessionsPerEra; + type BondingDuration = BondingDuration; + type SlashDeferDuration = (); + type SessionInterface = (); + type NextNewSession = (); + type MaxExposurePageSize = ConstU32<64>; + type MaxUnlockingChunks = ConstU32<32>; + type MaxControllersInDeprecationBatch = ConstU32<100>; + type EventListeners = (); + type DisablingStrategy = crate::UpToLimitDisablingStrategy; + #[cfg(feature = "std")] + type BenchmarkingConfig = crate::TestBenchmarkingConfig; + type WeightInfo = (); + } + } + /// The ideal number of active validators. #[pallet::storage] #[pallet::getter(fn validator_count)] diff --git a/substrate/frame/staking/src/tests.rs b/substrate/frame/staking/src/tests.rs index 2229eb28329ad07b5eb8742293a3b10eb6bdc905..825b03b8ecaac159e1332a2e73eb5441601f0bf2 100644 --- a/substrate/frame/staking/src/tests.rs +++ b/substrate/frame/staking/src/tests.rs @@ -780,7 +780,7 @@ fn nominators_also_get_slashed_pro_rata() { #[test] fn double_staking_should_fail() { // should test (in the same order): - // * an account already bonded as stash cannot be be stashed again. + // * an account already bonded as stash cannot be stashed again. // * an account already bonded as stash cannot nominate. // * an account already bonded as controller can nominate. ExtBuilder::default().try_state(false).build_and_execute(|| { diff --git a/substrate/frame/state-trie-migration/Cargo.toml b/substrate/frame/state-trie-migration/Cargo.toml index 0870989d81f15df54cec9c41a0fa408edb45af36..8bb4079715e2a99298239160f04d3bc967633c8c 100644 --- a/substrate/frame/state-trie-migration/Cargo.toml +++ b/substrate/frame/state-trie-migration/Cargo.toml @@ -15,27 +15,27 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } +codec = { workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } serde = { optional = true, workspace = true, default-features = true } -thousands = { version = "0.2.0", optional = true } -zstd = { version = "0.12.4", default-features = false, optional = true } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -remote-externalities = { package = "frame-remote-externalities", path = "../../utils/frame/remote-externalities", optional = true } -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -substrate-state-trie-migration-rpc = { path = "../../utils/frame/rpc/state-trie-migration-rpc", optional = true } +thousands = { optional = true, workspace = true } +zstd = { optional = true, workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +remote-externalities = { optional = true, workspace = true, default-features = true } +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] -parking_lot = "0.12.1" -tokio = { version = "1.22.0", features = ["macros"] } -pallet-balances = { path = "../balances" } -sp-tracing = { path = "../../primitives/tracing" } +parking_lot = { workspace = true, default-features = true } +tokio = { features = ["macros"], workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/statement/Cargo.toml b/substrate/frame/statement/Cargo.toml index 989f0c330fc10b19bde46d92d853fcbdef2b463a..233b7255fc5dbc0e617c53c427252431052cf891 100644 --- a/substrate/frame/statement/Cargo.toml +++ b/substrate/frame/statement/Cargo.toml @@ -15,20 +15,20 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-statement-store = { path = "../../primitives/statement-store", default-features = false } -sp-api = { path = "../../primitives/api", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } +frame-support = { workspace = true } +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 } [dev-dependencies] -pallet-balances = { path = "../balances" } +pallet-balances = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/statement/src/mock.rs b/substrate/frame/statement/src/mock.rs index 35d51e7a27bfc82e82d9b0b19220c31816c27e37..34afd332c083ddb4baefd367349a9e37f806838f 100644 --- a/substrate/frame/statement/src/mock.rs +++ b/substrate/frame/statement/src/mock.rs @@ -51,20 +51,10 @@ impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type Balance = u64; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); type ExistentialDeposit = ConstU64<5>; type AccountStore = System; - type WeightInfo = (); - type MaxLocks = (); - type MaxReserves = ConstU32<50>; - type ReserveIdentifier = [u8; 8]; - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeFreezeReason; } ord_parameter_types! { diff --git a/substrate/frame/sudo/Cargo.toml b/substrate/frame/sudo/Cargo.toml index fcbb00087e26c7b08a00227c142a2565b2c0c04b..5d5d09d692342746557c3a80190ff6257de37a53 100644 --- a/substrate/frame/sudo/Cargo.toml +++ b/substrate/frame/sudo/Cargo.toml @@ -16,19 +16,19 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +codec = { features = ["derive"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +scale-info = { features = ["derive"], workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } -docify = "0.2.8" +docify = { workspace = true } [dev-dependencies] -sp-core = { path = "../../primitives/core" } +sp-core = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/support/Cargo.toml b/substrate/frame/support/Cargo.toml index a6c4fd6ee309ec4fc07495b59df341b854dfb1a9..560697ab710b1af575c62c93c217f965e3f1d042 100644 --- a/substrate/frame/support/Cargo.toml +++ b/substrate/frame/support/Cargo.toml @@ -16,59 +16,59 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -array-bytes = { version = "6.2.2", default-features = false } +array-bytes = { workspace = true } serde = { features = ["alloc", "derive"], workspace = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", "max-encoded-len", -] } -scale-info = { version = "2.11.1", default-features = false, features = [ +], workspace = true } +scale-info = { features = [ "derive", -] } -frame-metadata = { version = "16.0.0", default-features = false, features = [ +], workspace = true } +frame-metadata = { features = [ "current", -] } -sp-api = { path = "../../primitives/api", default-features = false, features = [ +], workspace = true } +sp-api = { features = [ "frame-metadata", -] } -sp-std = { path = "../../primitives/std", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false, features = [ +], workspace = true } +sp-std = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { features = [ "serde", -] } -sp-tracing = { path = "../../primitives/tracing", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-arithmetic = { path = "../../primitives/arithmetic", default-features = false } -sp-inherents = { path = "../../primitives/inherents", default-features = false } -sp-staking = { path = "../../primitives/staking", default-features = false } -sp-weights = { path = "../../primitives/weights", default-features = false } -sp-debug-derive = { path = "../../primitives/debug-derive", default-features = false } -sp-metadata-ir = { path = "../../primitives/metadata-ir", default-features = false } -tt-call = "1.0.8" -macro_magic = "0.5.0" -frame-support-procedural = { path = "procedural", default-features = false } -paste = "1.0" -sp-state-machine = { path = "../../primitives/state-machine", default-features = false, optional = true } -bitflags = "1.3" -impl-trait-for-tuples = "0.2.2" -smallvec = "1.11.0" +], workspace = true } +sp-tracing = { workspace = true } +sp-core = { workspace = true } +sp-arithmetic = { workspace = true } +sp-inherents = { workspace = true } +sp-staking = { workspace = true } +sp-weights = { workspace = true } +sp-debug-derive = { workspace = true } +sp-metadata-ir = { workspace = true } +tt-call = { workspace = true } +macro_magic = { workspace = true } +frame-support-procedural = { workspace = true } +paste = { workspace = true, default-features = true } +sp-state-machine = { optional = true, workspace = true } +bitflags = { workspace = true } +impl-trait-for-tuples = { workspace = true } +smallvec = { workspace = true, default-features = true } log = { workspace = true } -sp-crypto-hashing-proc-macro = { path = "../../primitives/crypto/hashing/proc-macro" } -k256 = { version = "0.13.1", default-features = false, features = ["ecdsa"] } -environmental = { version = "1.1.4", default-features = false } -sp-genesis-builder = { path = "../../primitives/genesis-builder", default-features = false } +sp-crypto-hashing-proc-macro = { workspace = true, default-features = true } +k256 = { features = ["ecdsa"], workspace = true } +environmental = { workspace = true } +sp-genesis-builder = { workspace = true } serde_json = { features = ["alloc"], workspace = true } -docify = "0.2.8" -static_assertions = "1.1.0" +docify = { workspace = true } +static_assertions = { workspace = true, default-features = true } -aquamarine = { version = "0.5.0" } +aquamarine = { workspace = true } [dev-dependencies] -assert_matches = "1.3.0" -pretty_assertions = "1.2.1" -sp-timestamp = { path = "../../primitives/timestamp", default-features = false } -frame-system = { path = "../system" } -sp-crypto-hashing = { path = "../../primitives/crypto/hashing" } +assert_matches = { workspace = true } +pretty_assertions = { workspace = true } +sp-timestamp = { workspace = true } +frame-system = { workspace = true, default-features = true } +sp-crypto-hashing = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/support/procedural/Cargo.toml b/substrate/frame/support/procedural/Cargo.toml index b04af63de81174d02592c6d7caa51ad902c10ca8..fbb4da0177a4d9622375ef634b41cb688221eadb 100644 --- a/substrate/frame/support/procedural/Cargo.toml +++ b/substrate/frame/support/procedural/Cargo.toml @@ -18,21 +18,21 @@ targets = ["x86_64-unknown-linux-gnu"] proc-macro = true [dependencies] -derive-syn-parse = "0.2.0" -Inflector = "0.11.4" -cfg-expr = "0.15.5" -itertools = "0.11" -proc-macro2 = "1.0.56" +derive-syn-parse = { workspace = true } +Inflector = { workspace = true } +cfg-expr = { workspace = true } +itertools = { workspace = true } +proc-macro2 = { workspace = true } quote = { workspace = true } -syn = { features = ["full", "visit-mut"], workspace = true } -frame-support-procedural-tools = { path = "tools" } -macro_magic = { version = "0.5.0", features = ["proc_support"] } -proc-macro-warning = { version = "1.0.0", default-features = false } -expander = "2.0.0" -sp-crypto-hashing = { path = "../../../primitives/crypto/hashing", default-features = false } +syn = { features = ["full", "parsing", "visit-mut"], workspace = true } +frame-support-procedural-tools = { workspace = true, default-features = true } +macro_magic = { features = ["proc_support"], workspace = true } +proc-macro-warning = { workspace = true } +expander = { workspace = true } +sp-crypto-hashing = { workspace = true } [dev-dependencies] -regex = "1" +regex = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/support/procedural/src/lib.rs b/substrate/frame/support/procedural/src/lib.rs index e812ac071b2c9a2cf2e8ef199c2e1d656b7f0494..51e5657a2e8be433729a781b339f42b7f80e9bd8 100644 --- a/substrate/frame/support/procedural/src/lib.rs +++ b/substrate/frame/support/procedural/src/lib.rs @@ -81,6 +81,9 @@ fn counter_prefix(prefix: &str) -> String { /// Construct a runtime, with the given name and the given pallets. /// +/// NOTE: A new version of this macro is available at `frame_support::runtime`. This macro will +/// soon be deprecated. Please use the new macro instead. +/// /// The parameters here are specific types for `Block`, `NodeBlock`, and `UncheckedExtrinsic` /// and the pallets that are used by the runtime. /// `Block` is the block type that is used in the runtime and `NodeBlock` is the block type @@ -1188,67 +1191,11 @@ pub fn import_section(attr: TokenStream, tokens: TokenStream) -> TokenStream { .into() } -/// Construct a runtime, with the given name and the given pallets. -/// -/// # Example: /// -/// ```ignore -/// #[frame_support::runtime] -/// mod runtime { -/// // The main runtime -/// #[runtime::runtime] -/// // Runtime Types to be generated -/// #[runtime::derive( -/// RuntimeCall, -/// RuntimeEvent, -/// RuntimeError, -/// RuntimeOrigin, -/// RuntimeFreezeReason, -/// RuntimeHoldReason, -/// RuntimeSlashReason, -/// RuntimeLockId, -/// RuntimeTask, -/// )] -/// pub struct Runtime; -/// -/// #[runtime::pallet_index(0)] -/// pub type System = frame_system; -/// -/// #[runtime::pallet_index(1)] -/// pub type Test = path::to::test; -/// -/// // Pallet with instance. -/// #[runtime::pallet_index(2)] -/// pub type Test2_Instance1 = test2; -/// -/// // Pallet with calls disabled. -/// #[runtime::pallet_index(3)] -/// #[runtime::disable_call] -/// pub type Test3 = test3; -/// -/// // Pallet with unsigned extrinsics disabled. -/// #[runtime::pallet_index(4)] -/// #[runtime::disable_unsigned] -/// pub type Test4 = test4; -/// } -/// ``` -/// -/// # Legacy Ordering -/// -/// An optional attribute can be defined as #[frame_support::runtime(legacy_ordering)] to -/// ensure that the order of hooks is same as the order of pallets (and not based on the -/// pallet_index). This is to support legacy runtimes and should be avoided for new ones. -/// -/// # Note -/// -/// The population of the genesis storage depends on the order of pallets. So, if one of your -/// pallets depends on another pallet, the pallet that is depended upon needs to come before -/// the pallet depending on it. -/// -/// # Type definitions +/// --- /// -/// * The macro generates a type alias for each pallet to their `Pallet`. E.g. `type System = -/// frame_system::Pallet` +/// **Rust-Analyzer users**: See the documentation of the Rust item in +/// `frame_support::runtime`. #[proc_macro_attribute] pub fn runtime(attr: TokenStream, item: TokenStream) -> TokenStream { runtime::runtime(attr, item) diff --git a/substrate/frame/support/procedural/src/pallet/expand/constants.rs b/substrate/frame/support/procedural/src/pallet/expand/constants.rs index 57fa8b7f3cd9af0e24feffaac17367b7cc817054..d7fbb5a718973c9d2a9ed9f32ab384536265f3d6 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/constants.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/constants.rs @@ -30,8 +30,7 @@ struct ConstDef { pub metadata_name: Option, } -/// -/// * Impl fn module_constant_metadata for pallet. +/// Implement the `pallet_constants_metadata` function for the pallet. pub fn expand_constants(def: &mut Def) -> proc_macro2::TokenStream { let frame_support = &def.frame_support; let type_impl_gen = &def.type_impl_generics(proc_macro2::Span::call_site()); diff --git a/substrate/frame/support/procedural/src/pallet/parse/config.rs b/substrate/frame/support/procedural/src/pallet/parse/config.rs index 406072df4b9d60b874df83578c12df5df1216329..eaeaab247588052a36d7aac469935b62151fa013 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/config.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/config.rs @@ -94,30 +94,26 @@ impl TryFrom<&syn::TraitItemType> for ConstMetadataDef { let bound = trait_ty .bounds .iter() - .find_map(|b| { - if let syn::TypeParamBound::Trait(tb) = b { - tb.path - .segments - .last() - .and_then(|s| if s.ident == "Get" { Some(s) } else { None }) - } else { - None - } + .find_map(|param_bound| { + let syn::TypeParamBound::Trait(trait_bound) = param_bound else { return None }; + + trait_bound.path.segments.last().and_then(|s| (s.ident == "Get").then(|| s)) }) .ok_or_else(|| err(trait_ty.span(), "`Get` trait bound not found"))?; - let type_arg = if let syn::PathArguments::AngleBracketed(ref ab) = bound.arguments { - if ab.args.len() == 1 { - if let syn::GenericArgument::Type(ref ty) = ab.args[0] { - Ok(ty) - } else { - Err(err(ab.args[0].span(), "Expected a type argument")) - } - } else { - Err(err(bound.span(), "Expected a single type argument")) - } - } else { - Err(err(bound.span(), "Expected trait generic args")) - }?; + + let syn::PathArguments::AngleBracketed(ref ab) = bound.arguments else { + return Err(err(bound.span(), "Expected trait generic args")) + }; + + // Only one type argument is expected. + if ab.args.len() != 1 { + return Err(err(bound.span(), "Expected a single type argument")) + } + + let syn::GenericArgument::Type(ref type_arg) = ab.args[0] else { + return Err(err(ab.args[0].span(), "Expected a type argument")) + }; + let type_ = syn::parse2::(replace_self_by_t(type_arg.to_token_stream())) .expect("Internal error: replacing `Self` by `T` should result in valid type"); @@ -223,55 +219,55 @@ fn check_event_type( trait_item: &syn::TraitItem, trait_has_instance: bool, ) -> syn::Result { - if let syn::TraitItem::Type(type_) = trait_item { - if type_.ident == "RuntimeEvent" { - // Check event has no generics - if !type_.generics.params.is_empty() || type_.generics.where_clause.is_some() { - let msg = "Invalid `type RuntimeEvent`, associated type `RuntimeEvent` is reserved and must have\ - no generics nor where_clause"; - return Err(syn::Error::new(trait_item.span(), msg)) - } + let syn::TraitItem::Type(type_) = trait_item else { return Ok(false) }; - // Check bound contains IsType and From - let has_is_type_bound = type_.bounds.iter().any(|s| { - syn::parse2::(s.to_token_stream()) - .map_or(false, |b| has_expected_system_config(b.0, frame_system)) - }); - - if !has_is_type_bound { - let msg = "Invalid `type RuntimeEvent`, associated type `RuntimeEvent` is reserved and must \ - bound: `IsType<::RuntimeEvent>`".to_string(); - return Err(syn::Error::new(type_.span(), msg)) - } + if type_.ident != "RuntimeEvent" { + return Ok(false) + } - let from_event_bound = type_ - .bounds - .iter() - .find_map(|s| syn::parse2::(s.to_token_stream()).ok()); + // Check event has no generics + if !type_.generics.params.is_empty() || type_.generics.where_clause.is_some() { + let msg = + "Invalid `type RuntimeEvent`, associated type `RuntimeEvent` is reserved and must have\ + no generics nor where_clause"; + return Err(syn::Error::new(trait_item.span(), msg)) + } - let from_event_bound = if let Some(b) = from_event_bound { - b - } else { - let msg = "Invalid `type RuntimeEvent`, associated type `RuntimeEvent` is reserved and must \ - bound: `From` or `From>` or `From>`"; - return Err(syn::Error::new(type_.span(), msg)) - }; + // Check bound contains IsType and From + let has_is_type_bound = type_.bounds.iter().any(|s| { + syn::parse2::(s.to_token_stream()) + .map_or(false, |b| has_expected_system_config(b.0, frame_system)) + }); + + if !has_is_type_bound { + let msg = + "Invalid `type RuntimeEvent`, associated type `RuntimeEvent` is reserved and must \ + bound: `IsType<::RuntimeEvent>`" + .to_string(); + return Err(syn::Error::new(type_.span(), msg)) + } - if from_event_bound.is_generic && (from_event_bound.has_instance != trait_has_instance) - { - let msg = "Invalid `type RuntimeEvent`, associated type `RuntimeEvent` bounds inconsistent \ + let from_event_bound = type_ + .bounds + .iter() + .find_map(|s| syn::parse2::(s.to_token_stream()).ok()); + + let Some(from_event_bound) = from_event_bound else { + let msg = + "Invalid `type RuntimeEvent`, associated type `RuntimeEvent` is reserved and must \ + bound: `From` or `From>` or `From>`"; + return Err(syn::Error::new(type_.span(), msg)) + }; + + if from_event_bound.is_generic && (from_event_bound.has_instance != trait_has_instance) { + let msg = + "Invalid `type RuntimeEvent`, associated type `RuntimeEvent` bounds inconsistent \ `From`. Config and generic Event must be both with instance or \ without instance"; - return Err(syn::Error::new(type_.span(), msg)) - } - - Ok(true) - } else { - Ok(false) - } - } else { - Ok(false) + return Err(syn::Error::new(type_.span(), msg)) } + + Ok(true) } /// Check that the path to `frame_system::Config` is valid, this is that the path is just @@ -334,9 +330,7 @@ impl ConfigDef { item: &mut syn::Item, enable_default: bool, ) -> syn::Result { - let item = if let syn::Item::Trait(item) = item { - item - } else { + let syn::Item::Trait(item) = item else { let msg = "Invalid pallet::config, expected trait definition"; return Err(syn::Error::new(item.span(), msg)) }; diff --git a/substrate/frame/support/procedural/src/pallet/parse/helper.rs b/substrate/frame/support/procedural/src/pallet/parse/helper.rs index 3187c9139c8f46c7664e96edb6870f68979146ae..d4f58a4c56df8ba61e26535cc19287f336e78846 100644 --- a/substrate/frame/support/procedural/src/pallet/parse/helper.rs +++ b/substrate/frame/support/procedural/src/pallet/parse/helper.rs @@ -55,16 +55,16 @@ pub(crate) fn take_first_item_pallet_attr( where Attr: syn::parse::Parse, { - let attrs = if let Some(attrs) = item.mut_item_attrs() { attrs } else { return Ok(None) }; + let Some(attrs) = item.mut_item_attrs() else { return Ok(None) }; - if let Some(index) = attrs.iter().position(|attr| { + let Some(index) = attrs.iter().position(|attr| { attr.path().segments.first().map_or(false, |segment| segment.ident == "pallet") - }) { - let pallet_attr = attrs.remove(index); - Ok(Some(syn::parse2(pallet_attr.into_token_stream())?)) - } else { - Ok(None) - } + }) else { + return Ok(None) + }; + + let pallet_attr = attrs.remove(index); + Ok(Some(syn::parse2(pallet_attr.into_token_stream())?)) } /// Take all the pallet attributes (e.g. attribute like `#[pallet..]`) and decode them to `Attr` diff --git a/substrate/frame/support/procedural/src/runtime/expand/mod.rs b/substrate/frame/support/procedural/src/runtime/expand/mod.rs index 43f11896808c71aed001a4660f3a73de2825dc8b..3cdfb06cb6eaa65c71777688421d5ef28a77fb11 100644 --- a/substrate/frame/support/procedural/src/runtime/expand/mod.rs +++ b/substrate/frame/support/procedural/src/runtime/expand/mod.rs @@ -99,14 +99,20 @@ fn construct_runtime_implicit_to_explicit( for pallet in definition.pallet_decls.iter() { let pallet_path = &pallet.path; let pallet_name = &pallet.name; - let pallet_instance = pallet.instance.as_ref().map(|instance| quote::quote!(<#instance>)); + let runtime_param = &pallet.runtime_param; + let pallet_segment_and_instance = match (&pallet.pallet_segment, &pallet.instance) { + (Some(segment), Some(instance)) => quote::quote!(::#segment<#runtime_param, #instance>), + (Some(segment), None) => quote::quote!(::#segment<#runtime_param>), + (None, Some(instance)) => quote::quote!(<#instance>), + (None, None) => quote::quote!(), + }; expansion = quote::quote!( #frame_support::__private::tt_call! { macro = [{ #pallet_path::tt_default_parts_v2 }] your_tt_return = [{ #frame_support::__private::tt_return }] ~~> #frame_support::match_and_insert! { target = [{ #expansion }] - pattern = [{ #pallet_name = #pallet_path #pallet_instance }] + pattern = [{ #pallet_name = #pallet_path #pallet_segment_and_instance }] } } ); diff --git a/substrate/frame/support/procedural/src/runtime/parse/mod.rs b/substrate/frame/support/procedural/src/runtime/parse/mod.rs index dd83cd0da90a2185ebc5015daadba0a9d00ac438..49647993aac725e5c80bb68ab26a5cc150f4ad5c 100644 --- a/substrate/frame/support/procedural/src/runtime/parse/mod.rs +++ b/substrate/frame/support/procedural/src/runtime/parse/mod.rs @@ -189,7 +189,7 @@ impl Def { match *pallet_item.ty.clone() { syn::Type::Path(ref path) => { let pallet_decl = - PalletDeclaration::try_from(item.span(), &pallet_item, path)?; + PalletDeclaration::try_from(item.span(), &pallet_item, &path.path)?; if let Some(used_pallet) = names.insert(pallet_decl.name.clone(), pallet_decl.name.span()) @@ -267,3 +267,24 @@ impl Def { Ok(def) } } + +#[test] +fn runtime_parsing_works() { + let def = Def::try_from(syn::parse_quote! { + #[runtime::runtime] + mod runtime { + #[runtime::derive(RuntimeCall, RuntimeEvent)] + #[runtime::runtime] + pub struct Runtime; + + #[runtime::pallet_index(0)] + pub type System = frame_system::Pallet; + + #[runtime::pallet_index(1)] + pub type Pallet1 = pallet1; + } + }) + .expect("Failed to parse runtime definition"); + + assert_eq!(def.runtime_struct.ident, "Runtime"); +} diff --git a/substrate/frame/support/procedural/src/runtime/parse/pallet.rs b/substrate/frame/support/procedural/src/runtime/parse/pallet.rs index 09f5290541d3a6ac038cd863a96330f10b605c44..ebfd0c9ccceed5156d48c8704cae2eb14a3423b5 100644 --- a/substrate/frame/support/procedural/src/runtime/parse/pallet.rs +++ b/substrate/frame/support/procedural/src/runtime/parse/pallet.rs @@ -15,10 +15,13 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::construct_runtime::parse::{Pallet, PalletPart, PalletPartKeyword, PalletPath}; +use crate::{ + construct_runtime::parse::{Pallet, PalletPart, PalletPartKeyword, PalletPath}, + runtime::parse::PalletDeclaration, +}; use frame_support_procedural_tools::get_doc_literals; use quote::ToTokens; -use syn::{punctuated::Punctuated, spanned::Spanned, token, Error, Ident, PathArguments}; +use syn::{punctuated::Punctuated, token, Error}; impl Pallet { pub fn try_from( @@ -55,20 +58,10 @@ impl Pallet { "Invalid pallet declaration, expected a path or a trait object", ))?; - let mut instance = None; - if let Some(segment) = path.inner.segments.iter_mut().find(|seg| !seg.arguments.is_empty()) - { - if let PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments { - args, .. - }) = segment.arguments.clone() - { - if let Some(syn::GenericArgument::Type(syn::Type::Path(arg_path))) = args.first() { - instance = - Some(Ident::new(&arg_path.to_token_stream().to_string(), arg_path.span())); - segment.arguments = PathArguments::None; - } - } - } + let PalletDeclaration { path: inner, instance, .. } = + PalletDeclaration::try_from(attr_span, item, &path.inner)?; + + path = PalletPath { inner }; pallet_parts = pallet_parts .into_iter() @@ -101,3 +94,95 @@ impl Pallet { }) } } + +#[test] +fn pallet_parsing_works() { + use syn::{parse_quote, ItemType}; + + let item: ItemType = parse_quote! { + pub type System = frame_system + Call; + }; + let ItemType { ty, .. } = item.clone(); + let syn::Type::TraitObject(syn::TypeTraitObject { bounds, .. }) = *ty else { + panic!("Expected a trait object"); + }; + + let index = 0; + let pallet = + Pallet::try_from(proc_macro2::Span::call_site(), &item, index, false, false, &bounds) + .unwrap(); + + assert_eq!(pallet.name.to_string(), "System"); + assert_eq!(pallet.index, index); + assert_eq!(pallet.path.to_token_stream().to_string(), "frame_system"); + assert_eq!(pallet.instance, None); +} + +#[test] +fn pallet_parsing_works_with_instance() { + use syn::{parse_quote, ItemType}; + + let item: ItemType = parse_quote! { + pub type System = frame_system + Call; + }; + let ItemType { ty, .. } = item.clone(); + let syn::Type::TraitObject(syn::TypeTraitObject { bounds, .. }) = *ty else { + panic!("Expected a trait object"); + }; + + let index = 0; + let pallet = + Pallet::try_from(proc_macro2::Span::call_site(), &item, index, false, false, &bounds) + .unwrap(); + + assert_eq!(pallet.name.to_string(), "System"); + assert_eq!(pallet.index, index); + assert_eq!(pallet.path.to_token_stream().to_string(), "frame_system"); + assert_eq!(pallet.instance, Some(parse_quote! { Instance1 })); +} + +#[test] +fn pallet_parsing_works_with_pallet() { + use syn::{parse_quote, ItemType}; + + let item: ItemType = parse_quote! { + pub type System = frame_system::Pallet + Call; + }; + let ItemType { ty, .. } = item.clone(); + let syn::Type::TraitObject(syn::TypeTraitObject { bounds, .. }) = *ty else { + panic!("Expected a trait object"); + }; + + let index = 0; + let pallet = + Pallet::try_from(proc_macro2::Span::call_site(), &item, index, false, false, &bounds) + .unwrap(); + + assert_eq!(pallet.name.to_string(), "System"); + assert_eq!(pallet.index, index); + assert_eq!(pallet.path.to_token_stream().to_string(), "frame_system"); + assert_eq!(pallet.instance, None); +} + +#[test] +fn pallet_parsing_works_with_instance_and_pallet() { + use syn::{parse_quote, ItemType}; + + let item: ItemType = parse_quote! { + pub type System = frame_system::Pallet + Call; + }; + let ItemType { ty, .. } = item.clone(); + let syn::Type::TraitObject(syn::TypeTraitObject { bounds, .. }) = *ty else { + panic!("Expected a trait object"); + }; + + let index = 0; + let pallet = + Pallet::try_from(proc_macro2::Span::call_site(), &item, index, false, false, &bounds) + .unwrap(); + + assert_eq!(pallet.name.to_string(), "System"); + assert_eq!(pallet.index, index); + assert_eq!(pallet.path.to_token_stream().to_string(), "frame_system"); + assert_eq!(pallet.instance, Some(parse_quote! { Instance1 })); +} diff --git a/substrate/frame/support/procedural/src/runtime/parse/pallet_decl.rs b/substrate/frame/support/procedural/src/runtime/parse/pallet_decl.rs index e167d37d5f14099c1f8f656e9aa5e6e5e44780b5..fbac75336f2553c399d8fc9b0c2a9197abce4fb7 100644 --- a/substrate/frame/support/procedural/src/runtime/parse/pallet_decl.rs +++ b/substrate/frame/support/procedural/src/runtime/parse/pallet_decl.rs @@ -15,8 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use quote::ToTokens; -use syn::{spanned::Spanned, Attribute, Ident, PathArguments}; +use syn::{Attribute, Ident, PathArguments}; /// The declaration of a pallet. #[derive(Debug, Clone)] @@ -27,6 +26,11 @@ pub struct PalletDeclaration { pub attrs: Vec, /// The path of the pallet, e.g. `frame_system` in `pub type System = frame_system`. pub path: syn::Path, + /// The segment of the pallet, e.g. `Pallet` in `pub type System = frame_system::Pallet`. + pub pallet_segment: Option, + /// The runtime parameter of the pallet, e.g. `Runtime` in + /// `pub type System = frame_system::Pallet`. + pub runtime_param: Option, /// The instance of the pallet, e.g. `Instance1` in `pub type Council = /// pallet_collective`. pub instance: Option, @@ -36,26 +40,135 @@ impl PalletDeclaration { pub fn try_from( _attr_span: proc_macro2::Span, item: &syn::ItemType, - path: &syn::TypePath, + path: &syn::Path, ) -> syn::Result { let name = item.ident.clone(); - let mut path = path.path.clone(); + let mut path = path.clone(); + let mut pallet_segment = None; + let mut runtime_param = None; let mut instance = None; if let Some(segment) = path.segments.iter_mut().find(|seg| !seg.arguments.is_empty()) { if let PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments { args, .. }) = segment.arguments.clone() { - if let Some(syn::GenericArgument::Type(syn::Type::Path(arg_path))) = args.first() { - instance = - Some(Ident::new(&arg_path.to_token_stream().to_string(), arg_path.span())); + if segment.ident == "Pallet" { + let mut segment = segment.clone(); segment.arguments = PathArguments::None; + pallet_segment = Some(segment.clone()); + } + let mut args_iter = args.iter(); + if let Some(syn::GenericArgument::Type(syn::Type::Path(arg_path))) = + args_iter.next() + { + let ident = arg_path.path.require_ident()?.clone(); + if segment.ident == "Pallet" { + runtime_param = Some(ident); + if let Some(syn::GenericArgument::Type(syn::Type::Path(arg_path))) = + args_iter.next() + { + instance = Some(arg_path.path.require_ident()?.clone()); + } + } else { + instance = Some(ident); + segment.arguments = PathArguments::None; + } } } } - Ok(Self { name, path, instance, attrs: item.attrs.clone() }) + if pallet_segment.is_some() { + path = syn::Path { + leading_colon: None, + segments: path + .segments + .iter() + .filter(|seg| seg.arguments.is_empty()) + .cloned() + .collect(), + }; + } + + Ok(Self { name, path, pallet_segment, runtime_param, instance, attrs: item.attrs.clone() }) } } + +#[test] +fn declaration_works() { + use syn::parse_quote; + + let decl: PalletDeclaration = PalletDeclaration::try_from( + proc_macro2::Span::call_site(), + &parse_quote! { pub type System = frame_system; }, + &parse_quote! { frame_system }, + ) + .expect("Failed to parse pallet declaration"); + + assert_eq!(decl.name, "System"); + assert_eq!(decl.path, parse_quote! { frame_system }); + assert_eq!(decl.pallet_segment, None); + assert_eq!(decl.runtime_param, None); + assert_eq!(decl.instance, None); +} + +#[test] +fn declaration_works_with_instance() { + use syn::parse_quote; + + let decl: PalletDeclaration = PalletDeclaration::try_from( + proc_macro2::Span::call_site(), + &parse_quote! { pub type System = frame_system; }, + &parse_quote! { frame_system }, + ) + .expect("Failed to parse pallet declaration"); + + assert_eq!(decl.name, "System"); + assert_eq!(decl.path, parse_quote! { frame_system }); + assert_eq!(decl.pallet_segment, None); + assert_eq!(decl.runtime_param, None); + assert_eq!(decl.instance, Some(parse_quote! { Instance1 })); +} + +#[test] +fn declaration_works_with_pallet() { + use syn::parse_quote; + + let decl: PalletDeclaration = PalletDeclaration::try_from( + proc_macro2::Span::call_site(), + &parse_quote! { pub type System = frame_system::Pallet; }, + &parse_quote! { frame_system::Pallet }, + ) + .expect("Failed to parse pallet declaration"); + + assert_eq!(decl.name, "System"); + assert_eq!(decl.path, parse_quote! { frame_system }); + + let segment: syn::PathSegment = + syn::PathSegment { ident: parse_quote! { Pallet }, arguments: PathArguments::None }; + assert_eq!(decl.pallet_segment, Some(segment)); + assert_eq!(decl.runtime_param, Some(parse_quote! { Runtime })); + assert_eq!(decl.instance, None); +} + +#[test] +fn declaration_works_with_pallet_and_instance() { + use syn::parse_quote; + + let decl: PalletDeclaration = PalletDeclaration::try_from( + proc_macro2::Span::call_site(), + &parse_quote! { pub type System = frame_system::Pallet; }, + &parse_quote! { frame_system::Pallet }, + ) + .expect("Failed to parse pallet declaration"); + + assert_eq!(decl.name, "System"); + assert_eq!(decl.path, parse_quote! { frame_system }); + + let segment: syn::PathSegment = + syn::PathSegment { ident: parse_quote! { Pallet }, arguments: PathArguments::None }; + assert_eq!(decl.pallet_segment, Some(segment)); + assert_eq!(decl.runtime_param, Some(parse_quote! { Runtime })); + assert_eq!(decl.instance, Some(parse_quote! { Instance1 })); +} diff --git a/substrate/frame/support/procedural/tools/Cargo.toml b/substrate/frame/support/procedural/tools/Cargo.toml index a75307aca79b6ff241611b49b60c931ee1f83373..f672740e57e85f8ed79407b31c064d5d1b089cce 100644 --- a/substrate/frame/support/procedural/tools/Cargo.toml +++ b/substrate/frame/support/procedural/tools/Cargo.toml @@ -15,8 +15,8 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -proc-macro-crate = "3.0.0" -proc-macro2 = "1.0.56" +proc-macro-crate = { workspace = true } +proc-macro2 = { workspace = true } quote = { workspace = true } syn = { features = ["extra-traits", "full", "visit"], workspace = true } -frame-support-procedural-tools-derive = { path = "derive" } +frame-support-procedural-tools-derive = { workspace = true, default-features = true } diff --git a/substrate/frame/support/procedural/tools/derive/Cargo.toml b/substrate/frame/support/procedural/tools/derive/Cargo.toml index b39d99a822fb7aed533bc7795daa53c903cc2952..2292c2a7c7247f5b58903fd066e9de2ffaf86aeb 100644 --- a/substrate/frame/support/procedural/tools/derive/Cargo.toml +++ b/substrate/frame/support/procedural/tools/derive/Cargo.toml @@ -18,6 +18,6 @@ targets = ["x86_64-unknown-linux-gnu"] proc-macro = true [dependencies] -proc-macro2 = "1.0.56" +proc-macro2 = { workspace = true } quote = { features = ["proc-macro"], workspace = true } syn = { features = ["extra-traits", "full", "parsing", "proc-macro"], workspace = true } diff --git a/substrate/frame/support/src/lib.rs b/substrate/frame/support/src/lib.rs index 8ae1f56b4d686e6d6aa637aac1f6f2a0973e6157..138091689a59eaa42578896189ad321cea155a28 100644 --- a/substrate/frame/support/src/lib.rs +++ b/substrate/frame/support/src/lib.rs @@ -508,6 +508,29 @@ pub use frame_support_procedural::{ construct_runtime, match_and_insert, transactional, PalletError, RuntimeDebugNoBound, }; +/// Construct a runtime, with the given name and the given pallets. +/// +/// # Example: +#[doc = docify::embed!("src/tests/runtime.rs", runtime_macro)] +/// +/// # Supported Attributes: +/// +/// ## Legacy Ordering +/// +/// An optional attribute can be defined as #[frame_support::runtime(legacy_ordering)] to +/// ensure that the order of hooks is same as the order of pallets (and not based on the +/// pallet_index). This is to support legacy runtimes and should be avoided for new ones. +/// +/// # Note +/// +/// The population of the genesis storage depends on the order of pallets. So, if one of your +/// pallets depends on another pallet, the pallet that is depended upon needs to come before +/// the pallet depending on it. +/// +/// # Type definitions +/// +/// * The macro generates a type alias for each pallet to their `Pallet`. E.g. `type System = +/// frame_system::Pallet` pub use frame_support_procedural::runtime; #[doc(hidden)] diff --git a/substrate/frame/support/src/migrations.rs b/substrate/frame/support/src/migrations.rs index 968639e02d35be13160918619a77041ceca20be6..fa018d743653f2131944d188af7b0dd74057f143 100644 --- a/substrate/frame/support/src/migrations.rs +++ b/substrate/frame/support/src/migrations.rs @@ -17,7 +17,7 @@ use crate::{ defensive, - storage::transactional::with_transaction_opaque_err, + storage::{storage_prefix, transactional::with_transaction_opaque_err}, traits::{ Defensive, GetStorageVersion, NoStorageVersionSet, PalletInfoAccess, SafeMode, StorageVersion, @@ -369,6 +369,118 @@ impl, DbWeight: Get> frame_support::traits } } +/// `RemoveStorage` is a utility struct used to remove a storage item from a specific pallet. +/// +/// This struct is generic over three parameters: +/// - `P` is a type that implements the [`Get`] trait for a static string, representing the pallet's +/// name. +/// - `S` is a type that implements the [`Get`] trait for a static string, representing the storage +/// name. +/// - `DbWeight` is a type that implements the [`Get`] trait for [`RuntimeDbWeight`], providing the +/// weight for database operations. +/// +/// On runtime upgrade, the `on_runtime_upgrade` function will clear the storage from the specified +/// storage, logging the number of keys removed. If the `try-runtime` feature is enabled, the +/// `pre_upgrade` and `post_upgrade` functions can be used to verify the storage removal before and +/// after the upgrade. +/// +/// # Examples: +/// ```ignore +/// construct_runtime! { +/// pub enum Runtime +/// { +/// System: frame_system = 0, +/// +/// SomePallet: pallet_something = 1, +/// +/// YourOtherPallets... +/// } +/// }; +/// +/// parameter_types! { +/// pub const SomePallet: &'static str = "SomePallet"; +/// pub const StorageAccounts: &'static str = "Accounts"; +/// pub const StorageAccountCount: &'static str = "AccountCount"; +/// } +/// +/// pub type Migrations = ( +/// RemoveStorage, +/// RemoveStorage, +/// AnyOtherMigrations... +/// ); +/// +/// pub type Executive = frame_executive::Executive< +/// Runtime, +/// Block, +/// frame_system::ChainContext, +/// Runtime, +/// Migrations +/// >; +/// ``` +/// +/// WARNING: `RemoveStorage` has no guard rails preventing it from bricking the chain if the +/// operation of removing storage for the given pallet would exceed the block weight limit. +/// +/// If your storage has too many keys to be removed in a single block, it is advised to wait for +/// a multi-block scheduler currently under development which will allow for removal of storage +/// items (and performing other heavy migrations) over multiple blocks +/// (see ). +pub struct RemoveStorage, S: Get<&'static str>, DbWeight: Get>( + PhantomData<(P, S, DbWeight)>, +); +impl, S: Get<&'static str>, DbWeight: Get> + frame_support::traits::OnRuntimeUpgrade for RemoveStorage +{ + fn on_runtime_upgrade() -> frame_support::weights::Weight { + let hashed_prefix = storage_prefix(P::get().as_bytes(), S::get().as_bytes()); + let keys_removed = match clear_prefix(&hashed_prefix, None) { + KillStorageResult::AllRemoved(value) => value, + KillStorageResult::SomeRemaining(value) => { + log::error!( + "`clear_prefix` failed to remove all keys for storage `{}` from pallet `{}`. THIS SHOULD NEVER HAPPEN! ๐Ÿšจ", + S::get(), P::get() + ); + value + }, + } as u64; + + log::info!("Removed `{}` `{}` `{}` keys ๐Ÿงน", keys_removed, P::get(), S::get()); + + DbWeight::get().reads_writes(keys_removed + 1, keys_removed) + } + + #[cfg(feature = "try-runtime")] + 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()); + match contains_prefixed_key(&hashed_prefix) { + true => log::info!("Found `{}` `{}` keys pre-removal ๐Ÿ‘€", P::get(), S::get()), + false => log::warn!( + "Migration RemoveStorage<{}, {}> can be removed (no keys found pre-removal).", + P::get(), + S::get() + ), + }; + Ok(Default::default()) + } + + #[cfg(feature = "try-runtime")] + fn post_upgrade(_state: sp_std::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()); + match contains_prefixed_key(&hashed_prefix) { + true => { + log::error!("`{}` `{}` has keys remaining post-removal โ—", P::get(), S::get()); + return Err("Keys remaining post-removal, this should never happen ๐Ÿšจ".into()) + }, + false => log::info!("No `{}` `{}` keys found post-removal ๐ŸŽ‰", P::get(), S::get()), + }; + Ok(()) + } +} + /// A migration that can proceed in multiple steps. pub trait SteppedMigration { /// The cursor type that stores the progress (aka. state) of this migration. diff --git a/substrate/frame/support/src/tests/mod.rs b/substrate/frame/support/src/tests/mod.rs index 88afa243f0932e797516192f0fd1495f00cd69bf..34652231e3bce6cf9702b6439fa02e2051dee2a8 100644 --- a/substrate/frame/support/src/tests/mod.rs +++ b/substrate/frame/support/src/tests/mod.rs @@ -27,6 +27,7 @@ use sp_runtime::{generic, traits::BlakeTwo256, BuildStorage}; pub use self::frame_system::{pallet_prelude::*, Config, Pallet}; mod inject_runtime_type; +mod runtime; mod storage_alias; mod tasks; @@ -220,12 +221,25 @@ type Header = generic::Header; type UncheckedExtrinsic = generic::UncheckedExtrinsic; type Block = generic::Block; -crate::construct_runtime!( - pub enum Runtime - { - System: self::frame_system, - } -); +#[crate::runtime] +mod runtime { + #[runtime::runtime] + #[runtime::derive( + RuntimeCall, + RuntimeEvent, + RuntimeError, + RuntimeOrigin, + RuntimeFreezeReason, + RuntimeHoldReason, + RuntimeSlashReason, + RuntimeLockId, + RuntimeTask + )] + pub struct Runtime; + + #[runtime::pallet_index(0)] + pub type System = self::frame_system; +} #[crate::derive_impl(self::frame_system::config_preludes::TestDefaultConfig as self::frame_system::DefaultConfig)] impl Config for Runtime { diff --git a/substrate/frame/support/src/tests/runtime.rs b/substrate/frame/support/src/tests/runtime.rs new file mode 100644 index 0000000000000000000000000000000000000000..a9d9281f50da36e988482feac010ab778864d7dc --- /dev/null +++ b/substrate/frame/support/src/tests/runtime.rs @@ -0,0 +1,130 @@ +// 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. + +use super::{frame_system, Block}; +use crate::derive_impl; + +#[crate::pallet(dev_mode)] +mod pallet_basic { + use super::frame_system; + + #[pallet::pallet] + pub struct Pallet(_); + + #[pallet::config] + pub trait Config: frame_system::Config {} +} + +impl pallet_basic::Config for Runtime {} + +#[crate::pallet(dev_mode)] +mod pallet_with_disabled_call { + use super::frame_system; + + #[pallet::pallet] + pub struct Pallet(_); + + #[pallet::config] + pub trait Config: frame_system::Config {} +} + +impl pallet_with_disabled_call::Config for Runtime {} + +#[crate::pallet(dev_mode)] +mod pallet_with_disabled_unsigned { + use super::frame_system; + + #[pallet::pallet] + pub struct Pallet(_); + + #[pallet::config] + pub trait Config: frame_system::Config {} +} + +impl pallet_with_disabled_unsigned::Config for Runtime {} + +#[crate::pallet] +mod pallet_with_instance { + use super::frame_system; + + #[pallet::pallet] + pub struct Pallet(_); + + #[pallet::config] + pub trait Config: frame_system::Config {} +} + +#[allow(unused)] +type Instance1 = pallet_with_instance::Pallet; + +impl pallet_with_instance::Config for Runtime {} + +#[allow(unused)] +type Instance2 = pallet_with_instance::Pallet; + +impl pallet_with_instance::Config for Runtime {} + +#[derive_impl(frame_system::config_preludes::TestDefaultConfig)] +impl frame_system::Config for Runtime { + type Block = Block; +} + +#[docify::export(runtime_macro)] +#[crate::runtime] +mod runtime { + // The main runtime + #[runtime::runtime] + // Runtime Types to be generated + #[runtime::derive( + RuntimeCall, + RuntimeEvent, + RuntimeError, + RuntimeOrigin, + RuntimeFreezeReason, + RuntimeHoldReason, + RuntimeSlashReason, + RuntimeLockId, + RuntimeTask + )] + pub struct Runtime; + + // Use the concrete pallet type + #[runtime::pallet_index(0)] + pub type System = frame_system::Pallet; + + // Use path to the pallet + #[runtime::pallet_index(1)] + pub type Basic = pallet_basic; + + // Use the concrete pallet type with instance + #[runtime::pallet_index(2)] + pub type PalletWithInstance1 = pallet_with_instance::Pallet; + + // Use path to the pallet with instance + #[runtime::pallet_index(3)] + pub type PalletWithInstance2 = pallet_with_instance; + + // Ensure that the runtime does not export the calls from the pallet + #[runtime::pallet_index(4)] + #[runtime::disable_call] + pub type PalletWithDisabledCall = pallet_with_disabled_call::Pallet; + + // Ensure that the runtime does not export the unsigned calls from the pallet + #[runtime::pallet_index(5)] + #[runtime::disable_unsigned] + pub type PalletWithDisabledUnsigned = pallet_with_disabled_unsigned::Pallet; +} diff --git a/substrate/frame/support/src/traits/hooks.rs b/substrate/frame/support/src/traits/hooks.rs index ccccc5063286602538c0c46293ffabe8ad01181a..1a687cade79f5973a8b2816d0cba40ef250c4b3a 100644 --- a/substrate/frame/support/src/traits/hooks.rs +++ b/substrate/frame/support/src/traits/hooks.rs @@ -351,6 +351,7 @@ pub trait IntegrityTest { /// - [`crate::traits::misc::OffchainWorker`] /// - [`OnIdle`] /// - [`IntegrityTest`] +/// - [`OnPoll`] /// /// ## Ordering /// @@ -363,34 +364,32 @@ pub trait IntegrityTest { /// /// ```mermaid /// graph LR -/// Optional --> BeforeExtrinsics -/// BeforeExtrinsics --> Extrinsics -/// Extrinsics --> AfterExtrinsics -/// subgraph Optional +/// Optional --> Mandatory +/// Mandatory --> ExtrinsicsMandatory +/// ExtrinsicsMandatory --> Poll +/// Poll --> Extrinsics +/// Extrinsics --> AfterMandatory +/// AfterMandatory --> onIdle +/// +/// subgraph Optional /// OnRuntimeUpgrade /// end /// -/// subgraph BeforeExtrinsics +/// subgraph Mandatory /// OnInitialize /// end /// +/// subgraph ExtrinsicsMandatory +/// Inherent1 --> Inherent2 +/// end +/// /// subgraph Extrinsics /// direction TB -/// Inherent1 -/// Inherent2 -/// Extrinsic1 -/// Extrinsic2 -/// -/// Inherent1 --> Inherent2 -/// Inherent2 --> Extrinsic1 /// Extrinsic1 --> Extrinsic2 /// end /// -/// subgraph AfterExtrinsics -/// OnIdle +/// subgraph AfterMandatory /// OnFinalize -/// -/// OnIdle --> OnFinalize /// end /// ``` /// @@ -466,6 +465,8 @@ pub trait Hooks { /// /// Is not guaranteed to execute in a block and should therefore only be used in no-deadline /// scenarios. + /// + /// This is the non-mandatory version of [`Hooks::on_initialize`]. fn on_poll(_n: BlockNumber, _weight: &mut WeightMeter) {} /// Hook executed when a code change (aka. a "runtime upgrade") is detected by the FRAME diff --git a/substrate/frame/support/src/traits/storage.rs b/substrate/frame/support/src/traits/storage.rs index 9e467aea4220dd7296a3ccad8236f122ff39e7d8..875ff56bea19e3c9f5770365833092da58fca6f4 100644 --- a/substrate/frame/support/src/traits/storage.rs +++ b/substrate/frame/support/src/traits/storage.rs @@ -194,7 +194,7 @@ where } /// Some sort of cost taken from account temporarily in order to offset the cost to the chain of -/// holding some data [`Footprint`] in state. +/// holding some data `Footprint` (e.g. [`Footprint`]) in state. /// /// The cost may be increased, reduced or dropped entirely as the footprint changes. /// @@ -206,16 +206,20 @@ where /// treated as one*. Don't type to duplicate it, and remember to drop it when you're done with /// it. #[must_use] -pub trait Consideration: Member + FullCodec + TypeInfo + MaxEncodedLen { +pub trait Consideration: + Member + FullCodec + TypeInfo + MaxEncodedLen +{ /// Create a ticket for the `new` footprint attributable to `who`. This ticket *must* ultimately - /// be consumed through `update` or `drop` once the footprint changes or is removed. - fn new(who: &AccountId, new: Footprint) -> Result; + /// be consumed through `update` or `drop` once the footprint changes or is removed. `None` + /// implies no cost for a given footprint. + fn new(who: &AccountId, new: Footprint) -> Result, DispatchError>; /// Optionally consume an old ticket and alter the footprint, enforcing the new cost to `who` - /// and returning the new ticket (or an error if there was an issue). + /// and returning the new ticket (or an error if there was an issue). `None` implies no cost for + /// a given footprint. /// /// For creating tickets and dropping them, you can use the simpler `new` and `drop` instead. - fn update(self, who: &AccountId, new: Footprint) -> Result; + fn update(self, who: &AccountId, new: Footprint) -> Result, DispatchError>; /// Consume a ticket for some `old` footprint attributable to `who` which should now been freed. fn drop(self, who: &AccountId) -> Result<(), DispatchError>; @@ -230,12 +234,12 @@ pub trait Consideration: Member + FullCodec + TypeInfo + MaxEncodedLe } } -impl Consideration for () { - fn new(_: &A, _: Footprint) -> Result { - Ok(()) +impl Consideration for () { + fn new(_: &A, _: F) -> Result, DispatchError> { + Ok(Some(())) } - fn update(self, _: &A, _: Footprint) -> Result<(), DispatchError> { - Ok(()) + fn update(self, _: &A, _: F) -> Result, DispatchError> { + Ok(Some(())) } fn drop(self, _: &A) -> Result<(), DispatchError> { Ok(()) diff --git a/substrate/frame/support/src/traits/tokens.rs b/substrate/frame/support/src/traits/tokens.rs index 8842b20580181f81e4377a0d9f6223e59a6fee6a..138703cf1d135ef50a228e008fae3d37e0c972a1 100644 --- a/substrate/frame/support/src/traits/tokens.rs +++ b/substrate/frame/support/src/traits/tokens.rs @@ -30,8 +30,8 @@ pub use imbalance::Imbalance; pub mod pay; pub use misc::{ AssetId, Balance, BalanceStatus, ConversionFromAssetBalance, ConversionToAssetBalance, - ConvertRank, DepositConsequence, ExistenceRequirement, Fortitude, GetSalary, Locker, Precision, - Preservation, Provenance, Restriction, UnityAssetBalanceConversion, UnityOrOuterConversion, - WithdrawConsequence, WithdrawReasons, + ConvertRank, DepositConsequence, ExistenceRequirement, Fortitude, GetSalary, IdAmount, Locker, + Precision, Preservation, Provenance, Restriction, UnityAssetBalanceConversion, + UnityOrOuterConversion, WithdrawConsequence, WithdrawReasons, }; pub use pay::{Pay, PayFromAccount, PaymentStatus}; diff --git a/substrate/frame/support/src/traits/tokens/fungible/mod.rs b/substrate/frame/support/src/traits/tokens/fungible/mod.rs index 01c3b9dfe46a562ec5c0692fd51ecc0e53f83872..b8e985648983e0fe6257e4f676f39b6a34847533 100644 --- a/substrate/frame/support/src/traits/tokens/fungible/mod.rs +++ b/substrate/frame/support/src/traits/tokens/fungible/mod.rs @@ -198,31 +198,40 @@ use crate::{ MaxEncodedLen, RuntimeDebugNoBound, )] -#[scale_info(skip_type_params(A, F, R, D))] +#[scale_info(skip_type_params(A, F, R, D, Fp))] #[codec(mel_bound())] -pub struct FreezeConsideration(F::Balance, PhantomData (A, R, D)>) +pub struct FreezeConsideration(F::Balance, PhantomData (A, R, D, Fp)>) where F: MutateFreeze; impl< A: 'static, F: 'static + MutateFreeze, R: 'static + Get, - D: 'static + Convert, - > Consideration for FreezeConsideration + D: 'static + Convert, + Fp: 'static, + > Consideration for FreezeConsideration { - fn new(who: &A, footprint: Footprint) -> Result { + fn new(who: &A, footprint: Fp) -> Result, DispatchError> { let new = D::convert(footprint); - F::increase_frozen(&R::get(), who, new)?; - Ok(Self(new, PhantomData)) + if new.is_zero() { + Ok(None) + } else { + F::increase_frozen(&R::get(), who, new)?; + Ok(Some(Self(new, PhantomData))) + } } - fn update(self, who: &A, footprint: Footprint) -> Result { + fn update(self, who: &A, footprint: Fp) -> Result, DispatchError> { let new = D::convert(footprint); if self.0 > new { F::decrease_frozen(&R::get(), who, self.0 - new)?; } else if new > self.0 { F::increase_frozen(&R::get(), who, new - self.0)?; } - Ok(Self(new, PhantomData)) + if new.is_zero() { + Ok(None) + } else { + Ok(Some(Self(new, PhantomData))) + } } fn drop(self, who: &A) -> Result<(), DispatchError> { F::decrease_frozen(&R::get(), who, self.0).map(|_| ()) @@ -240,31 +249,43 @@ impl< MaxEncodedLen, RuntimeDebugNoBound, )] -#[scale_info(skip_type_params(A, F, R, D))] +#[scale_info(skip_type_params(A, F, R, D, Fp))] #[codec(mel_bound())] -pub struct HoldConsideration(F::Balance, PhantomData (A, R, D)>) +pub struct HoldConsideration( + F::Balance, + PhantomData (A, R, D, Fp)>, +) where F: MutateHold; impl< A: 'static, F: 'static + MutateHold, R: 'static + Get, - D: 'static + Convert, - > Consideration for HoldConsideration + D: 'static + Convert, + Fp: 'static, + > Consideration for HoldConsideration { - fn new(who: &A, footprint: Footprint) -> Result { + fn new(who: &A, footprint: Fp) -> Result, DispatchError> { let new = D::convert(footprint); - F::hold(&R::get(), who, new)?; - Ok(Self(new, PhantomData)) + if new.is_zero() { + Ok(None) + } else { + F::hold(&R::get(), who, new)?; + Ok(Some(Self(new, PhantomData))) + } } - fn update(self, who: &A, footprint: Footprint) -> Result { + fn update(self, who: &A, footprint: Fp) -> Result, DispatchError> { let new = D::convert(footprint); if self.0 > new { F::release(&R::get(), who, self.0 - new, BestEffort)?; } else if new > self.0 { F::hold(&R::get(), who, new - self.0)?; } - Ok(Self(new, PhantomData)) + if new.is_zero() { + Ok(None) + } else { + Ok(Some(Self(new, PhantomData))) + } } fn drop(self, who: &A) -> Result<(), DispatchError> { F::release(&R::get(), who, self.0, BestEffort).map(|_| ()) @@ -291,22 +312,34 @@ impl< MaxEncodedLen, RuntimeDebugNoBound, )] -#[scale_info(skip_type_params(A, Fx, Rx, D))] +#[scale_info(skip_type_params(A, Fx, Rx, D, Fp))] #[codec(mel_bound())] -pub struct LoneFreezeConsideration(PhantomData (A, Fx, Rx, D)>); +pub struct LoneFreezeConsideration(PhantomData (A, Fx, Rx, D, Fp)>); impl< A: 'static, Fx: 'static + MutateFreeze, Rx: 'static + Get, - D: 'static + Convert, - > Consideration for LoneFreezeConsideration + D: 'static + Convert, + Fp: 'static, + > Consideration for LoneFreezeConsideration { - fn new(who: &A, footprint: Footprint) -> Result { + fn new(who: &A, footprint: Fp) -> Result, DispatchError> { ensure!(Fx::balance_frozen(&Rx::get(), who).is_zero(), DispatchError::Unavailable); - Fx::set_frozen(&Rx::get(), who, D::convert(footprint), Polite).map(|_| Self(PhantomData)) + let new = D::convert(footprint); + if new.is_zero() { + Ok(None) + } else { + Fx::set_frozen(&Rx::get(), who, new, Polite).map(|_| Some(Self(PhantomData))) + } } - fn update(self, who: &A, footprint: Footprint) -> Result { - Fx::set_frozen(&Rx::get(), who, D::convert(footprint), Polite).map(|_| Self(PhantomData)) + fn update(self, who: &A, footprint: Fp) -> Result, DispatchError> { + let new = D::convert(footprint); + let _ = Fx::set_frozen(&Rx::get(), who, new, Polite)?; + if new.is_zero() { + Ok(None) + } else { + Ok(Some(Self(PhantomData))) + } } fn drop(self, who: &A) -> Result<(), DispatchError> { Fx::thaw(&Rx::get(), who).map(|_| ()) @@ -330,22 +363,34 @@ impl< MaxEncodedLen, RuntimeDebugNoBound, )] -#[scale_info(skip_type_params(A, Fx, Rx, D))] +#[scale_info(skip_type_params(A, Fx, Rx, D, Fp))] #[codec(mel_bound())] -pub struct LoneHoldConsideration(PhantomData (A, Fx, Rx, D)>); +pub struct LoneHoldConsideration(PhantomData (A, Fx, Rx, D, Fp)>); impl< A: 'static, F: 'static + MutateHold, R: 'static + Get, - D: 'static + Convert, - > Consideration for LoneHoldConsideration + D: 'static + Convert, + Fp: 'static, + > Consideration for LoneHoldConsideration { - fn new(who: &A, footprint: Footprint) -> Result { + fn new(who: &A, footprint: Fp) -> Result, DispatchError> { ensure!(F::balance_on_hold(&R::get(), who).is_zero(), DispatchError::Unavailable); - F::set_on_hold(&R::get(), who, D::convert(footprint)).map(|_| Self(PhantomData)) + let new = D::convert(footprint); + if new.is_zero() { + Ok(None) + } else { + F::set_on_hold(&R::get(), who, new).map(|_| Some(Self(PhantomData))) + } } - fn update(self, who: &A, footprint: Footprint) -> Result { - F::set_on_hold(&R::get(), who, D::convert(footprint)).map(|_| Self(PhantomData)) + fn update(self, who: &A, footprint: Fp) -> Result, DispatchError> { + let new = D::convert(footprint); + let _ = F::set_on_hold(&R::get(), who, new)?; + if new.is_zero() { + Ok(None) + } else { + Ok(Some(Self(PhantomData))) + } } fn drop(self, who: &A) -> Result<(), DispatchError> { F::release_all(&R::get(), who, BestEffort).map(|_| ()) diff --git a/substrate/frame/support/src/traits/tokens/misc.rs b/substrate/frame/support/src/traits/tokens/misc.rs index 424acb1d550b15b69582d004e2e466e65e6a9b3f..e1ff1e058ae7aabd8ce9e0725b51f292c406a1a5 100644 --- a/substrate/frame/support/src/traits/tokens/misc.rs +++ b/substrate/frame/support/src/traits/tokens/misc.rs @@ -17,7 +17,7 @@ //! Miscellaneous types. -use crate::traits::Contains; +use crate::{traits::Contains, TypeInfo}; use codec::{Decode, Encode, FullCodec, MaxEncodedLen}; use sp_arithmetic::traits::{AtLeast32BitUnsigned, Zero}; use sp_core::RuntimeDebug; @@ -357,3 +357,12 @@ impl> GetSalary for ConvertRank { C::convert(rank) } } + +/// An identifier and balance. +#[derive(Encode, Decode, Clone, PartialEq, Eq, RuntimeDebug, MaxEncodedLen, TypeInfo)] +pub struct IdAmount { + /// An identifier for this item. + pub id: Id, + /// Some amount for this item. + pub amount: Balance, +} diff --git a/substrate/frame/support/test/Cargo.toml b/substrate/frame/support/test/Cargo.toml index 6e861ad769cf71d0c1200b2039f28217a558b335..697e14ae1d38893428f19f41aec441c19cfd1711 100644 --- a/substrate/frame/support/test/Cargo.toml +++ b/substrate/frame/support/test/Cargo.toml @@ -15,29 +15,29 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -static_assertions = "1.1.0" +static_assertions = { workspace = true, default-features = true } serde = { features = ["derive"], workspace = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-metadata = { version = "16.0.0", default-features = false, features = ["current"] } -sp-api = { path = "../../../primitives/api", default-features = false } -sp-arithmetic = { path = "../../../primitives/arithmetic", default-features = false } -sp-io = { path = "../../../primitives/io", default-features = false } -sp-state-machine = { path = "../../../primitives/state-machine", optional = true } -frame-support = { path = "..", default-features = false, features = ["experimental"] } -frame-benchmarking = { path = "../../benchmarking", default-features = false } -sp-runtime = { path = "../../../primitives/runtime", default-features = false } -sp-core = { path = "../../../primitives/core", default-features = false } -sp-std = { path = "../../../primitives/std", default-features = false } -sp-version = { path = "../../../primitives/version", default-features = false } -sp-metadata-ir = { path = "../../../primitives/metadata-ir", default-features = false } -trybuild = { version = "1.0.88", features = ["diff"] } -pretty_assertions = "1.3.0" -rustversion = "1.0.6" -frame-system = { path = "../../system", default-features = false } -frame-executive = { path = "../../executive", default-features = false } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } +frame-metadata = { features = ["current"], workspace = true } +sp-api = { workspace = true } +sp-arithmetic = { workspace = true } +sp-io = { workspace = true } +sp-state-machine = { optional = true, workspace = true, default-features = true } +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 } +pretty_assertions = { workspace = true } +rustversion = { workspace = true } +frame-system = { workspace = true } +frame-executive = { workspace = true } # The "std" feature for this pallet is never activated on purpose, in order to test construct_runtime error message -test-pallet = { package = "frame-support-test-pallet", path = "pallet", default-features = false } +test-pallet = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/support/test/compile_pass/Cargo.toml b/substrate/frame/support/test/compile_pass/Cargo.toml index d6e0c66261a993ba70413d89d70dabc107177e1d..60896ca2a10f25401b853e5e297dbbdd14635a8b 100644 --- a/substrate/frame/support/test/compile_pass/Cargo.toml +++ b/substrate/frame/support/test/compile_pass/Cargo.toml @@ -15,13 +15,13 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-support = { path = "../..", default-features = false } -frame-system = { path = "../../../system", default-features = false } -sp-core = { path = "../../../../primitives/core", default-features = false } -sp-runtime = { path = "../../../../primitives/runtime", default-features = false } -sp-version = { path = "../../../../primitives/version", default-features = false } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-core = { workspace = true } +sp-runtime = { workspace = true } +sp-version = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/support/test/pallet/Cargo.toml b/substrate/frame/support/test/pallet/Cargo.toml index 8607339a2b054530404499c23a402c2a673e2b5a..cee0eac6f1bcd2a54337d97a968fceab76320133 100644 --- a/substrate/frame/support/test/pallet/Cargo.toml +++ b/substrate/frame/support/test/pallet/Cargo.toml @@ -15,12 +15,12 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } serde = { features = ["derive"], workspace = true } -frame-support = { path = "../..", default-features = false } -frame-system = { path = "../../../system", default-features = false } -sp-runtime = { path = "../../../../primitives/runtime", default-features = false } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-runtime = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/support/test/stg_frame_crate/Cargo.toml b/substrate/frame/support/test/stg_frame_crate/Cargo.toml index 5b97db60c00bb7c8b5b40dfa9f823fcc27b73d95..8447cc12ef20cac6058d2666971d8501627e0a64 100644 --- a/substrate/frame/support/test/stg_frame_crate/Cargo.toml +++ b/substrate/frame/support/test/stg_frame_crate/Cargo.toml @@ -15,9 +15,9 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -frame = { package = "polkadot-sdk-frame", path = "../../..", default-features = false, features = ["experimental", "runtime"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +frame = { features = ["experimental", "runtime"], workspace = true } +scale-info = { features = ["derive"], workspace = true } [features] default = ["std"] diff --git a/substrate/frame/support/test/tests/runtime_legacy_ordering.rs b/substrate/frame/support/test/tests/runtime_legacy_ordering.rs index 5b74cc172c6eb8ed057284ef9dd4c2f91fbf8d7c..6330a138e2f2a66a5b763ecd57d1c742fa092465 100644 --- a/substrate/frame/support/test/tests/runtime_legacy_ordering.rs +++ b/substrate/frame/support/test/tests/runtime_legacy_ordering.rs @@ -340,7 +340,7 @@ mod runtime { pub type Module1_9 = module1; } -#[derive_impl(frame_system::config_preludes::TestDefaultConfig as frame_system::DefaultConfig)] +#[derive_impl(frame_system::config_preludes::TestDefaultConfig)] impl frame_system::Config for Runtime { type AccountId = AccountId; type Lookup = sp_runtime::traits::IdentityLookup; diff --git a/substrate/frame/system/Cargo.toml b/substrate/frame/system/Cargo.toml index a2a8970814b0a7c7c2c3f5ba9536371236c16bbd..3d056c894b92f49c40201fb56de08b92b4c2244d 100644 --- a/substrate/frame/system/Cargo.toml +++ b/substrate/frame/system/Cargo.toml @@ -16,24 +16,24 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -cfg-if = "1.0" -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +cfg-if = { workspace = true } +codec = { features = ["derive"], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive", "serde"] } +scale-info = { features = ["derive", "serde"], workspace = true } serde = { features = ["alloc", "derive"], workspace = true } -frame-support = { path = "../support", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false, features = ["serde"] } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false, features = ["serde"] } -sp-std = { path = "../../primitives/std", default-features = false } -sp-version = { path = "../../primitives/version", default-features = false, features = ["serde"] } -sp-weights = { path = "../../primitives/weights", default-features = false, features = ["serde"] } -docify = "0.2.8" +frame-support = { workspace = true } +sp-core = { features = ["serde"], workspace = true } +sp-io = { workspace = true } +sp-runtime = { features = ["serde"], workspace = true } +sp-std = { workspace = true } +sp-version = { features = ["serde"], workspace = true } +sp-weights = { features = ["serde"], workspace = true } +docify = { workspace = true } [dev-dependencies] -criterion = "0.5.1" -sp-externalities = { path = "../../primitives/externalities" } -substrate-test-runtime-client = { path = "../../test-utils/runtime/client" } +criterion = { workspace = true, default-features = true } +sp-externalities = { workspace = true, default-features = true } +substrate-test-runtime-client = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/system/benchmarking/Cargo.toml b/substrate/frame/system/benchmarking/Cargo.toml index 022f0ffce6b5ee23168db0ccaad1da5ea767ddf3..47a6721b93f585bf3b5c0f6a777327ade4f38be6 100644 --- a/substrate/frame/system/benchmarking/Cargo.toml +++ b/substrate/frame/system/benchmarking/Cargo.toml @@ -16,19 +16,19 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../../benchmarking", default-features = false } -frame-support = { path = "../../support", default-features = false } -frame-system = { path = "..", default-features = false } -sp-core = { path = "../../../primitives/core", default-features = false } -sp-runtime = { path = "../../../primitives/runtime", default-features = false } -sp-std = { path = "../../../primitives/std", default-features = false } +codec = { workspace = true } +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-core = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -sp-io = { path = "../../../primitives/io" } -sp-externalities = { path = "../../../primitives/externalities" } -sp-version = { path = "../../../primitives/version" } +sp-io = { workspace = true, default-features = true } +sp-externalities = { workspace = true, default-features = true } +sp-version = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/system/rpc/runtime-api/Cargo.toml b/substrate/frame/system/rpc/runtime-api/Cargo.toml index 8b71ca2a13952d4aa1bf983a30d17d3126189524..901a035b6476c7af2e13013a141f3dcafa391a4a 100644 --- a/substrate/frame/system/rpc/runtime-api/Cargo.toml +++ b/substrate/frame/system/rpc/runtime-api/Cargo.toml @@ -16,9 +16,9 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -sp-api = { path = "../../../../primitives/api", default-features = false } -docify = "0.2.0" +codec = { workspace = true } +sp-api = { workspace = true } +docify = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/system/src/extensions/check_weight.rs b/substrate/frame/system/src/extensions/check_weight.rs index 5d6c68989ed53bfec6d95f80f5c9b149aa4c3063..d4705f200efddacd18149651acf8ed431ca722a8 100644 --- a/substrate/frame/system/src/extensions/check_weight.rs +++ b/substrate/frame/system/src/extensions/check_weight.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use crate::{limits::BlockWeights, Config, DispatchClass, Pallet, LOG_TARGET}; +use crate::{limits::BlockWeights, Config, Pallet, LOG_TARGET}; use codec::{Decode, Encode}; use frame_support::{ dispatch::{DispatchInfo, PostDispatchInfo}, @@ -106,8 +106,7 @@ where let all_weight = Pallet::::block_weight(); let maximum_weight = T::BlockWeights::get(); let next_weight = - calculate_consumed_weight::(&maximum_weight, all_weight, info)?; - check_combined_proof_size::(info, &maximum_weight, next_len, &next_weight)?; + calculate_consumed_weight::(&maximum_weight, all_weight, info, len)?; Self::check_extrinsic_weight(info)?; crate::AllExtrinsicsLen::::put(next_len); @@ -130,36 +129,6 @@ where } } -/// Check that the combined extrinsic length and proof size together do not exceed the PoV limit. -pub fn check_combined_proof_size( - info: &DispatchInfoOf, - maximum_weight: &BlockWeights, - next_len: u32, - next_weight: &crate::ConsumedWeight, -) -> Result<(), TransactionValidityError> -where - Call: Dispatchable, -{ - // This extra check ensures that the extrinsic length does not push the - // PoV over the limit. - let total_pov_size = next_weight.total().proof_size().saturating_add(next_len as u64); - if total_pov_size > maximum_weight.max_block.proof_size() { - log::debug!( - target: LOG_TARGET, - "Extrinsic exceeds total pov size. Still including if mandatory. size: {}kb, limit: {}kb, is_mandatory: {}", - total_pov_size as f64/1024.0, - maximum_weight.max_block.proof_size() as f64/1024.0, - info.class == DispatchClass::Mandatory - ); - return match info.class { - // Allow mandatory extrinsics - DispatchClass::Mandatory => Ok(()), - _ => Err(InvalidTransaction::ExhaustsResources.into()), - }; - } - Ok(()) -} - /// Checks if the current extrinsic can fit into the block with respect to block weight limits. /// /// Upon successes, it returns the new block weight as a `Result`. @@ -167,12 +136,16 @@ pub fn calculate_consumed_weight( maximum_weight: &BlockWeights, mut all_weight: crate::ConsumedWeight, info: &DispatchInfoOf, + len: usize, ) -> Result where Call: Dispatchable, { - let extrinsic_weight = - info.weight.saturating_add(maximum_weight.get(info.class).base_extrinsic); + // Also Consider extrinsic length as proof weight. + let extrinsic_weight = info + .weight + .saturating_add(maximum_weight.get(info.class).base_extrinsic) + .saturating_add(Weight::from_parts(0, len as u64)); let limit_per_class = maximum_weight.get(info.class); // add the weight. If class is unlimited, use saturating add instead of checked one. @@ -772,168 +745,115 @@ mod tests { &maximum_weight, all_weight.clone(), &mandatory1, + 0 )); assert_err!( calculate_consumed_weight::<::RuntimeCall>( &maximum_weight, all_weight, &mandatory2, + 0 ), InvalidTransaction::ExhaustsResources ); } #[test] - fn maximum_proof_size_includes_length() { + fn proof_size_includes_length() { let maximum_weight = BlockWeights::builder() .base_block(Weight::zero()) .for_class(DispatchClass::non_mandatory(), |w| { w.base_extrinsic = Weight::zero(); - w.max_total = Some(Weight::from_parts(20, 10)); + w.max_total = Some(Weight::from_parts(20, 1000)); }) .for_class(DispatchClass::Mandatory, |w| { w.base_extrinsic = Weight::zero(); - w.reserved = Some(Weight::from_parts(5, 10)); - w.max_total = None; + w.max_total = Some(Weight::from_parts(20, 1000)); }) .build_or_panic(); + let all_weight = crate::ConsumedWeight::new(|class| match class { + DispatchClass::Normal => Weight::from_parts(5, 0), + DispatchClass::Operational => Weight::from_parts(5, 0), + DispatchClass::Mandatory => Weight::from_parts(0, 0), + }); - assert_eq!(maximum_weight.max_block, Weight::from_parts(20, 10)); + let normal = DispatchInfo { + weight: Weight::from_parts(5, 0), + class: DispatchClass::Normal, + ..Default::default() + }; - let info = DispatchInfo { class: DispatchClass::Normal, ..Default::default() }; - let mandatory = DispatchInfo { class: DispatchClass::Mandatory, ..Default::default() }; - // We have 10 reftime and 5 proof size left over. - let next_weight = crate::ConsumedWeight::new(|class| match class { - DispatchClass::Normal => Weight::from_parts(10, 5), - DispatchClass::Operational => Weight::from_parts(0, 0), - DispatchClass::Mandatory => Weight::zero(), - }); + let mandatory = DispatchInfo { + weight: Weight::from_parts(5, 0), + class: DispatchClass::Mandatory, + ..Default::default() + }; - // Simple checks for the length - assert_ok!(check_combined_proof_size::<::RuntimeCall>( - &info, + // Using 0 length extrinsics. + let consumed = calculate_consumed_weight::<::RuntimeCall>( &maximum_weight, + all_weight.clone(), + &normal, 0, - &next_weight - )); - assert_ok!(check_combined_proof_size::<::RuntimeCall>( - &info, + ) + .unwrap(); + + assert_eq!(consumed.total().saturating_sub(all_weight.total()), normal.weight); + + let consumed = calculate_consumed_weight::<::RuntimeCall>( &maximum_weight, - 5, - &next_weight - )); - assert_err!( - check_combined_proof_size::<::RuntimeCall>( - &info, - &maximum_weight, - 6, - &next_weight - ), - InvalidTransaction::ExhaustsResources - ); - assert_ok!(check_combined_proof_size::<::RuntimeCall>( + all_weight.clone(), &mandatory, - &maximum_weight, - 6, - &next_weight - )); + 0, + ) + .unwrap(); + assert_eq!(consumed.total().saturating_sub(all_weight.total()), mandatory.weight); - // We have 10 reftime and 0 proof size left over. - let next_weight = crate::ConsumedWeight::new(|class| match class { - DispatchClass::Normal => Weight::from_parts(10, 10), - DispatchClass::Operational => Weight::from_parts(0, 0), - DispatchClass::Mandatory => Weight::zero(), - }); - assert_ok!(check_combined_proof_size::<::RuntimeCall>( - &info, + // Using non zero length extrinsics. + let consumed = calculate_consumed_weight::<::RuntimeCall>( &maximum_weight, - 0, - &next_weight - )); - assert_err!( - check_combined_proof_size::<::RuntimeCall>( - &info, - &maximum_weight, - 1, - &next_weight - ), - InvalidTransaction::ExhaustsResources + all_weight.clone(), + &normal, + 100, + ) + .unwrap(); + // Must account for the len in the proof size + assert_eq!( + consumed.total().saturating_sub(all_weight.total()), + normal.weight.add_proof_size(100) ); - assert_ok!(check_combined_proof_size::<::RuntimeCall>( - &mandatory, - &maximum_weight, - 1, - &next_weight - )); - // We have 10 reftime and 2 proof size left over. - // Used weight is spread across dispatch classes this time. - let next_weight = crate::ConsumedWeight::new(|class| match class { - DispatchClass::Normal => Weight::from_parts(10, 5), - DispatchClass::Operational => Weight::from_parts(0, 3), - DispatchClass::Mandatory => Weight::zero(), - }); - assert_ok!(check_combined_proof_size::<::RuntimeCall>( - &info, + let consumed = calculate_consumed_weight::<::RuntimeCall>( &maximum_weight, - 0, - &next_weight - )); - assert_ok!(check_combined_proof_size::<::RuntimeCall>( - &info, - &maximum_weight, - 2, - &next_weight - )); - assert_err!( - check_combined_proof_size::<::RuntimeCall>( - &info, - &maximum_weight, - 3, - &next_weight - ), - InvalidTransaction::ExhaustsResources - ); - assert_ok!(check_combined_proof_size::<::RuntimeCall>( + all_weight.clone(), &mandatory, - &maximum_weight, - 3, - &next_weight - )); + 100, + ) + .unwrap(); + // Must account for the len in the proof size + assert_eq!( + consumed.total().saturating_sub(all_weight.total()), + mandatory.weight.add_proof_size(100) + ); - // Ref time is over the limit. Should not happen, but we should make sure that it is - // ignored. - let next_weight = crate::ConsumedWeight::new(|class| match class { - DispatchClass::Normal => Weight::from_parts(30, 5), - DispatchClass::Operational => Weight::from_parts(0, 0), - DispatchClass::Mandatory => Weight::zero(), - }); - assert_ok!(check_combined_proof_size::<::RuntimeCall>( - &info, + // Using oversized zero length extrinsics. + let consumed = calculate_consumed_weight::<::RuntimeCall>( &maximum_weight, - 0, - &next_weight - )); - assert_ok!(check_combined_proof_size::<::RuntimeCall>( - &info, - &maximum_weight, - 5, - &next_weight - )); - assert_err!( - check_combined_proof_size::<::RuntimeCall>( - &info, - &maximum_weight, - 6, - &next_weight - ), - InvalidTransaction::ExhaustsResources + all_weight.clone(), + &normal, + 2000, ); - assert_ok!(check_combined_proof_size::<::RuntimeCall>( - &mandatory, + // errors out + assert_eq!(consumed, Err(InvalidTransaction::ExhaustsResources.into())); + + // Using oversized zero length extrinsics. + let consumed = calculate_consumed_weight::<::RuntimeCall>( &maximum_weight, - 6, - &next_weight - )); + all_weight.clone(), + &mandatory, + 2000, + ); + // errors out + assert_eq!(consumed, Err(InvalidTransaction::ExhaustsResources.into())); } } diff --git a/substrate/frame/timestamp/Cargo.toml b/substrate/frame/timestamp/Cargo.toml index 93ce09611b55dc49746ad5e99fa98b21cf25ea6d..2da6e2d5a95d222853e7eeca372c770de84f77ea 100644 --- a/substrate/frame/timestamp/Cargo.toml +++ b/substrate/frame/timestamp/Cargo.toml @@ -17,24 +17,24 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive", "max-encoded-len"] } +codec = { features = ["derive", "max-encoded-len"], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-inherents = { path = "../../primitives/inherents", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false, optional = true } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -sp-storage = { path = "../../primitives/storage", default-features = false } -sp-timestamp = { path = "../../primitives/timestamp", default-features = false } +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +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 } -docify = "0.2.8" +docify = { workspace = true } [dev-dependencies] -sp-core = { path = "../../primitives/core" } -sp-io = { path = "../../primitives/io" } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/timestamp/src/benchmarking.rs b/substrate/frame/timestamp/src/benchmarking.rs index 82dfdfa8b312065aededecd7e81404c19403fe24..d8c27b4967af9a59a6a1711b8aa53726d4968fd2 100644 --- a/substrate/frame/timestamp/src/benchmarking.rs +++ b/substrate/frame/timestamp/src/benchmarking.rs @@ -25,7 +25,7 @@ use frame_support::{ensure, traits::OnFinalize}; use frame_system::RawOrigin; use sp_storage::TrackedStorageKey; -use crate::Pallet as Timestamp; +use crate::{Now, Pallet as Timestamp}; const MAX_TIME: u32 = 100; @@ -42,7 +42,7 @@ benchmarks! { }); }: _(RawOrigin::None, t.into()) verify { - ensure!(Timestamp::::now() == t.into(), "Time was not set."); + ensure!(Now::::get() == t.into(), "Time was not set."); } on_finalize { diff --git a/substrate/frame/timestamp/src/lib.rs b/substrate/frame/timestamp/src/lib.rs index 5269f17eca6b2151a787f91a1126c822aaf83879..6a22ab1cd5ef8fde0d94791e82750f46629a2340 100644 --- a/substrate/frame/timestamp/src/lib.rs +++ b/substrate/frame/timestamp/src/lib.rs @@ -202,7 +202,6 @@ pub mod pallet { /// The current time for the current block. #[pallet::storage] - #[pallet::getter(fn now)] pub type Now = StorageValue<_, T::Moment, ValueQuery>; /// Whether the timestamp has been updated in this block. @@ -261,7 +260,7 @@ pub mod pallet { pub fn set(origin: OriginFor, #[pallet::compact] now: T::Moment) -> DispatchResult { ensure_none(origin)?; assert!(!DidUpdate::::exists(), "Timestamp must be updated only once in the block"); - let prev = Self::now(); + let prev = Now::::get(); assert!( prev.is_zero() || now >= prev + T::MinimumPeriod::get(), "Timestamp must increment by at least between sequential blocks" @@ -296,7 +295,7 @@ pub mod pallet { .expect("Timestamp inherent data must be provided"); let data = (*inherent_data).saturated_into::(); - let next_time = cmp::max(data, Self::now() + T::MinimumPeriod::get()); + let next_time = cmp::max(data, Now::::get() + T::MinimumPeriod::get()); Some(Call::set { now: next_time }) } @@ -317,7 +316,7 @@ pub mod pallet { .expect("Timestamp inherent data not correctly encoded") .expect("Timestamp inherent data must be provided"); - let minimum = (Self::now() + T::MinimumPeriod::get()).saturated_into::(); + let minimum = (Now::::get() + T::MinimumPeriod::get()).saturated_into::(); if t > *(data + MAX_TIMESTAMP_DRIFT_MILLIS) { Err(InherentError::TooFarInFuture) } else if t < minimum { @@ -339,7 +338,7 @@ impl Pallet { /// NOTE: if this function is called prior to setting the timestamp, /// it will return the timestamp of the previous block. pub fn get() -> T::Moment { - Self::now() + Now::::get() } /// Set the timestamp to something in particular. Only used for tests. @@ -356,7 +355,7 @@ impl Time for Pallet { type Moment = T::Moment; fn now() -> Self::Moment { - Self::now() + Now::::get() } } @@ -367,7 +366,7 @@ impl UnixTime for Pallet { fn now() -> core::time::Duration { // now is duration since unix epoch in millisecond as documented in // `sp_timestamp::InherentDataProvider`. - let now = Self::now(); + let now = Now::::get(); sp_std::if_std! { if now == T::Moment::zero() { log::error!( diff --git a/substrate/frame/timestamp/src/tests.rs b/substrate/frame/timestamp/src/tests.rs index cc49d8a3296e831ae01fd60ab28c0cf7fafbf9b5..a83855561889f162c0787400e700ef6464fb854f 100644 --- a/substrate/frame/timestamp/src/tests.rs +++ b/substrate/frame/timestamp/src/tests.rs @@ -25,7 +25,7 @@ fn timestamp_works() { new_test_ext().execute_with(|| { crate::Now::::put(46); assert_ok!(Timestamp::set(RuntimeOrigin::none(), 69)); - assert_eq!(Timestamp::now(), 69); + assert_eq!(crate::Now::::get(), 69); assert_eq!(Some(69), get_captured_moment()); }); } diff --git a/substrate/frame/tips/Cargo.toml b/substrate/frame/tips/Cargo.toml index bcd54461406ead0f1bd67ab427c023d91b63fa0e..abebaa19aedaea145ad31be7d6af4abc46aad4dd 100644 --- a/substrate/frame/tips/Cargo.toml +++ b/substrate/frame/tips/Cargo.toml @@ -16,22 +16,22 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } serde = { features = ["derive"], optional = true, workspace = true, default-features = true } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -pallet-treasury = { path = "../treasury", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-treasury = { workspace = true } +sp-core = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -pallet-balances = { path = "../balances" } -sp-storage = { path = "../../primitives/storage" } +pallet-balances = { workspace = true, default-features = true } +sp-storage = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/tips/src/lib.rs b/substrate/frame/tips/src/lib.rs index 8c360fb57d72488553529ab4264eb7f8b444c064..e16ee041fcdf8b9692b9b9c9d9570fd7c38d715f 100644 --- a/substrate/frame/tips/src/lib.rs +++ b/substrate/frame/tips/src/lib.rs @@ -169,6 +169,9 @@ pub mod pallet { /// update weights file when altering this method. type Tippers: SortedMembers + ContainsLengthBound; + /// Handler for the unbalanced decrease when slashing for a removed tip. + type OnSlash: OnUnbalanced>; + /// Weight information for extrinsics in this pallet. type WeightInfo: WeightInfo; } diff --git a/substrate/frame/tips/src/tests.rs b/substrate/frame/tips/src/tests.rs index 78df3736815a11dcc8a766e6eb88c4972157a7b3..7e4a9368ad0c6abdf8930195e32fb982a162c994 100644 --- a/substrate/frame/tips/src/tests.rs +++ b/substrate/frame/tips/src/tests.rs @@ -65,20 +65,9 @@ impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type Balance = u64; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ConstU64<1>; type AccountStore = System; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } parameter_types! { static TenToFourteenTestValue: Vec = vec![10,11,12,13,14]; @@ -105,7 +94,6 @@ impl ContainsLengthBound for TenToFourteen { } } parameter_types! { - pub const ProposalBond: Permill = Permill::from_percent(5); pub const Burn: Permill = Permill::from_percent(50); pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry"); pub const TreasuryPalletId2: PalletId = PalletId(*b"py/trsr2"); @@ -116,13 +104,8 @@ parameter_types! { impl pallet_treasury::Config for Test { type PalletId = TreasuryPalletId; type Currency = pallet_balances::Pallet; - type ApproveOrigin = frame_system::EnsureRoot; type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; - type OnSlash = (); - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ConstU64<1>; - type ProposalBondMaximum = (); type SpendPeriod = ConstU64<2>; type Burn = Burn; type BurnDestination = (); // Just gets burned. @@ -143,13 +126,8 @@ impl pallet_treasury::Config for Test { impl pallet_treasury::Config for Test { type PalletId = TreasuryPalletId2; type Currency = pallet_balances::Pallet; - type ApproveOrigin = frame_system::EnsureRoot; type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; - type OnSlash = (); - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ConstU64<1>; - type ProposalBondMaximum = (); type SpendPeriod = ConstU64<2>; type Burn = Burn; type BurnDestination = (); // Just gets burned. @@ -180,6 +158,7 @@ impl Config for Test { type DataDepositPerByte = ConstU64<1>; type MaxTipAmount = ConstU64<10_000_000>; type RuntimeEvent = RuntimeEvent; + type OnSlash = (); type WeightInfo = (); } @@ -192,6 +171,7 @@ impl Config for Test { type DataDepositPerByte = ConstU64<1>; type MaxTipAmount = ConstU64<10_000_000>; type RuntimeEvent = RuntimeEvent; + type OnSlash = (); type WeightInfo = (); } diff --git a/substrate/frame/transaction-payment/Cargo.toml b/substrate/frame/transaction-payment/Cargo.toml index 4f7da9ae46fabe7b4dcb92bd40eab2ea339175a8..3e890a8f7b69f53b80376b78bb014a8c57726301 100644 --- a/substrate/frame/transaction-payment/Cargo.toml +++ b/substrate/frame/transaction-payment/Cargo.toml @@ -16,21 +16,21 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", -] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +], workspace = true } +scale-info = { features = ["derive"], workspace = true } serde = { optional = true, workspace = true, default-features = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +frame-support = { workspace = true } +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 } -pallet-balances = { path = "../balances" } +pallet-balances = { workspace = true, default-features = true } [features] default = ["std"] 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 177621d9adbd102369fe0466cf962441f7591e42..02ce212deb6a7b4982996945f1604ccd03ed4f29 100644 --- a/substrate/frame/transaction-payment/asset-conversion-tx-payment/Cargo.toml +++ b/substrate/frame/transaction-payment/asset-conversion-tx-payment/Cargo.toml @@ -17,21 +17,21 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] # Substrate dependencies -sp-runtime = { path = "../../../primitives/runtime", default-features = false } -sp-std = { path = "../../../primitives/std", default-features = false } -frame-support = { path = "../../support", default-features = false } -frame-system = { path = "../../system", default-features = false } -pallet-asset-conversion = { path = "../../asset-conversion", default-features = false } -pallet-transaction-payment = { path = "..", default-features = false } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +sp-runtime = { workspace = true } +sp-std = { workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-asset-conversion = { workspace = true } +pallet-transaction-payment = { workspace = true } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } [dev-dependencies] -sp-core = { path = "../../../primitives/core", default-features = false } -sp-io = { path = "../../../primitives/io", default-features = false } -sp-storage = { path = "../../../primitives/storage", default-features = false } -pallet-assets = { path = "../../assets" } -pallet-balances = { path = "../../balances" } +sp-core = { workspace = true } +sp-io = { workspace = true } +sp-storage = { workspace = true } +pallet-assets = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/mock.rs b/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/mock.rs index cc43cffd7deba11d252875d3b981e0a43eeafb1e..3f8c7bc0ea34d297dcb8ace6cb25735d9e1592a6 100644 --- a/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/mock.rs +++ b/substrate/frame/transaction-payment/asset-conversion-tx-payment/src/mock.rs @@ -98,20 +98,10 @@ parameter_types! { pub const ExistentialDeposit: u64 = 10; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Runtime { - type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); type ExistentialDeposit = ConstU64<10>; type AccountStore = System; - type MaxLocks = (); - type WeightInfo = (); - type MaxReserves = ConstU32<50>; - type ReserveIdentifier = [u8; 8]; - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } impl WeightToFeeT for WeightToFee { diff --git a/substrate/frame/transaction-payment/asset-tx-payment/Cargo.toml b/substrate/frame/transaction-payment/asset-tx-payment/Cargo.toml index a4a8efad869c84ef9fe8b905ae5c38a9ed94b614..1b92ecf53c0266606b3653911e305c4f069c1b72 100644 --- a/substrate/frame/transaction-payment/asset-tx-payment/Cargo.toml +++ b/substrate/frame/transaction-payment/asset-tx-payment/Cargo.toml @@ -17,29 +17,29 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] # Substrate dependencies -sp-core = { path = "../../../primitives/core", default-features = false } -sp-io = { path = "../../../primitives/io", default-features = false } -sp-runtime = { path = "../../../primitives/runtime", default-features = false } -sp-std = { path = "../../../primitives/std", default-features = false } +sp-core = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } -frame-support = { path = "../../support", default-features = false } -frame-system = { path = "../../system", default-features = false } -pallet-transaction-payment = { path = "..", default-features = false } -frame-benchmarking = { path = "../../benchmarking", default-features = false, optional = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +pallet-transaction-payment = { workspace = true } +frame-benchmarking = { optional = true, workspace = true } # Other dependencies -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } serde = { optional = true, workspace = true, default-features = true } [dev-dependencies] serde_json = { workspace = true, default-features = true } -sp-storage = { path = "../../../primitives/storage", default-features = false } +sp-storage = { workspace = true } -pallet-assets = { path = "../../assets" } -pallet-authorship = { path = "../../authorship" } -pallet-balances = { path = "../../balances" } +pallet-assets = { workspace = true, default-features = true } +pallet-authorship = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/transaction-payment/asset-tx-payment/src/mock.rs b/substrate/frame/transaction-payment/asset-tx-payment/src/mock.rs index fce712c3eba31f8a2816eb23fe221c2c7ce0c9bd..e84df1e4eb91b67a1cdb1477a6f5eac9b1b5180f 100644 --- a/substrate/frame/transaction-payment/asset-tx-payment/src/mock.rs +++ b/substrate/frame/transaction-payment/asset-tx-payment/src/mock.rs @@ -81,20 +81,10 @@ parameter_types! { pub const ExistentialDeposit: u64 = 10; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Runtime { - type Balance = Balance; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); type ExistentialDeposit = ConstU64<10>; type AccountStore = System; - type MaxLocks = (); - type WeightInfo = (); - type MaxReserves = ConstU32<50>; - type ReserveIdentifier = [u8; 8]; - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } impl WeightToFeeT for WeightToFee { diff --git a/substrate/frame/transaction-payment/rpc/Cargo.toml b/substrate/frame/transaction-payment/rpc/Cargo.toml index 2c9f814460f7cd1502779cc1645c0379611dc3d5..d2fb92a6bf3459beda62aeac800d379a897636d5 100644 --- a/substrate/frame/transaction-payment/rpc/Cargo.toml +++ b/substrate/frame/transaction-payment/rpc/Cargo.toml @@ -16,12 +16,12 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12" } -jsonrpsee = { version = "0.22.5", features = ["client-core", "macros", "server-core"] } -pallet-transaction-payment-rpc-runtime-api = { path = "runtime-api" } -sp-api = { path = "../../../primitives/api" } -sp-blockchain = { path = "../../../primitives/blockchain" } -sp-core = { path = "../../../primitives/core" } -sp-rpc = { path = "../../../primitives/rpc" } -sp-runtime = { path = "../../../primitives/runtime" } -sp-weights = { path = "../../../primitives/weights" } +codec = { workspace = true, default-features = true } +jsonrpsee = { features = ["client-core", "macros", "server-core"], workspace = true } +pallet-transaction-payment-rpc-runtime-api = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-rpc = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-weights = { workspace = true, default-features = true } diff --git a/substrate/frame/transaction-payment/rpc/runtime-api/Cargo.toml b/substrate/frame/transaction-payment/rpc/runtime-api/Cargo.toml index 6c0241ec5c03c4ceb757620d6ae4f528e379c74e..1a384c74b31c2f7964ef1383e25c44fdf479509d 100644 --- a/substrate/frame/transaction-payment/rpc/runtime-api/Cargo.toml +++ b/substrate/frame/transaction-payment/rpc/runtime-api/Cargo.toml @@ -16,11 +16,11 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -pallet-transaction-payment = { path = "../..", default-features = false } -sp-api = { path = "../../../../primitives/api", default-features = false } -sp-runtime = { path = "../../../../primitives/runtime", default-features = false } -sp-weights = { path = "../../../../primitives/weights", default-features = false } +codec = { features = ["derive"], workspace = true } +pallet-transaction-payment = { workspace = true } +sp-api = { workspace = true } +sp-runtime = { workspace = true } +sp-weights = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/transaction-payment/skip-feeless-payment/Cargo.toml b/substrate/frame/transaction-payment/skip-feeless-payment/Cargo.toml index 4d32a5123cf3fc0ef1322cedca7d2c8ef65ba51a..7265979cedc0c3737df51a24718e9b19d6cf57e9 100644 --- a/substrate/frame/transaction-payment/skip-feeless-payment/Cargo.toml +++ b/substrate/frame/transaction-payment/skip-feeless-payment/Cargo.toml @@ -15,15 +15,15 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] # Substrate dependencies -sp-runtime = { path = "../../../primitives/runtime", default-features = false } -sp-std = { path = "../../../primitives/std", default-features = false } +sp-runtime = { workspace = true } +sp-std = { workspace = true } -frame-support = { path = "../../support", default-features = false } -frame-system = { path = "../../system", default-features = false } +frame-support = { workspace = true } +frame-system = { workspace = true } # Other dependencies -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.5.0", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } [features] default = ["std"] diff --git a/substrate/frame/transaction-payment/src/mock.rs b/substrate/frame/transaction-payment/src/mock.rs index 7b731eeb825013325159f3bfe9fcaeeca11a2024..fa61572e9831f6487cb4c19a97737475776c55d1 100644 --- a/substrate/frame/transaction-payment/src/mock.rs +++ b/substrate/frame/transaction-payment/src/mock.rs @@ -21,7 +21,7 @@ use frame_support::{ derive_impl, dispatch::DispatchClass, parameter_types, - traits::{fungible, ConstU64, Imbalance, OnUnbalanced}, + traits::{fungible, Imbalance, OnUnbalanced}, weights::{Weight, WeightToFee as WeightToFeeT}, }; use frame_system as system; @@ -73,20 +73,9 @@ impl frame_system::Config for Runtime { type AccountData = pallet_balances::AccountData; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Runtime { - type Balance = u64; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ConstU64<1>; type AccountStore = System; - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } impl WeightToFeeT for WeightToFee { diff --git a/substrate/frame/transaction-storage/Cargo.toml b/substrate/frame/transaction-storage/Cargo.toml index bf647ca13ec1cf355e35bc9307239979ba8c8460..3bb97e0cd01562c439028f373339398b6ef4e2f1 100644 --- a/substrate/frame/transaction-storage/Cargo.toml +++ b/substrate/frame/transaction-storage/Cargo.toml @@ -16,24 +16,24 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -array-bytes = { version = "6.2.2", optional = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +array-bytes = { optional = true, workspace = true, default-features = true } +codec = { workspace = true } +scale-info = { features = ["derive"], workspace = true } serde = { optional = true, workspace = true, default-features = true } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -pallet-balances = { path = "../balances", default-features = false } -sp-inherents = { path = "../../primitives/inherents", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -sp-transaction-storage-proof = { path = "../../primitives/transaction-storage-proof", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +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 } [dev-dependencies] -sp-core = { path = "../../primitives/core", default-features = false } -sp-transaction-storage-proof = { path = "../../primitives/transaction-storage-proof", default-features = true } +sp-core = { workspace = true } +sp-transaction-storage-proof = { default-features = true, workspace = true } [features] default = ["std"] diff --git a/substrate/frame/treasury/Cargo.toml b/substrate/frame/treasury/Cargo.toml index c93272af11d4664495cac40984f99fbc60b23f11..33e74b0a4aa282699e2a278ab6359b22df563c39 100644 --- a/substrate/frame/treasury/Cargo.toml +++ b/substrate/frame/treasury/Cargo.toml @@ -16,26 +16,26 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", "max-encoded-len", -] } -docify = "0.2.8" -impl-trait-for-tuples = "0.2.2" -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +], workspace = true } +docify = { workspace = true } +impl-trait-for-tuples = { workspace = true } +scale-info = { features = ["derive"], workspace = true } serde = { features = ["derive"], optional = true, workspace = true, default-features = true } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -pallet-balances = { path = "../balances", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false, optional = true } +frame-benchmarking = { optional = true, workspace = true } +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] -sp-io = { path = "../../primitives/io" } -pallet-utility = { path = "../utility" } -sp-core = { path = "../../primitives/core", default-features = false } +sp-io = { workspace = true, default-features = true } +pallet-utility = { workspace = true, default-features = true } +sp-core = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/treasury/README.md b/substrate/frame/treasury/README.md index 4945d79d1429694a1c8db79e8508561f515163da..2bd58a9817aab8efb47dc83752b817d6e11a59a2 100644 --- a/substrate/frame/treasury/README.md +++ b/substrate/frame/treasury/README.md @@ -26,6 +26,14 @@ and use the funds to pay developers. ### Dispatchable Functions General spending/proposal protocol: -- `propose_spend` - Make a spending proposal and stake the required deposit. -- `reject_proposal` - Reject a proposal, slashing the deposit. -- `approve_proposal` - Accept the proposal, returning the deposit. +- `spend_local` - Propose and approve a spend of treasury funds, enables the + creation of spends using the native currency of the chain, utilizing the funds + stored in the pot +- `spend` - Propose and approve a spend of treasury funds, allows spending any + asset kind managed by the treasury +- `remove_approval` - Force a previously approved proposal to be removed from + the approval queue +- `payout` - Claim a spend +- `check_status` - Check the status of the spend and remove it from the storage + if processed +- `void_spend` - Void previously approved spend diff --git a/substrate/frame/treasury/src/benchmarking.rs b/substrate/frame/treasury/src/benchmarking.rs index 0b9999e37fbea566e7ec74f61357104b9b5d6376..63978c94e682f8cca84146e69c4b2e17d06ae637 100644 --- a/substrate/frame/treasury/src/benchmarking.rs +++ b/substrate/frame/treasury/src/benchmarking.rs @@ -59,12 +59,12 @@ where const SEED: u32 = 0; -// Create the pre-requisite information needed to create a treasury `propose_spend`. +// Create the pre-requisite information needed to create a treasury `spend_local`. fn setup_proposal, I: 'static>( u: u32, ) -> (T::AccountId, BalanceOf, AccountIdLookupOf) { let caller = account("caller", u, SEED); - let value: BalanceOf = T::ProposalBondMinimum::get().saturating_mul(100u32.into()); + let value: BalanceOf = T::Currency::minimum_balance() * 100u32.into(); let _ = T::Currency::make_free_balance_be(&caller, value); let beneficiary = account("beneficiary", u, SEED); let beneficiary_lookup = T::Lookup::unlookup(beneficiary); @@ -73,12 +73,10 @@ fn setup_proposal, I: 'static>( // Create proposals that are approved for use in `on_initialize`. fn create_approved_proposals, I: 'static>(n: u32) -> Result<(), &'static str> { + let origin = T::SpendOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; for i in 0..n { - let (caller, value, lookup) = setup_proposal::(i); - #[allow(deprecated)] - Treasury::::propose_spend(RawOrigin::Signed(caller).into(), value, lookup)?; - let proposal_id = >::get() - 1; - Approvals::::try_append(proposal_id).unwrap(); + let (_, value, lookup) = setup_proposal::(i); + Treasury::::spend_local(origin.clone(), value, lookup)?; } ensure!(>::get().len() == n as usize, "Not all approved"); Ok(()) @@ -126,71 +124,13 @@ mod benchmarks { Ok(()) } - #[benchmark] - fn propose_spend() -> Result<(), BenchmarkError> { - let (caller, value, beneficiary_lookup) = setup_proposal::(SEED); - // Whitelist caller account from further DB operations. - let caller_key = frame_system::Account::::hashed_key_for(&caller); - frame_benchmarking::benchmarking::add_to_whitelist(caller_key.into()); - - #[extrinsic_call] - _(RawOrigin::Signed(caller), value, beneficiary_lookup); - - Ok(()) - } - - #[benchmark] - fn reject_proposal() -> Result<(), BenchmarkError> { - let (caller, value, beneficiary_lookup) = setup_proposal::(SEED); - #[allow(deprecated)] - Treasury::::propose_spend( - RawOrigin::Signed(caller).into(), - value, - beneficiary_lookup, - )?; - let proposal_id = Treasury::::proposal_count() - 1; - let reject_origin = - T::RejectOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - - #[extrinsic_call] - _(reject_origin as T::RuntimeOrigin, proposal_id); - - Ok(()) - } - - #[benchmark] - fn approve_proposal( - p: Linear<0, { T::MaxApprovals::get() - 1 }>, - ) -> Result<(), BenchmarkError> { - let approve_origin = - T::ApproveOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; - create_approved_proposals::(p)?; - let (caller, value, beneficiary_lookup) = setup_proposal::(SEED); - #[allow(deprecated)] - Treasury::::propose_spend( - RawOrigin::Signed(caller).into(), - value, - beneficiary_lookup, - )?; - let proposal_id = Treasury::::proposal_count() - 1; - - #[extrinsic_call] - _(approve_origin as T::RuntimeOrigin, proposal_id); - - Ok(()) - } - #[benchmark] fn remove_approval() -> Result<(), BenchmarkError> { - let (caller, value, beneficiary_lookup) = setup_proposal::(SEED); - #[allow(deprecated)] - Treasury::::propose_spend( - RawOrigin::Signed(caller).into(), - value, - beneficiary_lookup, - )?; + let origin = + T::SpendOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; + let (_, value, beneficiary_lookup) = setup_proposal::(SEED); + Treasury::::spend_local(origin, value, beneficiary_lookup)?; let proposal_id = Treasury::::proposal_count() - 1; - Approvals::::try_append(proposal_id).unwrap(); let reject_origin = T::RejectOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?; diff --git a/substrate/frame/treasury/src/lib.rs b/substrate/frame/treasury/src/lib.rs index 1ccd8456643233c71eb3095aa7c05980b9e52e25..b437e5ef137e3e72bf39c10223a94a67dc31b91c 100644 --- a/substrate/frame/treasury/src/lib.rs +++ b/substrate/frame/treasury/src/lib.rs @@ -205,9 +205,6 @@ pub mod pallet { /// The staking balance. type Currency: Currency + ReservableCurrency; - /// Origin from which approvals must come. - type ApproveOrigin: EnsureOrigin; - /// Origin from which rejections must come. type RejectOrigin: EnsureOrigin; @@ -215,22 +212,6 @@ pub mod pallet { type RuntimeEvent: From> + IsType<::RuntimeEvent>; - /// Handler for the unbalanced decrease when slashing for a rejected proposal or bounty. - type OnSlash: OnUnbalanced>; - - /// Fraction of a proposal's value that should be bonded in order to place the proposal. - /// An accepted proposal gets these back. A rejected proposal does not. - #[pallet::constant] - type ProposalBond: Get; - - /// Minimum amount of funds that should be placed in a deposit for making a proposal. - #[pallet::constant] - type ProposalBondMinimum: Get>; - - /// Maximum amount of funds that should be placed in a deposit for making a proposal. - #[pallet::constant] - type ProposalBondMaximum: Get>>; - /// Period between successive spends. #[pallet::constant] type SpendPeriod: Get>; @@ -363,14 +344,10 @@ pub mod pallet { #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event, I: 'static = ()> { - /// New proposal. - Proposed { proposal_index: ProposalIndex }, /// We have ended a spend period and will now allocate funds. Spending { budget_remaining: BalanceOf }, /// Some funds have been allocated. Awarded { proposal_index: ProposalIndex, award: BalanceOf, account: T::AccountId }, - /// A proposal was rejected; funds were slashed. - Rejected { proposal_index: ProposalIndex, slashed: BalanceOf }, /// Some of our funds have been burnt. Burnt { burnt_funds: BalanceOf }, /// Spending has finished; this is the amount that rolls over until next spend. @@ -408,8 +385,6 @@ pub mod pallet { /// Error for the treasury pallet. #[pallet::error] pub enum Error { - /// Proposer's balance is too low. - InsufficientProposersBalance, /// No proposal, bounty or spend at that index. InvalidIndex, /// Too many approvals in the queue. @@ -476,123 +451,6 @@ pub mod pallet { #[pallet::call] impl, I: 'static> Pallet { - /// Put forward a suggestion for spending. - /// - /// ## Dispatch Origin - /// - /// Must be signed. - /// - /// ## Details - /// A deposit proportional to the value is reserved and slashed if the proposal is rejected. - /// It is returned once the proposal is awarded. - /// - /// ### Complexity - /// - O(1) - /// - /// ## Events - /// - /// Emits [`Event::Proposed`] if successful. - #[pallet::call_index(0)] - #[pallet::weight(T::WeightInfo::propose_spend())] - #[allow(deprecated)] - #[deprecated( - note = "`propose_spend` will be removed in February 2024. Use `spend` instead." - )] - pub fn propose_spend( - origin: OriginFor, - #[pallet::compact] value: BalanceOf, - beneficiary: AccountIdLookupOf, - ) -> DispatchResult { - let proposer = ensure_signed(origin)?; - let beneficiary = T::Lookup::lookup(beneficiary)?; - - let bond = Self::calculate_bond(value); - T::Currency::reserve(&proposer, bond) - .map_err(|_| Error::::InsufficientProposersBalance)?; - - let c = Self::proposal_count(); - >::put(c + 1); - >::insert(c, Proposal { proposer, value, beneficiary, bond }); - - Self::deposit_event(Event::Proposed { proposal_index: c }); - Ok(()) - } - - /// Reject a proposed spend. - /// - /// ## Dispatch Origin - /// - /// Must be [`Config::RejectOrigin`]. - /// - /// ## Details - /// The original deposit will be slashed. - /// - /// ### Complexity - /// - O(1) - /// - /// ## Events - /// - /// Emits [`Event::Rejected`] if successful. - #[pallet::call_index(1)] - #[pallet::weight((T::WeightInfo::reject_proposal(), DispatchClass::Operational))] - #[allow(deprecated)] - #[deprecated( - note = "`reject_proposal` will be removed in February 2024. Use `spend` instead." - )] - pub fn reject_proposal( - origin: OriginFor, - #[pallet::compact] proposal_id: ProposalIndex, - ) -> DispatchResult { - T::RejectOrigin::ensure_origin(origin)?; - - let proposal = - >::take(&proposal_id).ok_or(Error::::InvalidIndex)?; - let value = proposal.bond; - let imbalance = T::Currency::slash_reserved(&proposal.proposer, value).0; - T::OnSlash::on_unbalanced(imbalance); - - Self::deposit_event(Event::::Rejected { - proposal_index: proposal_id, - slashed: value, - }); - Ok(()) - } - - /// Approve a proposal. - /// - /// ## Dispatch Origin - /// - /// Must be [`Config::ApproveOrigin`]. - /// - /// ## Details - /// - /// At a later time, the proposal will be allocated to the beneficiary and the original - /// deposit will be returned. - /// - /// ### Complexity - /// - O(1). - /// - /// ## Events - /// - /// No events are emitted from this dispatch. - #[pallet::call_index(2)] - #[pallet::weight((T::WeightInfo::approve_proposal(T::MaxApprovals::get()), DispatchClass::Operational))] - #[allow(deprecated)] - #[deprecated( - note = "`approve_proposal` will be removed in February 2024. Use `spend` instead." - )] - pub fn approve_proposal( - origin: OriginFor, - #[pallet::compact] proposal_id: ProposalIndex, - ) -> DispatchResult { - T::ApproveOrigin::ensure_origin(origin)?; - - ensure!(>::contains_key(proposal_id), Error::::InvalidIndex); - Approvals::::try_append(proposal_id) - .map_err(|_| Error::::TooManyApprovals)?; - Ok(()) - } - /// Propose and approve a spend of treasury funds. /// /// ## Dispatch Origin @@ -794,7 +652,7 @@ pub mod pallet { /// /// ## Dispatch Origin /// - /// Must be signed. + /// Must be signed /// /// ## Details /// @@ -934,15 +792,6 @@ impl, I: 'static> Pallet { T::PalletId::get().into_account_truncating() } - /// The needed bond for a proposal whose spend is `value`. - fn calculate_bond(value: BalanceOf) -> BalanceOf { - let mut r = T::ProposalBondMinimum::get().max(T::ProposalBond::get() * value); - if let Some(m) = T::ProposalBondMaximum::get() { - r = r.min(m); - } - r - } - /// Spend some money! returns number of approvals before spend. pub fn spend_funds() -> Weight { let mut total_weight = Weight::zero(); diff --git a/substrate/frame/treasury/src/tests.rs b/substrate/frame/treasury/src/tests.rs index 67d81cb5c30224e68a2b72bcda3255273304b14a..97b735928192b4fef3dd9ed8cb8f3e060ce333d7 100644 --- a/substrate/frame/treasury/src/tests.rs +++ b/substrate/frame/treasury/src/tests.rs @@ -60,20 +60,10 @@ impl frame_system::Config for Test { type Block = Block; type AccountData = pallet_balances::AccountData; } + +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type Balance = u64; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ConstU64<1>; type AccountStore = System; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } impl pallet_utility::Config for Test { @@ -136,7 +126,6 @@ impl Pay for TestPay { } parameter_types! { - pub const ProposalBond: Permill = Permill::from_percent(5); pub const Burn: Permill = Permill::from_percent(50); pub const TreasuryPalletId: PalletId = PalletId(*b"py/trsry"); pub TreasuryAccount: u128 = Treasury::account_id(); @@ -152,6 +141,7 @@ impl frame_support::traits::EnsureOrigin for TestSpendOrigin { frame_system::RawOrigin::Signed(11) => Ok(10), frame_system::RawOrigin::Signed(12) => Ok(20), frame_system::RawOrigin::Signed(13) => Ok(50), + frame_system::RawOrigin::Signed(14) => Ok(500), r => Err(RuntimeOrigin::from(r)), }) } @@ -174,13 +164,8 @@ impl> ConversionFromAssetBalance for MulBy { impl Config for Test { type PalletId = TreasuryPalletId; type Currency = pallet_balances::Pallet; - type ApproveOrigin = frame_system::EnsureRoot; type RejectOrigin = frame_system::EnsureRoot; type RuntimeEvent = RuntimeEvent; - type OnSlash = (); - type ProposalBond = ProposalBond; - type ProposalBondMinimum = ConstU64<1>; - type ProposalBondMaximum = (); type SpendPeriod = ConstU64<2>; type Burn = Burn; type BurnDestination = (); // Just gets burned. @@ -295,56 +280,12 @@ fn minting_works() { }); } -#[test] -fn spend_proposal_takes_min_deposit() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 1, 3) - }); - assert_eq!(Balances::free_balance(0), 99); - assert_eq!(Balances::reserved_balance(0), 1); - }); -} - -#[test] -fn spend_proposal_takes_proportional_deposit() { - ExtBuilder::default().build().execute_with(|| { - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_eq!(Balances::free_balance(0), 95); - assert_eq!(Balances::reserved_balance(0), 5); - }); -} - -#[test] -fn spend_proposal_fails_when_proposer_poor() { - ExtBuilder::default().build().execute_with(|| { - assert_noop!( - { - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(2), 100, 3) - }, - Error::::InsufficientProposersBalance, - ); - }); -} - #[test] fn accepted_spend_proposal_ignored_outside_spend_period() { ExtBuilder::default().build().execute_with(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 100, 3)); >::on_initialize(1); assert_eq!(Balances::free_balance(3), 0); @@ -365,112 +306,13 @@ fn unused_pot_should_diminish() { }); } -#[test] -fn rejected_spend_proposal_ignored_on_spend_period() { - ExtBuilder::default().build().execute_with(|| { - Balances::make_free_balance_be(&Treasury::account_id(), 101); - - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::reject_proposal(RuntimeOrigin::root(), 0) - }); - - >::on_initialize(2); - assert_eq!(Balances::free_balance(3), 0); - assert_eq!(Treasury::pot(), 50); - }); -} - -#[test] -fn reject_already_rejected_spend_proposal_fails() { - ExtBuilder::default().build().execute_with(|| { - Balances::make_free_balance_be(&Treasury::account_id(), 101); - - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::reject_proposal(RuntimeOrigin::root(), 0) - }); - assert_noop!( - { - #[allow(deprecated)] - Treasury::reject_proposal(RuntimeOrigin::root(), 0) - }, - Error::::InvalidIndex - ); - }); -} - -#[test] -fn reject_non_existent_spend_proposal_fails() { - ExtBuilder::default().build().execute_with(|| { - assert_noop!( - { - #[allow(deprecated)] - Treasury::reject_proposal(RuntimeOrigin::root(), 0) - }, - Error::::InvalidIndex - ); - }); -} - -#[test] -fn accept_non_existent_spend_proposal_fails() { - ExtBuilder::default().build().execute_with(|| { - assert_noop!( - { - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }, - Error::::InvalidIndex - ); - }); -} - -#[test] -fn accept_already_rejected_spend_proposal_fails() { - ExtBuilder::default().build().execute_with(|| { - Balances::make_free_balance_be(&Treasury::account_id(), 101); - - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::reject_proposal(RuntimeOrigin::root(), 0) - }); - assert_noop!( - { - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }, - Error::::InvalidIndex - ); - }); -} - #[test] fn accepted_spend_proposal_enacted_on_spend_period() { ExtBuilder::default().build().execute_with(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Treasury::pot(), 100); - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 100, 3)); >::on_initialize(2); assert_eq!(Balances::free_balance(3), 100); @@ -484,14 +326,7 @@ fn pot_underflow_should_not_diminish() { Balances::make_free_balance_be(&Treasury::account_id(), 101); assert_eq!(Treasury::pot(), 100); - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 150, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 150, 3)); >::on_initialize(2); assert_eq!(Treasury::pot(), 100); // Pot hasn't changed @@ -512,26 +347,12 @@ fn treasury_account_doesnt_get_deleted() { assert_eq!(Treasury::pot(), 100); let treasury_balance = Balances::free_balance(&Treasury::account_id()); - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), treasury_balance, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), treasury_balance, 3)); >::on_initialize(2); assert_eq!(Treasury::pot(), 100); // Pot hasn't changed - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), Treasury::pot(), 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 1) - }); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), Treasury::pot(), 3)); >::on_initialize(4); assert_eq!(Treasury::pot(), 0); // Pot is emptied @@ -554,22 +375,9 @@ fn inexistent_account_works() { assert_eq!(Balances::free_balance(Treasury::account_id()), 0); // Account does not exist assert_eq!(Treasury::pot(), 0); // Pot is empty - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 99, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 1, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 1) - }); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 99, 3)); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 1, 3)); + >::on_initialize(2); assert_eq!(Treasury::pot(), 0); // Pot hasn't changed assert_eq!(Balances::free_balance(3), 0); // Balance of `3` hasn't changed @@ -611,26 +419,12 @@ fn max_approvals_limited() { Balances::make_free_balance_be(&0, u64::MAX); for _ in 0..::MaxApprovals::get() { - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 100, 3)); } // One too many will fail - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); assert_noop!( - { - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }, + Treasury::spend_local(RuntimeOrigin::signed(14), 100, 3), Error::::TooManyApprovals ); }); @@ -641,14 +435,8 @@ fn remove_already_removed_approval_fails() { ExtBuilder::default().build().execute_with(|| { Balances::make_free_balance_be(&Treasury::account_id(), 101); - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 100, 3) - }); - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }); + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 100, 3)); + assert_eq!(Treasury::approvals(), vec![0]); assert_ok!(Treasury::remove_approval(RuntimeOrigin::root(), 0)); assert_eq!(Treasury::approvals(), vec![]); @@ -982,11 +770,9 @@ fn check_status_works() { fn try_state_proposals_invariant_1_works() { ExtBuilder::default().build().execute_with(|| { use frame_support::pallet_prelude::DispatchError::Other; - // Add a proposal using `propose_spend` - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 1, 3) - }); + // Add a proposal and approve using `spend_local` + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 1, 3)); + assert_eq!(Proposals::::iter().count(), 1); assert_eq!(ProposalCount::::get(), 1); // Check invariant 1 holds @@ -1005,12 +791,11 @@ fn try_state_proposals_invariant_1_works() { fn try_state_proposals_invariant_2_works() { ExtBuilder::default().build().execute_with(|| { use frame_support::pallet_prelude::DispatchError::Other; - // Add a proposal using `propose_spend` - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 1, 3) - }); + // Add a proposal and approve using `spend_local` + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 1, 3)); + assert_eq!(Proposals::::iter().count(), 1); + assert_eq!(Approvals::::get().len(), 1); let current_proposal_count = ProposalCount::::get(); assert_eq!(current_proposal_count, 1); // Check invariant 2 holds @@ -1035,17 +820,10 @@ fn try_state_proposals_invariant_2_works() { fn try_state_proposals_invariant_3_works() { ExtBuilder::default().build().execute_with(|| { use frame_support::pallet_prelude::DispatchError::Other; - // Add a proposal using `propose_spend` - assert_ok!({ - #[allow(deprecated)] - Treasury::propose_spend(RuntimeOrigin::signed(0), 10, 3) - }); + // Add a proposal and approve using `spend_local` + assert_ok!(Treasury::spend_local(RuntimeOrigin::signed(14), 10, 3)); + assert_eq!(Proposals::::iter().count(), 1); - // Approve the proposal - assert_ok!({ - #[allow(deprecated)] - Treasury::approve_proposal(RuntimeOrigin::root(), 0) - }); assert_eq!(Approvals::::get().len(), 1); // Check invariant 3 holds assert!(Approvals::::get() diff --git a/substrate/frame/treasury/src/weights.rs b/substrate/frame/treasury/src/weights.rs index 82277e2d28f6c80e2bfa040103bb4a311ca41ac1..8c9c6eb1d0fbb552bb210be6435e973078d64d30 100644 --- a/substrate/frame/treasury/src/weights.rs +++ b/substrate/frame/treasury/src/weights.rs @@ -52,9 +52,6 @@ use core::marker::PhantomData; /// Weight functions needed for `pallet_treasury`. pub trait WeightInfo { fn spend_local() -> Weight; - fn propose_spend() -> Weight; - fn reject_proposal() -> Weight; - fn approve_proposal(p: u32, ) -> Weight; fn remove_approval() -> Weight; fn on_initialize_proposals(p: u32, ) -> Weight; fn spend() -> Weight; @@ -81,50 +78,8 @@ impl WeightInfo for SubstrateWeight { .saturating_add(T::DbWeight::get().reads(2_u64)) .saturating_add(T::DbWeight::get().writes(3_u64)) } - /// Storage: `Treasury::ProposalCount` (r:1 w:1) - /// Proof: `Treasury::ProposalCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `Treasury::Proposals` (r:0 w:1) - /// Proof: `Treasury::Proposals` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - fn propose_spend() -> Weight { - // Proof Size summary in bytes: - // Measured: `177` - // Estimated: `1489` - // Minimum execution time: 24_704_000 picoseconds. - Weight::from_parts(25_484_000, 1489) - .saturating_add(T::DbWeight::get().reads(1_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) - } - /// Storage: `Treasury::Proposals` (r:1 w:1) - /// Proof: `Treasury::Proposals` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - fn reject_proposal() -> Weight { - // Proof Size summary in bytes: - // Measured: `335` - // Estimated: `3593` - // Minimum execution time: 26_632_000 picoseconds. - Weight::from_parts(27_325_000, 3593) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(2_u64)) - } - /// Storage: `Treasury::Proposals` (r:1 w:0) - /// Proof: `Treasury::Proposals` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `Treasury::Approvals` (r:1 w:1) - /// Proof: `Treasury::Approvals` (`max_values`: Some(1), `max_size`: Some(402), added: 897, mode: `MaxEncodedLen`) - /// The range of component `p` is `[0, 99]`. - fn approve_proposal(p: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `504 + p * (8 ยฑ0)` - // Estimated: `3573` - // Minimum execution time: 8_436_000 picoseconds. - Weight::from_parts(11_268_438, 3573) - // Standard Error: 1_039 - .saturating_add(Weight::from_parts(70_903, 0).saturating_mul(p.into())) - .saturating_add(T::DbWeight::get().reads(2_u64)) - .saturating_add(T::DbWeight::get().writes(1_u64)) - } - /// Storage: `Treasury::Approvals` (r:1 w:1) - /// Proof: `Treasury::Approvals` (`max_values`: Some(1), `max_size`: Some(402), added: 897, mode: `MaxEncodedLen`) + /// Storage: Treasury Approvals (r:1 w:1) + /// Proof: Treasury Approvals (max_values: Some(1), max_size: Some(402), added: 897, mode: MaxEncodedLen) fn remove_approval() -> Weight { // Proof Size summary in bytes: // Measured: `161` @@ -232,50 +187,8 @@ impl WeightInfo for () { .saturating_add(RocksDbWeight::get().reads(2_u64)) .saturating_add(RocksDbWeight::get().writes(3_u64)) } - /// Storage: `Treasury::ProposalCount` (r:1 w:1) - /// Proof: `Treasury::ProposalCount` (`max_values`: Some(1), `max_size`: Some(4), added: 499, mode: `MaxEncodedLen`) - /// Storage: `Treasury::Proposals` (r:0 w:1) - /// Proof: `Treasury::Proposals` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - fn propose_spend() -> Weight { - // Proof Size summary in bytes: - // Measured: `177` - // Estimated: `1489` - // Minimum execution time: 24_704_000 picoseconds. - Weight::from_parts(25_484_000, 1489) - .saturating_add(RocksDbWeight::get().reads(1_u64)) - .saturating_add(RocksDbWeight::get().writes(2_u64)) - } - /// Storage: `Treasury::Proposals` (r:1 w:1) - /// Proof: `Treasury::Proposals` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `System::Account` (r:1 w:1) - /// Proof: `System::Account` (`max_values`: None, `max_size`: Some(128), added: 2603, mode: `MaxEncodedLen`) - fn reject_proposal() -> Weight { - // Proof Size summary in bytes: - // Measured: `335` - // Estimated: `3593` - // Minimum execution time: 26_632_000 picoseconds. - Weight::from_parts(27_325_000, 3593) - .saturating_add(RocksDbWeight::get().reads(2_u64)) - .saturating_add(RocksDbWeight::get().writes(2_u64)) - } - /// Storage: `Treasury::Proposals` (r:1 w:0) - /// Proof: `Treasury::Proposals` (`max_values`: None, `max_size`: Some(108), added: 2583, mode: `MaxEncodedLen`) - /// Storage: `Treasury::Approvals` (r:1 w:1) - /// Proof: `Treasury::Approvals` (`max_values`: Some(1), `max_size`: Some(402), added: 897, mode: `MaxEncodedLen`) - /// The range of component `p` is `[0, 99]`. - fn approve_proposal(p: u32, ) -> Weight { - // Proof Size summary in bytes: - // Measured: `504 + p * (8 ยฑ0)` - // Estimated: `3573` - // Minimum execution time: 8_436_000 picoseconds. - Weight::from_parts(11_268_438, 3573) - // Standard Error: 1_039 - .saturating_add(Weight::from_parts(70_903, 0).saturating_mul(p.into())) - .saturating_add(RocksDbWeight::get().reads(2_u64)) - .saturating_add(RocksDbWeight::get().writes(1_u64)) - } - /// Storage: `Treasury::Approvals` (r:1 w:1) - /// Proof: `Treasury::Approvals` (`max_values`: Some(1), `max_size`: Some(402), added: 897, mode: `MaxEncodedLen`) + /// Storage: Treasury Approvals (r:1 w:1) + /// Proof: Treasury Approvals (max_values: Some(1), max_size: Some(402), added: 897, mode: MaxEncodedLen) fn remove_approval() -> Weight { // Proof Size summary in bytes: // Measured: `161` diff --git a/substrate/frame/try-runtime/Cargo.toml b/substrate/frame/try-runtime/Cargo.toml index e4e5f1940b25b67a97ef6026daa13a83cab791a4..16e815975b5440000a0bc0808205e2323865adaa 100644 --- a/substrate/frame/try-runtime/Cargo.toml +++ b/substrate/frame/try-runtime/Cargo.toml @@ -15,11 +15,11 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -frame-support = { path = "../support", default-features = false } -sp-api = { path = "../../primitives/api", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +codec = { features = ["derive"], workspace = true } +frame-support = { workspace = true } +sp-api = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/tx-pause/Cargo.toml b/substrate/frame/tx-pause/Cargo.toml index e44bb90dd7f8438673f7b5a23b1e7b1c15da03b5..fbb71513c6ae7e59595a8b06a39c62d5db2ebecf 100644 --- a/substrate/frame/tx-pause/Cargo.toml +++ b/substrate/frame/tx-pause/Cargo.toml @@ -15,24 +15,24 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -docify = "0.2.8" -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } -pallet-balances = { path = "../balances", default-features = false, optional = true } -pallet-utility = { path = "../utility", default-features = false, optional = true } -pallet-proxy = { path = "../proxy", default-features = false, optional = true } +codec = { features = ["derive"], workspace = true } +docify = { workspace = true } +frame-benchmarking = { optional = true, workspace = true } +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 } [dev-dependencies] -sp-core = { path = "../../primitives/core" } -sp-io = { path = "../../primitives/io" } -pallet-balances = { path = "../balances" } -pallet-utility = { path = "../utility" } -pallet-proxy = { path = "../proxy" } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +pallet-balances = { workspace = true, default-features = true } +pallet-utility = { workspace = true, default-features = true } +pallet-proxy = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/tx-pause/src/mock.rs b/substrate/frame/tx-pause/src/mock.rs index f42d4cb58a2ac77b843f7624723d414216cb26da..84ce45e835280dd9beeddacf84193ff858c3ea80 100644 --- a/substrate/frame/tx-pause/src/mock.rs +++ b/substrate/frame/tx-pause/src/mock.rs @@ -36,24 +36,9 @@ impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; } -parameter_types! { - pub const ExistentialDeposit: u64 = 1; - pub const MaxLocks: u32 = 10; -} +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type Balance = u64; - type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; - type ExistentialDeposit = ExistentialDeposit; type AccountStore = System; - type WeightInfo = (); - type MaxLocks = MaxLocks; - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type FreezeIdentifier = (); - type RuntimeHoldReason = RuntimeHoldReason; - type RuntimeFreezeReason = RuntimeFreezeReason; - type MaxFreezes = ConstU32<0>; } impl pallet_utility::Config for Test { diff --git a/substrate/frame/uniques/Cargo.toml b/substrate/frame/uniques/Cargo.toml index 65b727b40b254567d46bff7704b4f124b78820f0..d41d322bb63f1a9e72915549107f673a340c039d 100644 --- a/substrate/frame/uniques/Cargo.toml +++ b/substrate/frame/uniques/Cargo.toml @@ -16,20 +16,20 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } +codec = { workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +scale-info = { features = ["derive"], workspace = true } +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 = { path = "../balances" } -sp-core = { path = "../../primitives/core" } -sp-io = { path = "../../primitives/io" } -sp-std = { path = "../../primitives/std" } +pallet-balances = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-std = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/uniques/src/mock.rs b/substrate/frame/uniques/src/mock.rs index 9fd7f87e159bb29bb7206fcba05b573ccc140115..c3b74eb8c255417b7a6ed12f2d2ee771ec3d9f48 100644 --- a/substrate/frame/uniques/src/mock.rs +++ b/substrate/frame/uniques/src/mock.rs @@ -43,20 +43,9 @@ impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type Balance = u64; - type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; - type ExistentialDeposit = ConstU64<1>; type AccountStore = System; - type WeightInfo = (); - type MaxLocks = (); - type MaxReserves = ConstU32<50>; - type ReserveIdentifier = [u8; 8]; - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } impl Config for Test { diff --git a/substrate/frame/utility/Cargo.toml b/substrate/frame/utility/Cargo.toml index 00e8be75a3de600eada40f33afd4af94156dd554..0ccdac6be6236ef68f528f5c24f8904a7dba1670 100644 --- a/substrate/frame/utility/Cargo.toml +++ b/substrate/frame/utility/Cargo.toml @@ -16,22 +16,22 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +codec = { workspace = true } +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-core = { workspace = true } +sp-io = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -pallet-balances = { path = "../balances" } -pallet-root-testing = { path = "../root-testing" } -pallet-collective = { path = "../collective" } -pallet-timestamp = { path = "../timestamp" } -sp-core = { path = "../../primitives/core" } +pallet-balances = { workspace = true, default-features = true } +pallet-root-testing = { workspace = true, default-features = true } +pallet-collective = { workspace = true, default-features = true } +pallet-timestamp = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/utility/src/tests.rs b/substrate/frame/utility/src/tests.rs index 9bcbec99f3b441669eaf68433f0e88b3f5117502..eb2047aac28af40e9d8872c38ed21b89666e1c48 100644 --- a/substrate/frame/utility/src/tests.rs +++ b/substrate/frame/utility/src/tests.rs @@ -151,20 +151,9 @@ impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type Balance = u64; - type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; - type ExistentialDeposit = ConstU64<1>; type AccountStore = System; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } impl pallet_root_testing::Config for Test { diff --git a/substrate/frame/vesting/Cargo.toml b/substrate/frame/vesting/Cargo.toml index 7372b84240364aff99bf4ecbe35929b219f8b50e..3aca5683465cd39e6873cb123135312b8c3ca74b 100644 --- a/substrate/frame/vesting/Cargo.toml +++ b/substrate/frame/vesting/Cargo.toml @@ -16,21 +16,21 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", -] } +], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +scale-info = { features = ["derive"], workspace = true } +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 = { path = "../balances" } -sp-core = { path = "../../primitives/core" } -sp-io = { path = "../../primitives/io", default-features = false } +pallet-balances = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true } [features] default = ["std"] diff --git a/substrate/frame/vesting/src/mock.rs b/substrate/frame/vesting/src/mock.rs index 674a6f6e2a83677eae30fae445c05def44741e12..f0954a5b989c8a20d1fbb7feba9e49b20d61a27c 100644 --- a/substrate/frame/vesting/src/mock.rs +++ b/substrate/frame/vesting/src/mock.rs @@ -15,10 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use frame_support::{ - derive_impl, parameter_types, - traits::{ConstU32, WithdrawReasons}, -}; +use frame_support::{derive_impl, parameter_types, traits::WithdrawReasons}; use sp_runtime::{traits::Identity, BuildStorage}; use super::*; @@ -41,20 +38,10 @@ impl frame_system::Config for Test { type Block = Block; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { type AccountStore = System; - type Balance = u64; - type DustRemoval = (); - type RuntimeEvent = RuntimeEvent; type ExistentialDeposit = ExistentialDeposit; - type MaxLocks = ConstU32<10>; - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } parameter_types! { pub const MinVestedTransfer: u64 = 256 * 2; diff --git a/substrate/frame/whitelist/Cargo.toml b/substrate/frame/whitelist/Cargo.toml index 61bbb278019de8b4c012c460ab4d836cdf8a556d..922f9124d913a1b81c9142f9822635753eec728c 100644 --- a/substrate/frame/whitelist/Cargo.toml +++ b/substrate/frame/whitelist/Cargo.toml @@ -15,20 +15,20 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive", "max-encoded-len"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -frame-benchmarking = { path = "../benchmarking", default-features = false, optional = true } -frame-support = { path = "../support", default-features = false } -frame-system = { path = "../system", default-features = false } -sp-api = { path = "../../primitives/api", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false } -sp-std = { path = "../../primitives/std", default-features = false } +codec = { features = ["derive", "max-encoded-len"], workspace = true } +scale-info = { features = ["derive"], workspace = true } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } +sp-api = { workspace = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } [dev-dependencies] -pallet-balances = { path = "../balances" } -pallet-preimage = { path = "../preimage" } -sp-core = { path = "../../primitives/core" } -sp-io = { path = "../../primitives/io" } +pallet-balances = { workspace = true, default-features = true } +pallet-preimage = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/frame/whitelist/src/mock.rs b/substrate/frame/whitelist/src/mock.rs index 6fb8711057ef0cd53cc388e07cf90347c0e13000..0a97d1c2df5445223a4253cf0e1b81bd020806b0 100644 --- a/substrate/frame/whitelist/src/mock.rs +++ b/substrate/frame/whitelist/src/mock.rs @@ -21,7 +21,7 @@ use crate as pallet_whitelist; -use frame_support::{construct_runtime, derive_impl, traits::ConstU64}; +use frame_support::{construct_runtime, derive_impl}; use frame_system::EnsureRoot; use sp_runtime::BuildStorage; @@ -43,20 +43,9 @@ impl frame_system::Config for Test { type AccountData = pallet_balances::AccountData; } +#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)] impl pallet_balances::Config for Test { - type MaxLocks = (); - type MaxReserves = (); - type ReserveIdentifier = [u8; 8]; - type Balance = u64; - type RuntimeEvent = RuntimeEvent; - type DustRemoval = (); - type ExistentialDeposit = ConstU64<1>; type AccountStore = System; - type WeightInfo = (); - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); } impl pallet_preimage::Config for Test { diff --git a/substrate/kitchensink_runtime.wasm b/substrate/kitchensink_runtime.wasm new file mode 100644 index 0000000000000000000000000000000000000000..7ebb14371243afa4956a107374b27a4e686f0360 Binary files /dev/null and b/substrate/kitchensink_runtime.wasm differ diff --git a/substrate/primitives/api/Cargo.toml b/substrate/primitives/api/Cargo.toml index f48480f398d00729a5fb10e0c9bcfba5d62f9776..f8cbad8e31f02d38ee5a218d107968f634420a67 100644 --- a/substrate/primitives/api/Cargo.toml +++ b/substrate/primitives/api/Cargo.toml @@ -16,26 +16,27 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -sp-api-proc-macro = { path = "proc-macro", default-features = false } -sp-core = { path = "../core", default-features = false } -sp-std = { path = "../std", default-features = false } -sp-runtime = { path = "../runtime", default-features = false } -sp-runtime-interface = { path = "../runtime-interface", default-features = false } -sp-externalities = { path = "../externalities", default-features = false, optional = true } -sp-version = { path = "../version", default-features = false } -sp-state-machine = { path = "../state-machine", default-features = false, optional = true } -sp-trie = { path = "../trie", default-features = false, optional = true } -hash-db = { version = "0.16.0", optional = true } +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 } +sp-version = { workspace = true } +sp-state-machine = { optional = true, workspace = true } +sp-trie = { optional = true, workspace = true } +hash-db = { optional = true, workspace = true, default-features = true } thiserror = { optional = true, workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = [ +scale-info = { features = [ "derive", -] } -sp-metadata-ir = { path = "../metadata-ir", default-features = false, optional = true } +], workspace = true } +sp-metadata-ir = { optional = true, workspace = true } log = { workspace = true } +docify = { workspace = true } [dev-dependencies] -sp-test-primitives = { path = "../test-primitives" } +sp-test-primitives = { workspace = true } [features] default = ["std"] diff --git a/substrate/primitives/api/proc-macro/Cargo.toml b/substrate/primitives/api/proc-macro/Cargo.toml index b1bc547f3e4ae82e4e4331643c0aef14e1df3451..7d7fc19fcf5beb4274074a7aed49fa7e75147bd9 100644 --- a/substrate/primitives/api/proc-macro/Cargo.toml +++ b/substrate/primitives/api/proc-macro/Cargo.toml @@ -21,14 +21,14 @@ proc-macro = true [dependencies] quote = { workspace = true } syn = { features = ["extra-traits", "fold", "full", "visit"], workspace = true } -proc-macro2 = "1.0.56" -blake2 = { version = "0.10.4", default-features = false } -proc-macro-crate = "3.0.0" -expander = "2.0.0" -Inflector = "0.11.4" +proc-macro2 = { workspace = true } +blake2 = { workspace = true } +proc-macro-crate = { workspace = true } +expander = { workspace = true } +Inflector = { workspace = true } [dev-dependencies] -assert_matches = "1.3.0" +assert_matches = { workspace = true } [features] # Required for the doc tests diff --git a/substrate/primitives/api/src/lib.rs b/substrate/primitives/api/src/lib.rs index 20f989c4882e35fe06d5496f851b4adec2c6f1c0..cd8da8ba2374e142835967c8f304c62b1d0bf250 100644 --- a/substrate/primitives/api/src/lib.rs +++ b/substrate/primitives/api/src/lib.rs @@ -532,6 +532,7 @@ pub trait ConstructRuntimeApi> { fn construct_runtime_api(call: &C) -> ApiRef; } +#[docify::export] /// Init the [`RuntimeLogger`](sp_runtime::runtime_logger::RuntimeLogger). pub fn init_runtime_logger() { #[cfg(not(feature = "disable-logging"))] diff --git a/substrate/primitives/api/test/Cargo.toml b/substrate/primitives/api/test/Cargo.toml index b49f774161fd3f593872452a54e4f186a6743f6c..6c159fc63d0d3b86bbf59cbd43b9897d61c74d8a 100644 --- a/substrate/primitives/api/test/Cargo.toml +++ b/substrate/primitives/api/test/Cargo.toml @@ -15,25 +15,25 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-api = { path = ".." } -substrate-test-runtime-client = { path = "../../../test-utils/runtime/client" } -sp-version = { path = "../../version" } -sp-tracing = { path = "../../tracing" } -sp-runtime = { path = "../../runtime" } -sp-consensus = { path = "../../consensus/common" } -sc-block-builder = { path = "../../../client/block-builder" } -codec = { package = "parity-scale-codec", version = "3.6.12" } -sp-state-machine = { path = "../../state-machine" } -trybuild = "1.0.88" -rustversion = "1.0.6" -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +sp-api = { workspace = true, default-features = true } +substrate-test-runtime-client = { workspace = true } +sp-version = { workspace = true, default-features = true } +sp-tracing = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sc-block-builder = { workspace = true, default-features = true } +codec = { workspace = true, default-features = true } +sp-state-machine = { workspace = true, default-features = true } +trybuild = { workspace = true } +rustversion = { workspace = true } +scale-info = { features = ["derive"], workspace = true } [dev-dependencies] -criterion = "0.5.1" -futures = "0.3.30" +criterion = { workspace = true, default-features = true } +futures = { workspace = true } log = { workspace = true, default-features = true } -sp-core = { path = "../../core" } -static_assertions = "1.1.0" +sp-core = { workspace = true, default-features = true } +static_assertions = { workspace = true, default-features = true } [[bench]] name = "bench" diff --git a/substrate/primitives/application-crypto/Cargo.toml b/substrate/primitives/application-crypto/Cargo.toml index cbb9f2133577b93234c052dba329ed1d5f453be7..fbf9def20fce7468ced3036c107cbbaac9e2593b 100644 --- a/substrate/primitives/application-crypto/Cargo.toml +++ b/substrate/primitives/application-crypto/Cargo.toml @@ -18,12 +18,12 @@ targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-core = { path = "../core", default-features = false } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +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 = { path = "../std", default-features = false } -sp-io = { path = "../io", default-features = false } +sp-std = { workspace = true } +sp-io = { workspace = true } [features] default = ["std"] diff --git a/substrate/primitives/application-crypto/test/Cargo.toml b/substrate/primitives/application-crypto/test/Cargo.toml index 0057606b38e57112e2988d96dbaa342059616ee0..43f9d3852005a87f06b451cc30177f504d0d1366 100644 --- a/substrate/primitives/application-crypto/test/Cargo.toml +++ b/substrate/primitives/application-crypto/test/Cargo.toml @@ -16,8 +16,8 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-api = { path = "../../api" } -sp-application-crypto = { path = ".." } -sp-core = { path = "../../core", default-features = false } -sp-keystore = { path = "../../keystore", default-features = false } -substrate-test-runtime-client = { path = "../../../test-utils/runtime/client" } +sp-api = { workspace = true, default-features = true } +sp-application-crypto = { workspace = true, default-features = true } +sp-core = { workspace = true } +sp-keystore = { workspace = true } +substrate-test-runtime-client = { workspace = true } diff --git a/substrate/primitives/arithmetic/Cargo.toml b/substrate/primitives/arithmetic/Cargo.toml index a9f2b80156f5ec121eea75abb389e02bbf99884e..a0d80fc9b504984121c990d9053d67383ad9c57b 100644 --- a/substrate/primitives/arithmetic/Cargo.toml +++ b/substrate/primitives/arithmetic/Cargo.toml @@ -17,23 +17,23 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", "max-encoded-len", -] } -integer-sqrt = "0.1.2" -num-traits = { version = "0.2.17", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +], workspace = true } +integer-sqrt = { workspace = true } +num-traits = { workspace = true } +scale-info = { features = ["derive"], workspace = true } serde = { features = ["alloc", "derive"], optional = true, workspace = true } -static_assertions = "1.1.0" -sp-std = { path = "../std", default-features = false } -docify = "0.2.8" +static_assertions = { workspace = true, default-features = true } +sp-std = { workspace = true } +docify = { workspace = true } [dev-dependencies] -criterion = "0.5.1" -primitive-types = "0.12.0" -sp-crypto-hashing = { path = "../crypto/hashing" } -rand = "0.8.5" +criterion = { workspace = true, default-features = true } +primitive-types = { workspace = true, default-features = true } +sp-crypto-hashing = { workspace = true, default-features = true } +rand = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/primitives/arithmetic/fuzzer/Cargo.toml b/substrate/primitives/arithmetic/fuzzer/Cargo.toml index ace30e9c90e91d6b4c784cf090329b91e8095fad..c978393af34c42876024dc2e429e7b7b846008a8 100644 --- a/substrate/primitives/arithmetic/fuzzer/Cargo.toml +++ b/substrate/primitives/arithmetic/fuzzer/Cargo.toml @@ -17,11 +17,11 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -arbitrary = "1.3.2" -fraction = "0.13.1" -honggfuzz = "0.5.49" -num-bigint = "0.4.3" -sp-arithmetic = { path = ".." } +arbitrary = { workspace = true } +fraction = { workspace = true } +honggfuzz = { workspace = true } +num-bigint = { workspace = true } +sp-arithmetic = { workspace = true, default-features = true } [[bin]] name = "biguint" diff --git a/substrate/primitives/authority-discovery/Cargo.toml b/substrate/primitives/authority-discovery/Cargo.toml index 72a8bb7fc47d0f76a49de45a3828424eb7a0a240..26e08b8504c31d89b5ccbec33330a8877562f40d 100644 --- a/substrate/primitives/authority-discovery/Cargo.toml +++ b/substrate/primitives/authority-discovery/Cargo.toml @@ -16,11 +16,11 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -sp-api = { path = "../api", default-features = false } -sp-application-crypto = { path = "../application-crypto", default-features = false } -sp-runtime = { path = "../runtime", default-features = false } +codec = { workspace = true } +scale-info = { features = ["derive"], workspace = true } +sp-api = { workspace = true } +sp-application-crypto = { workspace = true } +sp-runtime = { workspace = true } [features] default = ["std"] diff --git a/substrate/primitives/block-builder/Cargo.toml b/substrate/primitives/block-builder/Cargo.toml index cc4b10851544d601ef9caea512280d49b77cd443..ddc0c00a3be8a19e11016db81da1d22372350dad 100644 --- a/substrate/primitives/block-builder/Cargo.toml +++ b/substrate/primitives/block-builder/Cargo.toml @@ -16,9 +16,9 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-api = { path = "../api", default-features = false } -sp-inherents = { path = "../inherents", default-features = false } -sp-runtime = { path = "../runtime", default-features = false } +sp-api = { workspace = true } +sp-inherents = { workspace = true } +sp-runtime = { workspace = true } [features] default = ["std"] diff --git a/substrate/primitives/blockchain/Cargo.toml b/substrate/primitives/blockchain/Cargo.toml index 5e51a2d06ed7a8f1de6fda7b2b19bf49fa515e51..67126d4d19ebdb267ad1da7cd1eb59a41fca347c 100644 --- a/substrate/primitives/blockchain/Cargo.toml +++ b/substrate/primitives/blockchain/Cargo.toml @@ -17,14 +17,14 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -futures = "0.3.30" +codec = { features = ["derive"], workspace = true } +futures = { workspace = true } log = { workspace = true, default-features = true } -parking_lot = "0.12.1" -schnellru = "0.2.1" +parking_lot = { workspace = true, default-features = true } +schnellru = { workspace = true } thiserror = { workspace = true } -sp-api = { path = "../api" } -sp-consensus = { path = "../consensus/common" } -sp-database = { path = "../database" } -sp-runtime = { path = "../runtime" } -sp-state-machine = { path = "../state-machine" } +sp-api = { workspace = true, default-features = true } +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 } diff --git a/substrate/primitives/blockchain/src/backend.rs b/substrate/primitives/blockchain/src/backend.rs index 06e5b682964a4e7672575c9e8b5460d7acb2de96..76393420da740b269a3790f7e69ed12ddf77b21a 100644 --- a/substrate/primitives/blockchain/src/backend.rs +++ b/substrate/primitives/blockchain/src/backend.rs @@ -21,16 +21,15 @@ use log::warn; use parking_lot::RwLock; use sp_runtime::{ generic::BlockId, - traits::{Block as BlockT, Header as HeaderT, NumberFor, Zero}, + traits::{Block as BlockT, CheckedSub, Header as HeaderT, NumberFor, Zero}, Justifications, }; use std::collections::{btree_map::BTreeMap, btree_set::BTreeSet}; -use crate::header_metadata::HeaderMetadata; - use crate::{ error::{Error, Result}, - tree_route, TreeRoute, + header_metadata::{self, HeaderMetadata}, + lowest_common_ancestor_multiblock, tree_route, TreeRoute, }; /// Blockchain database header backend. Does not perform any validation. @@ -229,12 +228,41 @@ pub trait Backend: ) -> std::result::Result, Error> { let mut result = DisplacedLeavesAfterFinalization::default(); - if finalized_block_number == Zero::zero() { + let leaves = self.leaves()?; + + // 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(result) } + let first_leaf = leaves.first().ok_or(Error::Backend( + "Unable to find any leaves. This should not happen.".to_string(), + ))?; + let leaf_block_header = self.expect_header(*first_leaf)?; + + // If the distance between the leafs and the finalized block is large, calculating + // tree routes can be very expensive. In that case, we will try to find the + // lowest common ancestor between all the leaves. The assumption here is that the forks are + // close to the tip and not long. So the LCA can be computed from the header cache. If the + // LCA is above the finalized block, we know that there are no displaced leaves by the + // finalization. + if leaf_block_header + .number() + .checked_sub(&finalized_block_number) + .unwrap_or(0u32.into()) > + header_metadata::LRU_CACHE_SIZE.into() + { + if let Some(lca) = lowest_common_ancestor_multiblock(self, leaves.clone())? { + if lca.number > finalized_block_number { + return Ok(result) + } else { + log::warn!("The distance between leafs and finalized block is large. Finalization can take a long time."); + } + }; + } + // For each leaf determine whether it belongs to a non-canonical branch. - for leaf_hash in self.leaves()? { + for leaf_hash in leaves { let leaf_block_header = self.expect_header(leaf_hash)?; let leaf_number = *leaf_block_header.number(); @@ -284,7 +312,7 @@ impl DisplacedLeavesAfterFinalization { } /// Blockchain info -#[derive(Debug, Eq, PartialEq)] +#[derive(Debug, Eq, PartialEq, Clone)] pub struct Info { /// Best block hash. pub best_hash: Block::Hash, diff --git a/substrate/primitives/blockchain/src/header_metadata.rs b/substrate/primitives/blockchain/src/header_metadata.rs index 27caaae71add1a440b8a772db131329c951befbc..c2054445b06765ad42b4d5a0718997fc9686cc14 100644 --- a/substrate/primitives/blockchain/src/header_metadata.rs +++ b/substrate/primitives/blockchain/src/header_metadata.rs @@ -23,7 +23,7 @@ use schnellru::{ByLength, LruMap}; use sp_runtime::traits::{Block as BlockT, Header, NumberFor, One}; /// Set to the expected max difference between `best` and `finalized` blocks at sync. -const LRU_CACHE_SIZE: u32 = 5_000; +pub(crate) const LRU_CACHE_SIZE: u32 = 5_000; /// Get lowest common ancestor between two blocks in the tree. /// @@ -96,6 +96,30 @@ pub fn lowest_common_ancestor + ?Sized>( Ok(HashAndNumber { hash: header_one.hash, number: header_one.number }) } +/// Get lowest common ancestor between multiple blocks. +pub fn lowest_common_ancestor_multiblock + ?Sized>( + backend: &T, + hashes: Vec, +) -> Result>, T::Error> { + // Ensure the list of hashes is not empty + let mut hashes_iter = hashes.into_iter(); + + let first_hash = match hashes_iter.next() { + Some(hash) => hash, + None => return Ok(None), + }; + + // Start with the first hash as the initial LCA + let first_cached = backend.header_metadata(first_hash)?; + let mut lca = HashAndNumber { number: first_cached.number, hash: first_cached.hash }; + for hash in hashes_iter { + // Calculate the LCA of the current LCA and the next hash + lca = lowest_common_ancestor(backend, lca.hash, hash)?; + } + + Ok(Some(lca)) +} + /// Compute a tree-route between two blocks. See tree-route docs for more details. pub fn tree_route + ?Sized>( backend: &T, diff --git a/substrate/primitives/consensus/aura/Cargo.toml b/substrate/primitives/consensus/aura/Cargo.toml index a54499178171dab260e953dd1082d512d48f6df0..3ae45062cb6814405d4398766fd636fc3c1b68ba 100644 --- a/substrate/primitives/consensus/aura/Cargo.toml +++ b/substrate/primitives/consensus/aura/Cargo.toml @@ -16,15 +16,15 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -async-trait = { version = "0.1.79", optional = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -sp-api = { path = "../../api", default-features = false } -sp-application-crypto = { path = "../../application-crypto", default-features = false } -sp-consensus-slots = { path = "../slots", default-features = false } -sp-inherents = { path = "../../inherents", default-features = false } -sp-runtime = { path = "../../runtime", default-features = false } -sp-timestamp = { path = "../../timestamp", default-features = false } +async-trait = { optional = true, workspace = true } +codec = { workspace = true } +scale-info = { features = ["derive"], workspace = true } +sp-api = { workspace = true } +sp-application-crypto = { workspace = true } +sp-consensus-slots = { workspace = true } +sp-inherents = { workspace = true } +sp-runtime = { workspace = true } +sp-timestamp = { workspace = true } [features] default = ["std"] diff --git a/substrate/primitives/consensus/babe/Cargo.toml b/substrate/primitives/consensus/babe/Cargo.toml index 46c032ba61a6067bd7cfa9f786706701c7e429c3..884fc6c25c97da6b04be5046d7b693b09be49c13 100644 --- a/substrate/primitives/consensus/babe/Cargo.toml +++ b/substrate/primitives/consensus/babe/Cargo.toml @@ -16,17 +16,17 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -async-trait = { version = "0.1.79", optional = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +async-trait = { optional = true, workspace = true } +codec = { workspace = true } +scale-info = { features = ["derive"], workspace = true } serde = { features = ["alloc", "derive"], optional = true, workspace = true } -sp-api = { path = "../../api", default-features = false } -sp-application-crypto = { path = "../../application-crypto", default-features = false } -sp-consensus-slots = { path = "../slots", default-features = false } -sp-core = { path = "../../core", default-features = false } -sp-inherents = { path = "../../inherents", default-features = false } -sp-runtime = { path = "../../runtime", default-features = false } -sp-timestamp = { path = "../../timestamp", optional = true, default-features = false } +sp-api = { workspace = true } +sp-application-crypto = { workspace = true } +sp-consensus-slots = { workspace = true } +sp-core = { workspace = true } +sp-inherents = { workspace = true } +sp-runtime = { workspace = true } +sp-timestamp = { optional = true, workspace = true } [features] default = ["std"] diff --git a/substrate/primitives/consensus/beefy/Cargo.toml b/substrate/primitives/consensus/beefy/Cargo.toml index a682939a02f95064f8fed2fe7f6be0a9ad228ede..49d907506049aa4ac4067e3e05cbcd5542495b53 100644 --- a/substrate/primitives/consensus/beefy/Cargo.toml +++ b/substrate/primitives/consensus/beefy/Cargo.toml @@ -15,23 +15,23 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } serde = { optional = true, features = ["alloc", "derive"], workspace = true } -sp-api = { path = "../../api", default-features = false } -sp-application-crypto = { path = "../../application-crypto", default-features = false } -sp-core = { path = "../../core", default-features = false } -sp-crypto-hashing = { path = "../../crypto/hashing", default-features = false } -sp-io = { path = "../../io", default-features = false } -sp-mmr-primitives = { path = "../../merkle-mountain-range", default-features = false } -sp-runtime = { path = "../../runtime", default-features = false } -sp-keystore = { path = "../../keystore", default-features = false } -strum = { version = "0.26.2", features = ["derive"], default-features = false } -lazy_static = { version = "1.4.0", optional = true } +sp-api = { workspace = true } +sp-application-crypto = { workspace = true } +sp-core = { workspace = true } +sp-crypto-hashing = { workspace = true } +sp-io = { workspace = true } +sp-mmr-primitives = { workspace = true } +sp-runtime = { workspace = true } +sp-keystore = { workspace = true } +strum = { features = ["derive"], workspace = true } +lazy_static = { optional = true, workspace = true } [dev-dependencies] -array-bytes = "6.2.2" -w3f-bls = { version = "0.1.3", features = ["std"] } +array-bytes = { workspace = true, default-features = true } +w3f-bls = { features = ["std"], workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/primitives/consensus/common/Cargo.toml b/substrate/primitives/consensus/common/Cargo.toml index 90aeadd5055e6e17107b70070ca30e17dd6b1c7c..a5d9a8da1a9bef6ac1faed5c61c6e12720570f59 100644 --- a/substrate/primitives/consensus/common/Cargo.toml +++ b/substrate/primitives/consensus/common/Cargo.toml @@ -17,18 +17,18 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -async-trait = "0.1.79" -futures = { version = "0.3.30", features = ["thread-pool"] } +async-trait = { workspace = true } +futures = { features = ["thread-pool"], workspace = true } log = { workspace = true, default-features = true } thiserror = { workspace = true } -sp-core = { path = "../../core" } -sp-inherents = { path = "../../inherents" } -sp-runtime = { path = "../../runtime" } -sp-state-machine = { path = "../../state-machine" } +sp-core = { 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 } [dev-dependencies] -futures = "0.3.30" -sp-test-primitives = { path = "../../test-primitives" } +futures = { workspace = true } +sp-test-primitives = { workspace = true } [features] default = [] diff --git a/substrate/primitives/consensus/common/src/lib.rs b/substrate/primitives/consensus/common/src/lib.rs index 01d3b7a24f9c143201f07092c7484e72f513d8f0..37636b34b03df6221865eada59abbb11cb92519a 100644 --- a/substrate/primitives/consensus/common/src/lib.rs +++ b/substrate/primitives/consensus/common/src/lib.rs @@ -40,7 +40,7 @@ pub use sp_inherents::InherentData; pub use sp_state_machine::Backend as StateBackend; /// Block status. -#[derive(Debug, PartialEq, Eq)] +#[derive(Debug, PartialEq, Eq, Clone)] pub enum BlockStatus { /// Added to the import queue. Queued, diff --git a/substrate/primitives/consensus/grandpa/Cargo.toml b/substrate/primitives/consensus/grandpa/Cargo.toml index 9a59575a22c3908c53665522233ac1d7e688a0ed..6ba5bb40595a0d626e34f6a20189d9572f43af25 100644 --- a/substrate/primitives/consensus/grandpa/Cargo.toml +++ b/substrate/primitives/consensus/grandpa/Cargo.toml @@ -17,16 +17,16 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -finality-grandpa = { version = "0.16.2", default-features = false, features = ["derive-codec"] } +codec = { features = ["derive"], workspace = true } +finality-grandpa = { features = ["derive-codec"], workspace = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +scale-info = { features = ["derive"], workspace = true } serde = { features = ["alloc", "derive"], optional = true, workspace = true } -sp-api = { path = "../../api", default-features = false } -sp-application-crypto = { path = "../../application-crypto", default-features = false } -sp-core = { path = "../../core", default-features = false } -sp-keystore = { path = "../../keystore", default-features = false, optional = true } -sp-runtime = { path = "../../runtime", default-features = false } +sp-api = { workspace = true } +sp-application-crypto = { workspace = true } +sp-core = { workspace = true } +sp-keystore = { optional = true, workspace = true } +sp-runtime = { workspace = true } [features] default = ["std"] diff --git a/substrate/primitives/consensus/pow/Cargo.toml b/substrate/primitives/consensus/pow/Cargo.toml index 0700e2c4f8b9f1595ca820ab0cc3fe5e963dec91..d4563cf8e6afdbb05556c17ab1235b0fa7caadba 100644 --- a/substrate/primitives/consensus/pow/Cargo.toml +++ b/substrate/primitives/consensus/pow/Cargo.toml @@ -16,10 +16,10 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -sp-api = { path = "../../api", default-features = false } -sp-core = { path = "../../core", default-features = false } -sp-runtime = { path = "../../runtime", default-features = false } +codec = { features = ["derive"], workspace = true } +sp-api = { workspace = true } +sp-core = { workspace = true } +sp-runtime = { workspace = true } [features] default = ["std"] diff --git a/substrate/primitives/consensus/sassafras/Cargo.toml b/substrate/primitives/consensus/sassafras/Cargo.toml index 792755730839226e2d200cdabccaa6f8bed0dda5..12bcbc1b33928dce6c08091cef8e9e0fff862d89 100644 --- a/substrate/primitives/consensus/sassafras/Cargo.toml +++ b/substrate/primitives/consensus/sassafras/Cargo.toml @@ -18,14 +18,14 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { workspace = true } +scale-info = { features = ["derive"], workspace = true } serde = { features = ["derive"], optional = true, workspace = true } -sp-api = { path = "../../api", default-features = false } -sp-application-crypto = { path = "../../application-crypto", default-features = false, features = ["bandersnatch-experimental"] } -sp-consensus-slots = { path = "../slots", default-features = false } -sp-core = { path = "../../core", default-features = false, features = ["bandersnatch-experimental"] } -sp-runtime = { path = "../../runtime", default-features = false } +sp-api = { workspace = true } +sp-application-crypto = { features = ["bandersnatch-experimental"], workspace = true } +sp-consensus-slots = { workspace = true } +sp-core = { features = ["bandersnatch-experimental"], workspace = true } +sp-runtime = { workspace = true } [features] default = ["std"] diff --git a/substrate/primitives/consensus/slots/Cargo.toml b/substrate/primitives/consensus/slots/Cargo.toml index dd519eab46475fb16f4768de2fab6138c5a059b4..9d881c3acd0045185584b05c06531345fcb911e5 100644 --- a/substrate/primitives/consensus/slots/Cargo.toml +++ b/substrate/primitives/consensus/slots/Cargo.toml @@ -16,10 +16,10 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive", "max-encoded-len"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive", "max-encoded-len"], workspace = true } +scale-info = { features = ["derive"], workspace = true } serde = { features = ["alloc", "derive"], optional = true, workspace = true } -sp-timestamp = { path = "../../timestamp", default-features = false } +sp-timestamp = { workspace = true } [features] default = ["std"] diff --git a/substrate/primitives/core/Cargo.toml b/substrate/primitives/core/Cargo.toml index f931faf8bd043406d2d30943a594d94ad745ae05..2ba4f959a5f9e7a14f9fdd2adf04b05d4b6b16b9 100644 --- a/substrate/primitives/core/Cargo.toml +++ b/substrate/primitives/core/Cargo.toml @@ -16,60 +16,60 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive", "max-encoded-len"] } -scale-info = { version = "2.5.0", default-features = false, features = ["derive"] } +codec = { features = ["derive", "max-encoded-len"], workspace = true } +scale-info = { features = ["derive"], workspace = true } log = { workspace = true } serde = { optional = true, features = ["alloc", "derive"], workspace = true } -bounded-collections = { version = "0.2.0", default-features = false } -primitive-types = { version = "0.12.0", default-features = false, features = ["codec", "scale-info"] } -impl-serde = { version = "0.4.0", default-features = false, optional = true } -hash-db = { version = "0.16.0", default-features = false } -hash256-std-hasher = { version = "0.15.2", default-features = false } -bs58 = { version = "0.5.0", default-features = false, optional = true } -rand = { version = "0.8.5", features = ["small_rng"], optional = true } -substrate-bip39 = { path = "../../utils/substrate-bip39", default-features = false } +bounded-collections = { workspace = true } +primitive-types = { features = ["codec", "scale-info"], workspace = true } +impl-serde = { optional = true, workspace = true } +hash-db = { workspace = true } +hash256-std-hasher = { workspace = true } +bs58 = { optional = true, workspace = true } +rand = { features = ["small_rng"], optional = true, workspace = true, default-features = true } +substrate-bip39 = { workspace = true } # personal fork here as workaround for: https://github.com/rust-bitcoin/rust-bip39/pull/64 bip39 = { package = "parity-bip39", version = "2.0.1", default-features = false, features = ["alloc"] } -zeroize = { version = "1.4.3", default-features = false } -secrecy = { version = "0.8.0", default-features = false, features = ["alloc"] } -parking_lot = { version = "0.12.1", optional = true } -ss58-registry = { version = "1.34.0", default-features = false } -sp-std = { path = "../std", default-features = false } -sp-debug-derive = { path = "../debug-derive", default-features = false } -sp-storage = { path = "../storage", default-features = false } -sp-externalities = { path = "../externalities", optional = true, default-features = false } -futures = { version = "0.3.30", optional = true } -dyn-clonable = { version = "0.9.0", optional = true } +zeroize = { workspace = true } +secrecy = { features = ["alloc"], workspace = true } +parking_lot = { optional = true, workspace = true, default-features = true } +ss58-registry = { workspace = true } +sp-std = { workspace = true } +sp-debug-derive = { workspace = true } +sp-storage = { workspace = true } +sp-externalities = { optional = true, workspace = true } +futures = { optional = true, workspace = true } +dyn-clonable = { optional = true, workspace = true } thiserror = { optional = true, workspace = true } -tracing = { version = "0.1.29", optional = true } -bitflags = "1.3" -paste = "1.0.7" -itertools = { version = "0.11", optional = true } +tracing = { optional = true, workspace = true, default-features = true } +bitflags = { workspace = true } +paste = { workspace = true, default-features = true } +itertools = { optional = true, workspace = true } # full crypto -array-bytes = { version = "6.2.2" } -ed25519-zebra = { version = "4.0.3", default-features = false } -blake2 = { version = "0.10.4", default-features = false, optional = true } -libsecp256k1 = { version = "0.7", default-features = false, features = ["static-context"] } -schnorrkel = { version = "0.11.4", features = ["preaudit_deprecated"], default-features = false } -merlin = { version = "3.0", default-features = false } -sp-crypto-hashing = { path = "../crypto/hashing", default-features = false } -sp-runtime-interface = { path = "../runtime-interface", default-features = false } +array-bytes = { workspace = true, default-features = true } +ed25519-zebra = { workspace = true } +blake2 = { optional = true, workspace = true } +libsecp256k1 = { features = ["static-context"], workspace = true } +schnorrkel = { features = ["preaudit_deprecated"], workspace = true } +merlin = { workspace = true } +sp-crypto-hashing = { workspace = true } +sp-runtime-interface = { workspace = true } # k256 crate, better portability, intended to be used in substrate-runtimes (no-std) -k256 = { version = "0.13.3", features = ["alloc", "ecdsa"], default-features = false } +k256 = { features = ["alloc", "ecdsa"], workspace = true } # secp256k1 crate, better performance, intended to be used on host side (std) -secp256k1 = { version = "0.28.0", default-features = false, features = ["alloc", "recovery"], optional = true } +secp256k1 = { features = ["alloc", "recovery"], optional = true, workspace = true } # bls crypto -w3f-bls = { version = "0.1.3", default-features = false, optional = true } +w3f-bls = { optional = true, workspace = true } # bandersnatch crypto bandersnatch_vrfs = { git = "https://github.com/w3f/ring-vrf", rev = "e9782f9", default-features = false, features = ["substrate-curves"], optional = true } [dev-dependencies] -criterion = "0.5.1" +criterion = { workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } -lazy_static = "1.4.0" -regex = "1.6.0" +lazy_static = { workspace = true } +regex = { workspace = true } [[bench]] name = "bench" diff --git a/substrate/primitives/core/fuzz/Cargo.toml b/substrate/primitives/core/fuzz/Cargo.toml index 463eaea8ea30d827c6f39b7cc02e8947a085c88b..46dfe8d483b7468b06d3dccb5494e6c6ec8cefe0 100644 --- a/substrate/primitives/core/fuzz/Cargo.toml +++ b/substrate/primitives/core/fuzz/Cargo.toml @@ -11,11 +11,11 @@ workspace = true cargo-fuzz = true [dependencies] -lazy_static = "1.4.0" -libfuzzer-sys = "0.4" -regex = "1.10.2" +lazy_static = { workspace = true } +libfuzzer-sys = { workspace = true } +regex = { workspace = true } -sp-core = { path = ".." } +sp-core = { workspace = true, default-features = true } [[bin]] name = "fuzz_address_uri" diff --git a/substrate/primitives/crypto/ec-utils/Cargo.toml b/substrate/primitives/crypto/ec-utils/Cargo.toml index 142a5abf9b30d660077d39c12808a26d47bd41b6..1068787728babd906c0aaa0ff9d83c559f8d4f6d 100644 --- a/substrate/primitives/crypto/ec-utils/Cargo.toml +++ b/substrate/primitives/crypto/ec-utils/Cargo.toml @@ -15,19 +15,19 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -ark-ec = { version = "0.4.2", default-features = false, optional = true } -ark-bls12-377-ext = { version = "0.4.1", default-features = false, optional = true } -ark-bls12-377 = { version = "0.4.0", default-features = false, features = ["curve"], optional = true } -ark-bls12-381-ext = { version = "0.4.1", default-features = false, optional = true } -ark-bls12-381 = { version = "0.4.0", default-features = false, features = ["curve"], optional = true } -ark-bw6-761-ext = { version = "0.4.1", default-features = false, optional = true } -ark-bw6-761 = { version = "0.4.0", default-features = false, optional = true } -ark-ed-on-bls12-381-bandersnatch-ext = { version = "0.4.1", default-features = false, optional = true } -ark-ed-on-bls12-381-bandersnatch = { version = "0.4.0", default-features = false, optional = true } -ark-ed-on-bls12-377-ext = { version = "0.4.1", default-features = false, optional = true } -ark-ed-on-bls12-377 = { version = "0.4.0", default-features = false, optional = true } -ark-scale = { version = "0.0.12", default-features = false, features = ["hazmat"], optional = true } -sp-runtime-interface = { path = "../../runtime-interface", default-features = false, optional = true } +ark-ec = { optional = true, workspace = true } +ark-bls12-377-ext = { optional = true, workspace = true } +ark-bls12-377 = { features = ["curve"], optional = true, workspace = true } +ark-bls12-381-ext = { optional = true, workspace = true } +ark-bls12-381 = { features = ["curve"], optional = true, workspace = true } +ark-bw6-761-ext = { optional = true, workspace = true } +ark-bw6-761 = { optional = true, workspace = true } +ark-ed-on-bls12-381-bandersnatch-ext = { optional = true, workspace = true } +ark-ed-on-bls12-381-bandersnatch = { optional = true, workspace = true } +ark-ed-on-bls12-377-ext = { optional = true, workspace = true } +ark-ed-on-bls12-377 = { optional = true, workspace = true } +ark-scale = { features = ["hazmat"], optional = true, workspace = true } +sp-runtime-interface = { optional = true, workspace = true } [features] default = ["std"] diff --git a/substrate/primitives/crypto/hashing/Cargo.toml b/substrate/primitives/crypto/hashing/Cargo.toml index 1755164888bc9f846dd2ff587aaef5124dd8923d..461af269bf2dae83538ca07d4cf8190fca4e679a 100644 --- a/substrate/primitives/crypto/hashing/Cargo.toml +++ b/substrate/primitives/crypto/hashing/Cargo.toml @@ -16,16 +16,16 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -blake2b_simd = { version = "1.0.1", default-features = false } -byteorder = { version = "1.3.2", default-features = false } -digest = { version = "0.10.3", default-features = false } -sha2 = { version = "0.10.7", default-features = false } -sha3 = { version = "0.10.0", default-features = false } -twox-hash = { version = "1.6.3", default-features = false, features = ["digest_0_10"] } +blake2b_simd = { workspace = true } +byteorder = { workspace = true } +digest = { workspace = true } +sha2 = { workspace = true } +sha3 = { workspace = true } +twox-hash = { features = ["digest_0_10"], workspace = true } [dev-dependencies] -criterion = "0.5.1" -sp-crypto-hashing-proc-macro = { path = "proc-macro" } +criterion = { workspace = true, default-features = true } +sp-crypto-hashing-proc-macro = { workspace = true, default-features = true } [[bench]] name = "bench" diff --git a/substrate/primitives/crypto/hashing/proc-macro/Cargo.toml b/substrate/primitives/crypto/hashing/proc-macro/Cargo.toml index f988042d3075933bda6ae62b48291be8ebc80936..68e865c7dac58613146ca1d9e6dc398346c7455b 100644 --- a/substrate/primitives/crypto/hashing/proc-macro/Cargo.toml +++ b/substrate/primitives/crypto/hashing/proc-macro/Cargo.toml @@ -21,4 +21,4 @@ proc-macro = true [dependencies] quote = { workspace = true } syn = { features = ["full", "parsing"], workspace = true } -sp-crypto-hashing = { path = "..", default-features = false } +sp-crypto-hashing = { workspace = true } diff --git a/substrate/primitives/database/Cargo.toml b/substrate/primitives/database/Cargo.toml index 081aad6075840c109d397d5830e3e654c3325172..c0867198e8b9be3eeb0827ec9cc556e6f4082940 100644 --- a/substrate/primitives/database/Cargo.toml +++ b/substrate/primitives/database/Cargo.toml @@ -14,5 +14,5 @@ readme = "README.md" workspace = true [dependencies] -kvdb = "0.13.0" -parking_lot = "0.12.1" +kvdb = { workspace = true } +parking_lot = { workspace = true, default-features = true } diff --git a/substrate/primitives/debug-derive/Cargo.toml b/substrate/primitives/debug-derive/Cargo.toml index debf964aa3dfdf7cebd23e0f1d24e74b0d880ec0..4f45d6525c4a9a153ad763847a4f79548127e8cc 100644 --- a/substrate/primitives/debug-derive/Cargo.toml +++ b/substrate/primitives/debug-derive/Cargo.toml @@ -21,7 +21,7 @@ proc-macro = true [dependencies] quote = { workspace = true } syn = { workspace = true } -proc-macro2 = "1.0.56" +proc-macro2 = { workspace = true } [features] default = ["std"] diff --git a/substrate/primitives/externalities/Cargo.toml b/substrate/primitives/externalities/Cargo.toml index 3a0d0315e9178a0e54ba001064fb6feb65c1b731..ca2f57c03b948061a15b73f5d7271885e5bc8a3c 100644 --- a/substrate/primitives/externalities/Cargo.toml +++ b/substrate/primitives/externalities/Cargo.toml @@ -17,9 +17,9 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -environmental = { version = "1.1.3", default-features = false } -sp-storage = { path = "../storage", default-features = false } +codec = { workspace = true } +environmental = { workspace = true } +sp-storage = { workspace = true } [features] default = ["std"] diff --git a/substrate/primitives/externalities/src/lib.rs b/substrate/primitives/externalities/src/lib.rs index 142200f614a69d8a5e195db8d434fba4bb5a83b7..bcc46ee4f1b2993fd34a5d632d2ce4a2757872e4 100644 --- a/substrate/primitives/externalities/src/lib.rs +++ b/substrate/primitives/externalities/src/lib.rs @@ -83,24 +83,24 @@ pub trait Externalities: ExtensionStore { fn set_offchain_storage(&mut self, key: &[u8], value: Option<&[u8]>); /// Read runtime storage. - fn storage(&self, key: &[u8]) -> Option>; + fn storage(&mut self, key: &[u8]) -> Option>; /// Get storage value hash. /// /// This may be optimized for large values. - fn storage_hash(&self, key: &[u8]) -> Option>; + fn storage_hash(&mut self, key: &[u8]) -> Option>; /// Get child storage value hash. /// /// This may be optimized for large values. /// /// Returns an `Option` that holds the SCALE encoded hash. - fn child_storage_hash(&self, child_info: &ChildInfo, key: &[u8]) -> Option>; + fn child_storage_hash(&mut self, child_info: &ChildInfo, key: &[u8]) -> Option>; /// Read child runtime storage. /// /// Returns an `Option` that holds the SCALE encoded hash. - fn child_storage(&self, child_info: &ChildInfo, key: &[u8]) -> Option>; + fn child_storage(&mut self, child_info: &ChildInfo, key: &[u8]) -> Option>; /// Set storage entry `key` of current contract being called (effective immediately). fn set_storage(&mut self, key: Vec, value: Vec) { @@ -124,20 +124,20 @@ pub trait Externalities: ExtensionStore { } /// Whether a storage entry exists. - fn exists_storage(&self, key: &[u8]) -> bool { + fn exists_storage(&mut self, key: &[u8]) -> bool { self.storage(key).is_some() } /// Whether a child storage entry exists. - fn exists_child_storage(&self, child_info: &ChildInfo, key: &[u8]) -> bool { + fn exists_child_storage(&mut self, child_info: &ChildInfo, key: &[u8]) -> bool { self.child_storage(child_info, key).is_some() } /// Returns the key immediately following the given key, if it exists. - fn next_storage_key(&self, key: &[u8]) -> Option>; + fn next_storage_key(&mut self, key: &[u8]) -> Option>; /// Returns the key immediately following the given key, if it exists, in child storage. - fn next_child_storage_key(&self, child_info: &ChildInfo, key: &[u8]) -> Option>; + fn next_child_storage_key(&mut self, child_info: &ChildInfo, key: &[u8]) -> Option>; /// Clear an entire child storage. /// diff --git a/substrate/primitives/genesis-builder/Cargo.toml b/substrate/primitives/genesis-builder/Cargo.toml index 4fc8a0416fbe5f2ffdbd021dd42a3d072c61b241..d4345d17e7e5c20829448fed3e7c5bd1579bb928 100644 --- a/substrate/primitives/genesis-builder/Cargo.toml +++ b/substrate/primitives/genesis-builder/Cargo.toml @@ -16,11 +16,11 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["bytes"] } -scale-info = { version = "2.10.0", default-features = false, features = ["derive"] } +codec = { features = ["bytes"], workspace = true } +scale-info = { features = ["derive"], workspace = true } -sp-api = { path = "../api", default-features = false } -sp-runtime = { path = "../runtime", default-features = false } +sp-api = { workspace = true } +sp-runtime = { workspace = true } serde_json = { features = ["alloc", "arbitrary_precision"], workspace = true } [features] diff --git a/substrate/primitives/inherents/Cargo.toml b/substrate/primitives/inherents/Cargo.toml index c63aca801a0d7e513963b06d2ce4375f17194d3d..1495287698d66ba712b853b6e5188957420b2cbd 100644 --- a/substrate/primitives/inherents/Cargo.toml +++ b/substrate/primitives/inherents/Cargo.toml @@ -17,15 +17,15 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -async-trait = { version = "0.1.79", optional = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -impl-trait-for-tuples = "0.2.2" +async-trait = { optional = true, workspace = true } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } +impl-trait-for-tuples = { workspace = true } thiserror = { optional = true, workspace = true } -sp-runtime = { path = "../runtime", default-features = false, optional = true } +sp-runtime = { optional = true, workspace = true } [dev-dependencies] -futures = "0.3.30" +futures = { workspace = true } [features] default = ["std"] diff --git a/substrate/primitives/io/Cargo.toml b/substrate/primitives/io/Cargo.toml index abb16d163da060ae1d152276189157b77fb6970d..6b58ea70b8e5ef3a31fc1b9b468e43b544d21343 100644 --- a/substrate/primitives/io/Cargo.toml +++ b/substrate/primitives/io/Cargo.toml @@ -18,31 +18,38 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -bytes = { version = "1.1.0", default-features = false } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["bytes"] } -sp-core = { path = "../core", default-features = false } -sp-crypto-hashing = { path = "../crypto/hashing", default-features = false } -sp-keystore = { path = "../keystore", default-features = false, optional = true } -sp-std = { path = "../std", default-features = false } -libsecp256k1 = { version = "0.7", optional = true } -sp-state-machine = { path = "../state-machine", default-features = false, optional = true } -sp-runtime-interface = { path = "../runtime-interface", default-features = false } -sp-trie = { path = "../trie", default-features = false, optional = true } -sp-externalities = { path = "../externalities", default-features = false } -sp-tracing = { path = "../tracing", default-features = false } +bytes = { workspace = true } +codec = { features = [ + "bytes", +], workspace = true } +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 } +sp-trie = { optional = true, workspace = true } +sp-externalities = { workspace = true } +sp-tracing = { workspace = true } log = { optional = true, workspace = true, default-features = true } -secp256k1 = { version = "0.28.0", features = ["global-context", "recovery"], optional = true } -tracing = { version = "0.1.29", default-features = false } -tracing-core = { version = "0.1.32", default-features = false } +secp256k1 = { features = [ + "global-context", + "recovery", +], optional = true, workspace = true, default-features = true } +tracing = { workspace = true } +tracing-core = { workspace = true } # Required for backwards compatibility reason, but only used for verifying when `UseDalekExt` is set. -ed25519-dalek = { version = "2.1", default-features = false, optional = true } +ed25519-dalek = { optional = true, workspace = true } + +docify = { workspace = true } [target.'cfg(all(any(target_arch = "riscv32", target_arch = "riscv64"), substrate_runtime))'.dependencies] polkavm-derive = { workspace = true } [build-dependencies] -rustversion = "1.0.6" +rustversion = { workspace = true } [features] default = ["std"] diff --git a/substrate/primitives/io/src/lib.rs b/substrate/primitives/io/src/lib.rs index c8675a9a90bd2ee16b9deca27457fafa88f8fec0..67e822ba7e248ed2b07614b85dca4e1c72e8c3e3 100644 --- a/substrate/primitives/io/src/lib.rs +++ b/substrate/primitives/io/src/lib.rs @@ -181,7 +181,7 @@ impl From for KillStorageResult { #[runtime_interface] pub trait Storage { /// Returns the data for `key` in the storage or `None` if the key can not be found. - fn get(&self, key: &[u8]) -> Option { + fn get(&mut self, key: &[u8]) -> Option { self.storage(key).map(bytes::Bytes::from) } @@ -190,7 +190,7 @@ pub trait Storage { /// doesn't exist at all. /// If `value_out` length is smaller than the returned length, only `value_out` length bytes /// are copied into `value_out`. - fn read(&self, key: &[u8], value_out: &mut [u8], value_offset: u32) -> Option { + fn read(&mut self, key: &[u8], value_out: &mut [u8], value_offset: u32) -> Option { self.storage(key).map(|value| { let value_offset = value_offset as usize; let data = &value[value_offset.min(value.len())..]; @@ -211,7 +211,7 @@ pub trait Storage { } /// Check whether the given `key` exists in storage. - fn exists(&self, key: &[u8]) -> bool { + fn exists(&mut self, key: &[u8]) -> bool { self.exists_storage(key) } @@ -387,7 +387,7 @@ pub trait DefaultChildStorage { /// /// Parameter `storage_key` is the unprefixed location of the root of the child trie in the /// parent trie. Result is `None` if the value for `key` in the child storage can not be found. - fn get(&self, storage_key: &[u8], key: &[u8]) -> Option> { + fn get(&mut self, storage_key: &[u8], key: &[u8]) -> Option> { let child_info = ChildInfo::new_default(storage_key); self.child_storage(&child_info, key).map(|s| s.to_vec()) } @@ -400,7 +400,7 @@ pub trait DefaultChildStorage { /// If `value_out` length is smaller than the returned length, only `value_out` length bytes /// are copied into `value_out`. fn read( - &self, + &mut self, storage_key: &[u8], key: &[u8], value_out: &mut [u8], @@ -478,7 +478,7 @@ pub trait DefaultChildStorage { /// Check a child storage key. /// /// Check whether the given `key` exists in default child defined at `storage_key`. - fn exists(&self, storage_key: &[u8], key: &[u8]) -> bool { + fn exists(&mut self, storage_key: &[u8], key: &[u8]) -> bool { let child_info = ChildInfo::new_default(storage_key); self.exists_child_storage(&child_info, key) } @@ -1805,6 +1805,7 @@ pub type TestExternalities = sp_state_machine::TestExternalities(data); +}); diff --git a/substrate/primitives/state-machine/src/basic.rs b/substrate/primitives/state-machine/src/basic.rs index 8b6f746eaba0af9438557dc7dbe118bfbc4cdf34..6201d60ababd27d1e212791a03e62b7915be2c98 100644 --- a/substrate/primitives/state-machine/src/basic.rs +++ b/substrate/primitives/state-machine/src/basic.rs @@ -59,16 +59,17 @@ impl BasicExternalities { } /// Consume self and returns inner storages - pub fn into_storages(self) -> Storage { + #[cfg(feature = "std")] + pub fn into_storages(mut self) -> Storage { Storage { top: self .overlay - .changes() + .changes_mut() .filter_map(|(k, v)| v.value().map(|v| (k.to_vec(), v.to_vec()))) .collect(), children_default: self .overlay - .children() + .children_mut() .map(|(iter, i)| { ( i.storage_key().to_vec(), @@ -87,6 +88,7 @@ impl BasicExternalities { /// Execute the given closure `f` with the externalities set and initialized with `storage`. /// /// Returns the result of the closure and updates `storage` with all changes. + #[cfg(feature = "std")] pub fn execute_with_storage( storage: &mut sp_core::storage::Storage, f: impl FnOnce() -> R, @@ -118,19 +120,37 @@ impl BasicExternalities { } } +#[cfg(test)] impl PartialEq for BasicExternalities { - fn eq(&self, other: &BasicExternalities) -> bool { - self.overlay.changes().map(|(k, v)| (k, v.value())).collect::>() == - other.overlay.changes().map(|(k, v)| (k, v.value())).collect::>() && + fn eq(&self, other: &Self) -> bool { + self.overlay + .changes() + .map(|(k, v)| (k, v.value_ref().materialize())) + .collect::>() == + other + .overlay + .changes() + .map(|(k, v)| (k, v.value_ref().materialize())) + .collect::>() && self.overlay .children() - .map(|(iter, i)| (i, iter.map(|(k, v)| (k, v.value())).collect::>())) + .map(|(iter, i)| { + ( + i, + iter.map(|(k, v)| (k, v.value_ref().materialize())) + .collect::>(), + ) + }) .collect::>() == other .overlay .children() .map(|(iter, i)| { - (i, iter.map(|(k, v)| (k, v.value())).collect::>()) + ( + i, + iter.map(|(k, v)| (k, v.value_ref().materialize())) + .collect::>(), + ) }) .collect::>() } @@ -159,27 +179,27 @@ impl From> for BasicExternalities { impl Externalities for BasicExternalities { fn set_offchain_storage(&mut self, _key: &[u8], _value: Option<&[u8]>) {} - fn storage(&self, key: &[u8]) -> Option { + fn storage(&mut self, key: &[u8]) -> Option { self.overlay.storage(key).and_then(|v| v.map(|v| v.to_vec())) } - fn storage_hash(&self, key: &[u8]) -> Option> { + fn storage_hash(&mut self, key: &[u8]) -> Option> { self.storage(key).map(|v| Blake2Hasher::hash(&v).encode()) } - fn child_storage(&self, child_info: &ChildInfo, key: &[u8]) -> Option { + fn child_storage(&mut self, child_info: &ChildInfo, key: &[u8]) -> Option { self.overlay.child_storage(child_info, key).and_then(|v| v.map(|v| v.to_vec())) } - fn child_storage_hash(&self, child_info: &ChildInfo, key: &[u8]) -> Option> { + fn child_storage_hash(&mut self, child_info: &ChildInfo, key: &[u8]) -> Option> { self.child_storage(child_info, key).map(|v| Blake2Hasher::hash(&v).encode()) } - fn next_storage_key(&self, key: &[u8]) -> Option { + fn next_storage_key(&mut self, key: &[u8]) -> Option { self.overlay.iter_after(key).find_map(|(k, v)| v.value().map(|_| k.to_vec())) } - fn next_child_storage_key(&self, child_info: &ChildInfo, key: &[u8]) -> Option { + fn next_child_storage_key(&mut self, child_info: &ChildInfo, key: &[u8]) -> Option { self.overlay .child_iter_after(child_info.storage_key(), key) .find_map(|(k, v)| v.value().map(|_| k.to_vec())) @@ -243,15 +263,14 @@ impl Externalities for BasicExternalities { MultiRemovalResults { maybe_cursor: None, backend: count, unique: count, loops: count } } - fn storage_append(&mut self, key: Vec, value: Vec) { - let current_value = self.overlay.value_mut_or_insert_with(&key, || Default::default()); - crate::ext::StorageAppend::new(current_value).append(value); + fn storage_append(&mut self, key: Vec, element: Vec) { + self.overlay.append_storage(key, element, Default::default); } fn storage_root(&mut self, state_version: StateVersion) -> Vec { let mut top = self .overlay - .changes() + .changes_mut() .filter_map(|(k, v)| v.value().map(|v| (k.clone(), v.clone()))) .collect::>(); // Single child trie implementation currently allows using the same child @@ -278,7 +297,7 @@ impl Externalities for BasicExternalities { child_info: &ChildInfo, state_version: StateVersion, ) -> Vec { - if let Some((data, child_info)) = self.overlay.child_changes(child_info.storage_key()) { + if let Some((data, child_info)) = self.overlay.child_changes_mut(child_info.storage_key()) { let delta = data.into_iter().map(|(k, v)| (k.as_ref(), v.value().map(|v| v.as_slice()))); crate::in_memory_backend::new_in_mem::() diff --git a/substrate/primitives/state-machine/src/ext.rs b/substrate/primitives/state-machine/src/ext.rs index 9aa32bc866cfab9e2db44959c93bc4fe0b11e120..7a79c4e8a1f1bbd51fbdb34f5b91d2427bdd2995 100644 --- a/substrate/primitives/state-machine/src/ext.rs +++ b/substrate/primitives/state-machine/src/ext.rs @@ -22,7 +22,7 @@ use crate::overlayed_changes::OverlayedExtensions; use crate::{ backend::Backend, IndexOperation, IterArgs, OverlayedChanges, StorageKey, StorageValue, }; -use codec::{Encode, EncodeAppend}; +use codec::{Compact, CompactLen, Decode, Encode}; use hash_db::Hasher; #[cfg(feature = "std")] use sp_core::hexdisplay::HexDisplay; @@ -31,8 +31,8 @@ use sp_core::storage::{ }; use sp_externalities::{Extension, ExtensionStore, Externalities, MultiRemovalResults}; -use crate::{log_error, trace, warn}; -use alloc::{boxed::Box, vec, vec::Vec}; +use crate::{trace, warn}; +use alloc::{boxed::Box, vec::Vec}; use core::{ any::{Any, TypeId}, cmp::Ordering, @@ -139,7 +139,7 @@ where H::Out: Ord + 'static, B: 'a + Backend, { - pub fn storage_pairs(&self) -> Vec<(StorageKey, StorageValue)> { + pub fn storage_pairs(&mut self) -> Vec<(StorageKey, StorageValue)> { use std::collections::HashMap; self.backend @@ -147,7 +147,7 @@ where .expect("never fails in tests; qed.") .map(|key_value| key_value.expect("never fails in tests; qed.")) .map(|(k, v)| (k, Some(v))) - .chain(self.overlay.changes().map(|(k, v)| (k.clone(), v.value().cloned()))) + .chain(self.overlay.changes_mut().map(|(k, v)| (k.clone(), v.value().cloned()))) .collect::>() .into_iter() .filter_map(|(k, maybe_val)| maybe_val.map(|val| (k, val))) @@ -165,7 +165,7 @@ where self.overlay.set_offchain_storage(key, value) } - fn storage(&self, key: &[u8]) -> Option { + fn storage(&mut self, key: &[u8]) -> Option { let _guard = guard(); let result = self .overlay @@ -191,7 +191,7 @@ where result } - fn storage_hash(&self, key: &[u8]) -> Option> { + fn storage_hash(&mut self, key: &[u8]) -> Option> { let _guard = guard(); let result = self .overlay @@ -209,7 +209,7 @@ where result.map(|r| r.encode()) } - fn child_storage(&self, child_info: &ChildInfo, key: &[u8]) -> Option { + fn child_storage(&mut self, child_info: &ChildInfo, key: &[u8]) -> Option { let _guard = guard(); let result = self .overlay @@ -231,7 +231,7 @@ where result } - fn child_storage_hash(&self, child_info: &ChildInfo, key: &[u8]) -> Option> { + fn child_storage_hash(&mut self, child_info: &ChildInfo, key: &[u8]) -> Option> { let _guard = guard(); let result = self .overlay @@ -253,7 +253,7 @@ where result.map(|r| r.encode()) } - fn exists_storage(&self, key: &[u8]) -> bool { + fn exists_storage(&mut self, key: &[u8]) -> bool { let _guard = guard(); let result = match self.overlay.storage(key) { Some(x) => x.is_some(), @@ -271,7 +271,7 @@ where result } - fn exists_child_storage(&self, child_info: &ChildInfo, key: &[u8]) -> bool { + fn exists_child_storage(&mut self, child_info: &ChildInfo, key: &[u8]) -> bool { let _guard = guard(); let result = match self.overlay.child_storage(child_info, key) { @@ -293,7 +293,7 @@ where result } - fn next_storage_key(&self, key: &[u8]) -> Option { + fn next_storage_key(&mut self, key: &[u8]) -> Option { let mut next_backend_key = self.backend.next_storage_key(key).expect(EXT_NOT_ALLOWED_TO_FAIL); let mut overlay_changes = self.overlay.iter_after(key).peekable(); @@ -331,7 +331,7 @@ where } } - fn next_child_storage_key(&self, child_info: &ChildInfo, key: &[u8]) -> Option { + fn next_child_storage_key(&mut self, child_info: &ChildInfo, key: &[u8]) -> Option { let mut next_backend_key = self .backend .next_child_storage_key(child_info, key) @@ -501,10 +501,9 @@ where let _guard = guard(); let backend = &mut self.backend; - let current_value = self.overlay.value_mut_or_insert_with(&key, || { + self.overlay.append_storage(key.clone(), value, || { backend.storage(&key).expect(EXT_NOT_ALLOWED_TO_FAIL).unwrap_or_default() }); - StorageAppend::new(current_value).append(value); } fn storage_root(&mut self, state_version: StateVersion) -> Vec { @@ -731,10 +730,27 @@ impl<'a> StorageAppend<'a> { Self(storage) } + /// Extract the length of the list like data structure. + pub fn extract_length(&self) -> Option { + Compact::::decode(&mut &self.0[..]).map(|c| c.0).ok() + } + + /// Replace the length in the encoded data. + /// + /// If `old_length` is `None`, the previous length will be assumed to be `0`. + pub fn replace_length(&mut self, old_length: Option, new_length: u32) { + let old_len_encoded_len = old_length.map(|l| Compact::::compact_len(&l)).unwrap_or(0); + let new_len_encoded = Compact::(new_length).encode(); + self.0.splice(0..old_len_encoded_len, new_len_encoded); + } + /// Append the given `value` to the storage item. /// - /// If appending fails, `[value]` is stored in the storage item. - pub fn append(&mut self, value: Vec) { + /// If appending fails, `[value]` is stored in the storage item and we return false. + #[cfg(any(test, feature = "fuzzing"))] + pub fn append(&mut self, value: Vec) -> bool { + use codec::EncodeAppend; + let mut result = true; let value = vec![EncodeOpaqueValue(value)]; let item = core::mem::take(self.0); @@ -742,13 +758,20 @@ impl<'a> StorageAppend<'a> { *self.0 = match Vec::::append_or_new(item, &value) { Ok(item) => item, Err(_) => { - log_error!( + result = false; + crate::log_error!( target: "runtime", "Failed to append value, resetting storage item to `[value]`.", ); value.encode() }, }; + result + } + + /// Append to current buffer, do not touch the prefixed length. + pub fn append_raw(&mut self, mut value: Vec) { + self.0.append(&mut value) } } @@ -849,7 +872,7 @@ mod tests { ) .into(); - let ext = TestExt::new(&mut overlay, &backend, None); + let mut ext = TestExt::new(&mut overlay, &backend, None); // next_backend < next_overlay assert_eq!(ext.next_storage_key(&[5]), Some(vec![10])); @@ -865,7 +888,7 @@ mod tests { drop(ext); overlay.set_storage(vec![50], Some(vec![50])); - let ext = TestExt::new(&mut overlay, &backend, None); + let mut ext = TestExt::new(&mut overlay, &backend, None); // next_overlay exist but next_backend doesn't exist assert_eq!(ext.next_storage_key(&[40]), Some(vec![50])); @@ -895,7 +918,7 @@ mod tests { ) .into(); - let ext = TestExt::new(&mut overlay, &backend, None); + let mut ext = TestExt::new(&mut overlay, &backend, None); assert_eq!(ext.next_storage_key(&[5]), Some(vec![30])); @@ -928,7 +951,7 @@ mod tests { ) .into(); - let ext = TestExt::new(&mut overlay, &backend, None); + let mut ext = TestExt::new(&mut overlay, &backend, None); // next_backend < next_overlay assert_eq!(ext.next_child_storage_key(child_info, &[5]), Some(vec![10])); @@ -944,7 +967,7 @@ mod tests { drop(ext); overlay.set_child_storage(child_info, vec![50], Some(vec![50])); - let ext = TestExt::new(&mut overlay, &backend, None); + let mut ext = TestExt::new(&mut overlay, &backend, None); // next_overlay exist but next_backend doesn't exist assert_eq!(ext.next_child_storage_key(child_info, &[40]), Some(vec![50])); @@ -975,7 +998,7 @@ mod tests { ) .into(); - let ext = TestExt::new(&mut overlay, &backend, None); + let mut ext = TestExt::new(&mut overlay, &backend, None); assert_eq!(ext.child_storage(child_info, &[10]), Some(vec![10])); assert_eq!( diff --git a/substrate/primitives/state-machine/src/fuzzing.rs b/substrate/primitives/state-machine/src/fuzzing.rs new file mode 100644 index 0000000000000000000000000000000000000000..e147e6e88003cf720d4f6062c392630602210388 --- /dev/null +++ b/substrate/primitives/state-machine/src/fuzzing.rs @@ -0,0 +1,319 @@ +// 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. + +//! State machine fuzzing implementation, behind `fuzzing` feature. + +use super::{ext::Ext, *}; +use crate::ext::StorageAppend; +use arbitrary::Arbitrary; +#[cfg(test)] +use codec::Encode; +use hash_db::Hasher; +use sp_core::{storage::StateVersion, traits::Externalities}; +#[cfg(test)] +use sp_runtime::traits::BlakeTwo256; +use sp_trie::PrefixedMemoryDB; +use std::collections::BTreeMap; + +#[derive(Arbitrary, Debug, Clone)] +enum DataLength { + Zero = 0, + Small = 1, + Medium = 3, + Big = 300, // 2 byte scale encode length +} + +#[derive(Arbitrary, Debug, Clone)] +#[repr(u8)] +enum DataValue { + A = b'a', + B = b'b', + C = b'c', + D = b'd', // This can be read as a multiple byte compact length. + EasyBug = 20u8, // value compact len. +} + +/// Action to fuzz +#[derive(Arbitrary, Debug, Clone)] +enum FuzzAppendItem { + Append(DataValue, DataLength), + Insert(DataValue, DataLength), + StartTransaction, + RollbackTransaction, + CommitTransaction, + Read, + Remove, + // To go over 256 items easily (different compact size then). + Append50(DataValue, DataLength), +} + +/// Arbitrary payload for fuzzing append. +#[derive(Arbitrary, Debug, Clone)] +pub struct FuzzAppendPayload(Vec, Option<(DataValue, DataLength)>); + +struct SimpleOverlay { + data: Vec, Option>>>, +} + +impl Default for SimpleOverlay { + fn default() -> Self { + Self { data: vec![BTreeMap::new()] } + } +} + +impl SimpleOverlay { + fn insert(&mut self, key: Vec, value: Option>) { + self.data.last_mut().expect("always at least one item").insert(key, value); + } + + fn append( + &mut self, + key: Vec, + value: Vec, + backend: &mut TrieBackend, H>, + ) where + H: Hasher, + H::Out: codec::Decode + codec::Encode + 'static, + { + let current_value = self + .data + .last_mut() + .expect("always at least one item") + .entry(key.clone()) + .or_insert_with(|| { + Some(backend.storage(&key).expect("Ext not allowed to fail").unwrap_or_default()) + }); + if current_value.is_none() { + *current_value = Some(vec![]); + } + StorageAppend::new(current_value.as_mut().expect("init above")).append(value); + } + + fn get(&mut self, key: &[u8]) -> Option<&Vec> { + self.data + .last_mut() + .expect("always at least one item") + .get(key) + .and_then(|o| o.as_ref()) + } + + fn commit_transaction(&mut self) { + if let Some(to_commit) = self.data.pop() { + let dest = self.data.last_mut().expect("always at least one item"); + for (k, v) in to_commit.into_iter() { + dest.insert(k, v); + } + } + } + + fn rollback_transaction(&mut self) { + let _ = self.data.pop(); + } + + fn start_transaction(&mut self) { + let cloned = self.data.last().expect("always at least one item").clone(); + self.data.push(cloned); + } +} + +struct FuzzAppendState { + key: Vec, + + // reference simple implementation + reference: SimpleOverlay, + + // trie backend + backend: TrieBackend, H>, + // Standard Overlay + overlay: OverlayedChanges, + + // block dropping/commiting too many transaction + transaction_depth: usize, +} + +impl FuzzAppendState +where + H: Hasher, + H::Out: codec::Decode + codec::Encode + 'static, +{ + fn process_item(&mut self, item: FuzzAppendItem) { + let mut ext = Ext::new(&mut self.overlay, &mut self.backend, None); + match item { + FuzzAppendItem::Append(value, length) => { + let value = vec![value as u8; length as usize]; + ext.storage_append(self.key.clone(), value.clone()); + self.reference.append(self.key.clone(), value, &mut self.backend); + }, + FuzzAppendItem::Append50(value, length) => { + let value = vec![value as u8; length as usize]; + for _ in 0..50 { + let mut ext = Ext::new(&mut self.overlay, &mut self.backend, None); + ext.storage_append(self.key.clone(), value.clone()); + self.reference.append(self.key.clone(), value.clone(), &mut self.backend); + } + }, + FuzzAppendItem::Insert(value, length) => { + let value = vec![value as u8; length as usize]; + ext.set_storage(self.key.clone(), value.clone()); + self.reference.insert(self.key.clone(), Some(value)); + }, + FuzzAppendItem::Remove => { + ext.clear_storage(&self.key); + self.reference.insert(self.key.clone(), None); + }, + FuzzAppendItem::Read => { + let left = ext.storage(self.key.as_slice()); + let right = self.reference.get(self.key.as_slice()); + assert_eq!(left.as_ref(), right); + }, + FuzzAppendItem::StartTransaction => { + self.transaction_depth += 1; + self.reference.start_transaction(); + ext.storage_start_transaction(); + }, + FuzzAppendItem::RollbackTransaction => { + if self.transaction_depth == 0 { + return + } + self.transaction_depth -= 1; + self.reference.rollback_transaction(); + ext.storage_rollback_transaction().unwrap(); + }, + FuzzAppendItem::CommitTransaction => { + if self.transaction_depth == 0 { + return + } + self.transaction_depth -= 1; + self.reference.commit_transaction(); + ext.storage_commit_transaction().unwrap(); + }, + } + } + + fn check_final_state(&mut self) { + let mut ext = Ext::new(&mut self.overlay, &mut self.backend, None); + let left = ext.storage(self.key.as_slice()); + let right = self.reference.get(self.key.as_slice()); + assert_eq!(left.as_ref(), right); + } +} + +#[test] +fn fuzz_scenarii() { + assert_eq!(codec::Compact(5u16).encode()[0], DataValue::EasyBug as u8); + let scenarii = vec![ + ( + vec![ + FuzzAppendItem::Append(DataValue::A, DataLength::Small), + FuzzAppendItem::StartTransaction, + FuzzAppendItem::Append50(DataValue::D, DataLength::Small), + FuzzAppendItem::Read, + FuzzAppendItem::RollbackTransaction, + FuzzAppendItem::StartTransaction, + FuzzAppendItem::Append(DataValue::D, DataLength::Small), + FuzzAppendItem::Read, + FuzzAppendItem::RollbackTransaction, + ], + Some((DataValue::D, DataLength::Small)), + ), + ( + vec![ + FuzzAppendItem::Append(DataValue::B, DataLength::Small), + FuzzAppendItem::StartTransaction, + FuzzAppendItem::Append(DataValue::A, DataLength::Small), + FuzzAppendItem::StartTransaction, + FuzzAppendItem::Remove, + FuzzAppendItem::StartTransaction, + FuzzAppendItem::Append(DataValue::A, DataLength::Zero), + FuzzAppendItem::CommitTransaction, + FuzzAppendItem::CommitTransaction, + FuzzAppendItem::Remove, + ], + Some((DataValue::EasyBug, DataLength::Small)), + ), + ( + vec![ + FuzzAppendItem::Append(DataValue::A, DataLength::Small), + FuzzAppendItem::StartTransaction, + FuzzAppendItem::Append(DataValue::A, DataLength::Medium), + FuzzAppendItem::StartTransaction, + FuzzAppendItem::Remove, + FuzzAppendItem::CommitTransaction, + FuzzAppendItem::RollbackTransaction, + ], + Some((DataValue::B, DataLength::Big)), + ), + ( + vec![ + FuzzAppendItem::Append(DataValue::A, DataLength::Big), + FuzzAppendItem::StartTransaction, + FuzzAppendItem::Append(DataValue::A, DataLength::Medium), + FuzzAppendItem::Remove, + FuzzAppendItem::RollbackTransaction, + FuzzAppendItem::StartTransaction, + FuzzAppendItem::Append(DataValue::A, DataLength::Zero), + ], + None, + ), + ( + vec![ + FuzzAppendItem::StartTransaction, + FuzzAppendItem::RollbackTransaction, + FuzzAppendItem::RollbackTransaction, + FuzzAppendItem::Append(DataValue::A, DataLength::Zero), + ], + None, + ), + (vec![FuzzAppendItem::StartTransaction], Some((DataValue::EasyBug, DataLength::Zero))), + ]; + + for (scenario, init) in scenarii.into_iter() { + fuzz_append::(FuzzAppendPayload(scenario, init)); + } +} + +/// Test append operation for a given fuzzing payload. +pub fn fuzz_append(payload: FuzzAppendPayload) +where + H: Hasher, + H::Out: codec::Decode + codec::Encode + 'static, +{ + let FuzzAppendPayload(to_fuzz, initial) = payload; + let key = b"k".to_vec(); + let mut reference = SimpleOverlay::default(); + let initial: BTreeMap<_, _> = initial + .into_iter() + .map(|(v, l)| (key.clone(), vec![v as u8; l as usize])) + .collect(); + for (k, v) in initial.iter() { + reference.data[0].insert(k.clone(), Some(v.clone())); + } + reference.start_transaction(); // level 0 is backend, keep it untouched. + let overlay = OverlayedChanges::default(); + + let mut state = FuzzAppendState:: { + key, + reference, + overlay, + backend: (initial, StateVersion::default()).into(), + transaction_depth: 0, + }; + for item in to_fuzz { + state.process_item(item); + } + state.check_final_state(); +} diff --git a/substrate/primitives/state-machine/src/in_memory_backend.rs b/substrate/primitives/state-machine/src/in_memory_backend.rs index 06fe6d4162a7f4c920c8f09c2e4e8b05a3c72c03..7ba7457a6bf18bfb17d3faa7c6d3aaea6cd36788 100644 --- a/substrate/primitives/state-machine/src/in_memory_backend.rs +++ b/substrate/primitives/state-machine/src/in_memory_backend.rs @@ -132,6 +132,7 @@ where } } +#[cfg(feature = "std")] impl From<(Storage, StateVersion)> for TrieBackend, H> where H::Out: Codec + Ord, diff --git a/substrate/primitives/state-machine/src/lib.rs b/substrate/primitives/state-machine/src/lib.rs index 13087431d387b9e986519bbdcabfe9eb3c4fe5c5..289b08755f680605a28a16adabac3cb3698a83fc 100644 --- a/substrate/primitives/state-machine/src/lib.rs +++ b/substrate/primitives/state-machine/src/lib.rs @@ -27,6 +27,8 @@ pub mod backend; mod basic; mod error; mod ext; +#[cfg(feature = "fuzzing")] +pub mod fuzzing; #[cfg(feature = "std")] mod in_memory_backend; pub(crate) mod overlayed_changes; @@ -1273,7 +1275,7 @@ mod tests { assert_eq!( overlay - .changes() + .changes_mut() .map(|(k, v)| (k.clone(), v.value().cloned())) .collect::>(), map![ @@ -1299,7 +1301,7 @@ mod tests { assert_eq!( overlay - .changes() + .changes_mut() .map(|(k, v)| (k.clone(), v.value().cloned())) .collect::>(), map![ @@ -1340,7 +1342,7 @@ mod tests { assert_eq!( overlay - .children() + .children_mut() .flat_map(|(iter, _child_info)| iter) .map(|(k, v)| (k.clone(), v.value())) .collect::>(), @@ -1440,11 +1442,78 @@ mod tests { } overlay.rollback_transaction().unwrap(); { - let ext = Ext::new(&mut overlay, backend, None); + let mut ext = Ext::new(&mut overlay, backend, None); assert_eq!(ext.storage(key.as_slice()), Some(vec![reference_data[0].clone()].encode())); } } + // Test that we can append twice to a key, then perform a remove operation. + // The test checks specifically that the append is merged with its parent transaction + // on commit. + #[test] + fn commit_merges_append_with_parent() { + #[derive(codec::Encode, codec::Decode)] + enum Item { + Item1, + Item2, + } + + let key = b"events".to_vec(); + let state = new_in_mem::(); + let backend = state.as_trie_backend(); + let mut overlay = OverlayedChanges::default(); + + // Append first item + overlay.start_transaction(); + { + let mut ext = Ext::new(&mut overlay, backend, None); + ext.clear_storage(key.as_slice()); + ext.storage_append(key.clone(), Item::Item1.encode()); + } + + // Append second item + overlay.start_transaction(); + { + let mut ext = Ext::new(&mut overlay, backend, None); + + assert_eq!(ext.storage(key.as_slice()), Some(vec![Item::Item1].encode())); + + ext.storage_append(key.clone(), Item::Item2.encode()); + + assert_eq!(ext.storage(key.as_slice()), Some(vec![Item::Item1, Item::Item2].encode()),); + } + + // Remove item + overlay.start_transaction(); + { + let mut ext = Ext::new(&mut overlay, backend, None); + + ext.place_storage(key.clone(), None); + + assert_eq!(ext.storage(key.as_slice()), None); + } + + // Remove gets commited and merged into previous transaction + overlay.commit_transaction().unwrap(); + { + let mut ext = Ext::new(&mut overlay, backend, None); + assert_eq!(ext.storage(key.as_slice()), None,); + } + + // Remove gets rolled back, we should see the initial append again. + overlay.rollback_transaction().unwrap(); + { + let mut ext = Ext::new(&mut overlay, backend, None); + assert_eq!(ext.storage(key.as_slice()), Some(vec![Item::Item1].encode())); + } + + overlay.commit_transaction().unwrap(); + { + let mut ext = Ext::new(&mut overlay, backend, None); + assert_eq!(ext.storage(key.as_slice()), Some(vec![Item::Item1].encode())); + } + } + #[test] fn remove_with_append_then_rollback_appended_then_append_again() { #[derive(codec::Encode, codec::Decode)] @@ -1499,7 +1568,7 @@ mod tests { // Then only initialization item and second (committed) item should persist. { - let ext = Ext::new(&mut overlay, backend, None); + let mut ext = Ext::new(&mut overlay, backend, None); assert_eq!( ext.storage(key.as_slice()), Some(vec![Item::InitializationItem, Item::CommittedItem].encode()), diff --git a/substrate/primitives/state-machine/src/overlayed_changes/changeset.rs b/substrate/primitives/state-machine/src/overlayed_changes/changeset.rs index 601bc2e29198561d501e1f20b11c2323c0064989..c478983e979af440a409199934c641eb01492675 100644 --- a/substrate/primitives/state-machine/src/overlayed_changes/changeset.rs +++ b/substrate/primitives/state-machine/src/overlayed_changes/changeset.rs @@ -21,11 +21,15 @@ use super::{Extrinsics, StorageKey, StorageValue}; #[cfg(not(feature = "std"))] use alloc::collections::btree_set::BTreeSet as Set; +use codec::{Compact, CompactLen}; #[cfg(feature = "std")] use std::collections::HashSet as Set; -use crate::warn; -use alloc::collections::{btree_map::BTreeMap, btree_set::BTreeSet}; +use crate::{ext::StorageAppend, warn}; +use alloc::{ + collections::{btree_map::BTreeMap, btree_set::BTreeSet}, + vec::Vec, +}; use core::hash::Hash; use smallvec::SmallVec; @@ -86,10 +90,97 @@ impl Default for OverlayedEntry { } /// History of value, with removal support. -pub type OverlayedValue = OverlayedEntry>; +pub type OverlayedValue = OverlayedEntry; + +/// Content in an overlay for a given transactional depth. +#[derive(Debug, Clone, Default)] +#[cfg_attr(test, derive(PartialEq))] +pub enum StorageEntry { + /// The storage entry should be set to the stored value. + Set(StorageValue), + /// The storage entry should be removed. + #[default] + Remove, + /// The storage entry was appended to. + /// + /// This assumes that the storage entry is encoded as a SCALE list. This means that it is + /// prefixed with a `Compact` that reprensents the length, followed by all the encoded + /// elements. + Append { + /// The value of the storage entry. + /// + /// This may or may not be prefixed by the length, depending on the materialized length. + data: StorageValue, + /// Current number of elements stored in data. + current_length: u32, + /// The number of elements as stored in the prefixed length in `data`. + /// + /// If `None`, than `data` is not yet prefixed with the length. + materialized_length: Option, + /// The size of `data` in the parent transactional layer. + /// + /// Only set when the parent layer is in `Append` state. + parent_size: Option, + }, +} + +impl StorageEntry { + /// Convert to an [`Option`]. + pub(super) fn to_option(mut self) -> Option { + self.materialize_in_place(); + match self { + StorageEntry::Append { data, .. } | StorageEntry::Set(data) => Some(data), + StorageEntry::Remove => None, + } + } + + /// Return as an [`Option`]. + fn as_option(&mut self) -> Option<&StorageValue> { + self.materialize_in_place(); + match self { + StorageEntry::Append { data, .. } | StorageEntry::Set(data) => Some(data), + StorageEntry::Remove => None, + } + } + + /// Materialize the internal state and cache the resulting materialized value. + fn materialize_in_place(&mut self) { + if let StorageEntry::Append { data, materialized_length, current_length, .. } = self { + let current_length = *current_length; + if materialized_length.map_or(false, |m| m == current_length) { + return + } + StorageAppend::new(data).replace_length(*materialized_length, current_length); + *materialized_length = Some(current_length); + } + } + + /// Materialize the internal state. + #[cfg(test)] + pub(crate) fn materialize(&self) -> Option> { + use alloc::borrow::Cow; + + match self { + StorageEntry::Append { data, materialized_length, current_length, .. } => { + let current_length = *current_length; + if materialized_length.map_or(false, |m| m == current_length) { + Some(Cow::Borrowed(data.as_ref())) + } else { + let mut data = data.clone(); + StorageAppend::new(&mut data) + .replace_length(*materialized_length, current_length); + + Some(data.into()) + } + }, + StorageEntry::Remove => None, + StorageEntry::Set(e) => Some(Cow::Borrowed(e.as_ref())), + } + } +} /// Change set for basic key value with extrinsics index recording and removal support. -pub type OverlayedChangeSet = OverlayedMap>; +pub type OverlayedChangeSet = OverlayedMap; /// Holds a set of changes with the ability modify them using nested transactions. #[derive(Debug, Clone)] @@ -120,7 +211,7 @@ impl Default for OverlayedMap { } #[cfg(feature = "std")] -impl From for OverlayedMap> { +impl From for OverlayedMap { fn from(storage: sp_core::storage::StorageMap) -> Self { Self { changes: storage @@ -130,7 +221,7 @@ impl From for OverlayedMap OverlayedEntry { /// /// This makes sure that the old version is not overwritten and can be properly /// rolled back when required. - fn set(&mut self, value: V, first_write_in_tx: bool, at_extrinsic: Option) { + fn set_offchain(&mut self, value: V, first_write_in_tx: bool, at_extrinsic: Option) { if first_write_in_tx || self.transactions.is_empty() { self.transactions.push(InnerValue { value, extrinsics: Default::default() }); } else { @@ -202,10 +293,223 @@ impl OverlayedEntry { } } -impl OverlayedEntry> { +/// Restore the `current_data` from an [`StorageEntry::Append`] back to the parent. +/// +/// When creating a new transaction layer from an appended entry, the `data` will be moved to +/// prevent extra allocations. So, we need to move back the `data` to the parent layer when there is +/// a roll back or the entry is set to some different value. This functions puts back the data to +/// the `parent` and truncates any extra elements that got added in the current layer. +/// +/// The current and the `parent` layer need to be [`StorageEntry::Append`] or otherwise the function +/// is a no-op. +fn restore_append_to_parent( + parent: &mut StorageEntry, + mut current_data: Vec, + current_materialized: Option, + mut target_parent_size: usize, +) { + match parent { + StorageEntry::Append { + data: parent_data, + materialized_length: parent_materialized, + .. + } => { + // Forward the materialized length to the parent with the data. Next time when + // materializing the value, the length will be corrected. This prevents doing a + // potential allocation here. + + let prev = parent_materialized.map(|l| Compact::::compact_len(&l)).unwrap_or(0); + let new = current_materialized.map(|l| Compact::::compact_len(&l)).unwrap_or(0); + let delta = new.abs_diff(prev); + if prev >= new { + target_parent_size -= delta; + } else { + target_parent_size += delta; + } + *parent_materialized = current_materialized; + + // Truncate the data to remove any extra elements + current_data.truncate(target_parent_size); + *parent_data = current_data; + }, + _ => { + // No value or a simple value, no need to restore + }, + } +} + +impl OverlayedEntry { + /// Writes a new version of a value. + /// + /// This makes sure that the old version is not overwritten and can be properly + /// rolled back when required. + fn set( + &mut self, + value: Option, + first_write_in_tx: bool, + at_extrinsic: Option, + ) { + let value = value.map_or_else(|| StorageEntry::Remove, StorageEntry::Set); + + if first_write_in_tx || self.transactions.is_empty() { + self.transactions.push(InnerValue { value, extrinsics: Default::default() }); + } else { + let mut old_value = self.value_mut(); + + let set_prev = if let StorageEntry::Append { + data, + current_length: _, + materialized_length, + parent_size, + } = &mut old_value + { + parent_size + .map(|parent_size| (core::mem::take(data), *materialized_length, parent_size)) + } else { + None + }; + + *old_value = value; + + if let Some((data, current_materialized, parent_size)) = set_prev { + let transactions = self.transactions.len(); + + debug_assert!(transactions >= 2); + let parent = self + .transactions + .get_mut(transactions - 2) + .expect("`set_prev` is only `Some(_)`, if the value came from parent; qed"); + restore_append_to_parent( + &mut parent.value, + data, + current_materialized, + parent_size, + ); + } + } + + if let Some(extrinsic) = at_extrinsic { + self.transaction_extrinsics_mut().insert(extrinsic); + } + } + + /// Append content to a value, updating a prefixed compact encoded length. + /// + /// This makes sure that the old version is not overwritten and can be properly + /// rolled back when required. + /// This avoid copying value from previous transaction. + fn append( + &mut self, + element: StorageValue, + first_write_in_tx: bool, + init: impl Fn() -> StorageValue, + at_extrinsic: Option, + ) { + if self.transactions.is_empty() { + let mut init_value = init(); + + let mut append = StorageAppend::new(&mut init_value); + + // Either the init value is a SCALE list like value to that the `element` gets appended + // or the value is reset to `[element]`. + let (data, current_length, materialized_length) = + if let Some(len) = append.extract_length() { + append.append_raw(element); + + (init_value, len + 1, Some(len)) + } else { + (element, 1, None) + }; + + self.transactions.push(InnerValue { + value: StorageEntry::Append { + data, + current_length, + materialized_length, + parent_size: None, + }, + extrinsics: Default::default(), + }); + } else if first_write_in_tx { + let parent = self.value_mut(); + let (data, current_length, materialized_length, parent_size) = match parent { + StorageEntry::Remove => (element, 1, None, None), + StorageEntry::Append { data, current_length, materialized_length, .. } => { + let parent_len = data.len(); + let mut data_buf = core::mem::take(data); + StorageAppend::new(&mut data_buf).append_raw(element); + (data_buf, *current_length + 1, *materialized_length, Some(parent_len)) + }, + StorageEntry::Set(prev) => { + // For compatibility: append if there is a encoded length, overwrite + // with value otherwhise. + if let Some(current_length) = StorageAppend::new(prev).extract_length() { + // The `prev` is cloned here, but it could be optimized to not do the clone + // here as it is done for `Append` above. + let mut data = prev.clone(); + StorageAppend::new(&mut data).append_raw(element); + (data, current_length + 1, Some(current_length), None) + } else { + // overwrite, same as empty case. + (element, 1, None, None) + } + }, + }; + + self.transactions.push(InnerValue { + value: StorageEntry::Append { + data, + current_length, + materialized_length, + parent_size, + }, + extrinsics: Default::default(), + }); + } else { + // not first transaction write + let old_value = self.value_mut(); + let replace = match old_value { + StorageEntry::Remove => Some((element, 1, None)), + StorageEntry::Set(data) => { + // Note that when the data here is not initialized with append, + // and still starts with a valid compact u32 we can have totally broken + // encoding. + let mut append = StorageAppend::new(data); + + // For compatibility: append if there is a encoded length, overwrite + // with value otherwhise. + if let Some(current_length) = append.extract_length() { + append.append_raw(element); + Some((core::mem::take(data), current_length + 1, Some(current_length))) + } else { + Some((element, 1, None)) + } + }, + StorageEntry::Append { data, current_length, .. } => { + StorageAppend::new(data).append_raw(element); + *current_length += 1; + None + }, + }; + + if let Some((data, current_length, materialized_length)) = replace { + *old_value = StorageEntry::Append { + data, + current_length, + materialized_length, + parent_size: None, + }; + } + } + + if let Some(extrinsic) = at_extrinsic { + self.transaction_extrinsics_mut().insert(extrinsic); + } + } + /// The value as seen by the current transaction. - pub fn value(&self) -> Option<&StorageValue> { - self.value_ref().as_ref() + pub fn value(&mut self) -> Option<&StorageValue> { + self.value_mut().as_option() } } @@ -238,20 +542,20 @@ impl OverlayedMap { } /// Get an optional reference to the value stored for the specified key. - pub fn get(&self, key: &Q) -> Option<&OverlayedEntry> + pub fn get(&mut self, key: &Q) -> Option<&mut OverlayedEntry> where K: core::borrow::Borrow, Q: Ord + ?Sized, { - self.changes.get(key) + self.changes.get_mut(key) } /// Set a new value for the specified key. /// /// Can be rolled back or committed when called inside a transaction. - pub fn set(&mut self, key: K, value: V, at_extrinsic: Option) { + pub fn set_offchain(&mut self, key: K, value: V, at_extrinsic: Option) { let overlayed = self.changes.entry(key.clone()).or_default(); - overlayed.set(value, insert_dirty(&mut self.dirty_keys, key), at_extrinsic); + overlayed.set_offchain(value, insert_dirty(&mut self.dirty_keys, key), at_extrinsic); } /// Get a list of all changes as seen by current transaction. @@ -259,6 +563,11 @@ impl OverlayedMap { self.changes.iter() } + /// Get a list of all changes as seen by current transaction. + pub fn changes_mut(&mut self) -> impl Iterator)> { + self.changes.iter_mut() + } + /// Get a list of all changes as seen by current transaction, consumes /// the overlay. pub fn into_changes(self) -> impl Iterator)> { @@ -298,7 +607,7 @@ impl OverlayedMap { /// /// This rollbacks all dangling transaction left open by the runtime. /// Calling this while already outside the runtime will return an error. - pub fn exit_runtime(&mut self) -> Result<(), NotInRuntime> { + pub fn exit_runtime_offchain(&mut self) -> Result<(), NotInRuntime> { if let ExecutionMode::Client = self.execution_mode { return Err(NotInRuntime) } @@ -310,7 +619,7 @@ impl OverlayedMap { ); } while self.has_open_runtime_transactions() { - self.rollback_transaction() + self.rollback_transaction_offchain() .expect("The loop condition checks that the transaction depth is > 0; qed"); } Ok(()) @@ -331,24 +640,24 @@ impl OverlayedMap { /// /// Any changes made during that transaction are discarded. Returns an error if /// there is no open transaction that can be rolled back. - pub fn rollback_transaction(&mut self) -> Result<(), NoOpenTransaction> { - self.close_transaction(true) + pub fn rollback_transaction_offchain(&mut self) -> Result<(), NoOpenTransaction> { + self.close_transaction_offchain(true) } /// Commit the last transaction started by `start_transaction`. /// /// Any changes made during that transaction are committed. Returns an error if /// there is no open transaction that can be committed. - pub fn commit_transaction(&mut self) -> Result<(), NoOpenTransaction> { - self.close_transaction(false) + pub fn commit_transaction_offchain(&mut self) -> Result<(), NoOpenTransaction> { + self.close_transaction_offchain(false) } - fn close_transaction(&mut self, rollback: bool) -> Result<(), NoOpenTransaction> { + fn close_transaction_offchain(&mut self, rollback: bool) -> Result<(), NoOpenTransaction> { // runtime is not allowed to close transactions started by the client - if let ExecutionMode::Runtime = self.execution_mode { - if !self.has_open_runtime_transactions() { - return Err(NoOpenTransaction) - } + if matches!(self.execution_mode, ExecutionMode::Runtime) && + !self.has_open_runtime_transactions() + { + return Err(NoOpenTransaction) } for key in self.dirty_keys.pop().ok_or(NoOpenTransaction)? { @@ -398,32 +707,176 @@ impl OverlayedMap { } impl OverlayedChangeSet { - /// Get a mutable reference for a value. + /// Rollback the last transaction started by `start_transaction`. + /// + /// Any changes made during that transaction are discarded. Returns an error if + /// there is no open transaction that can be rolled back. + pub fn rollback_transaction(&mut self) -> Result<(), NoOpenTransaction> { + self.close_transaction(true) + } + + /// Commit the last transaction started by `start_transaction`. + /// + /// Any changes made during that transaction are committed. Returns an error if + /// there is no open transaction that can be committed. + pub fn commit_transaction(&mut self) -> Result<(), NoOpenTransaction> { + self.close_transaction(false) + } + + fn close_transaction(&mut self, rollback: bool) -> Result<(), NoOpenTransaction> { + // runtime is not allowed to close transactions started by the client + if matches!(self.execution_mode, ExecutionMode::Runtime) && + !self.has_open_runtime_transactions() + { + return Err(NoOpenTransaction) + } + + for key in self.dirty_keys.pop().ok_or(NoOpenTransaction)? { + let overlayed = self.changes.get_mut(&key).expect( + "\ + A write to an OverlayedValue is recorded in the dirty key set. Before an + OverlayedValue is removed, its containing dirty set is removed. This + function is only called for keys that are in the dirty set. qed\ + ", + ); + + if rollback { + match overlayed.pop_transaction().value { + StorageEntry::Append { + data, + materialized_length, + parent_size: Some(parent_size), + .. + } => { + debug_assert!(!overlayed.transactions.is_empty()); + restore_append_to_parent( + overlayed.value_mut(), + data, + materialized_length, + parent_size, + ); + }, + _ => (), + } + + // We need to remove the key as an `OverlayValue` with no transactions + // violates its invariant of always having at least one transaction. + if overlayed.transactions.is_empty() { + self.changes.remove(&key); + } + } else { + let has_predecessor = if let Some(dirty_keys) = self.dirty_keys.last_mut() { + // Not the last tx: Did the previous tx write to this key? + !dirty_keys.insert(key) + } else { + // Last tx: Is there already a value in the committed set? + // Check against one rather than empty because the current tx is still + // in the list as it is popped later in this function. + overlayed.transactions.len() > 1 + }; + + // We only need to merge if there is an pre-existing value. It may be a value from + // the previous transaction or a value committed without any open transaction. + if has_predecessor { + let mut committed_tx = overlayed.pop_transaction(); + let mut merge_appends = false; + + // consecutive appends need to keep past `parent_size` value. + if let StorageEntry::Append { parent_size, .. } = &mut committed_tx.value { + if parent_size.is_some() { + let parent = overlayed.value_mut(); + if let StorageEntry::Append { parent_size: keep_me, .. } = parent { + merge_appends = true; + *parent_size = *keep_me; + } + } + } + + if merge_appends { + *overlayed.value_mut() = committed_tx.value; + } else { + let removed = core::mem::replace(overlayed.value_mut(), committed_tx.value); + // The transaction being commited is not an append operation. However, the + // value being overwritten in the previous transaction might be an append + // that needs to be merged with its parent. We only need to handle `Append` + // here because `Set` and `Remove` can directly overwrite previous + // operations. + if let StorageEntry::Append { + parent_size, data, materialized_length, .. + } = removed + { + if let Some(parent_size) = parent_size { + let transactions = overlayed.transactions.len(); + + // info from replaced head so len is at least one + // and parent_size implies a parent transaction + // so length is at least two. + debug_assert!(transactions >= 2); + if let Some(parent) = + overlayed.transactions.get_mut(transactions - 2) + { + restore_append_to_parent( + &mut parent.value, + data, + materialized_length, + parent_size, + ) + } + } + } + } + + overlayed.transaction_extrinsics_mut().extend(committed_tx.extrinsics); + } + } + } + + Ok(()) + } + + /// Call this when control returns from the runtime. + /// + /// This commits all dangling transaction left open by the runtime. + /// Calling this while already outside the runtime will return an error. + pub fn exit_runtime(&mut self) -> Result<(), NotInRuntime> { + if matches!(self.execution_mode, ExecutionMode::Client) { + return Err(NotInRuntime) + } + + self.execution_mode = ExecutionMode::Client; + if self.has_open_runtime_transactions() { + warn!( + "{} storage transactions are left open by the runtime. Those will be rolled back.", + self.transaction_depth() - self.num_client_transactions, + ); + } + while self.has_open_runtime_transactions() { + self.rollback_transaction() + .expect("The loop condition checks that the transaction depth is > 0; qed"); + } + + Ok(()) + } + + /// Set a new value for the specified key. /// /// Can be rolled back or committed when called inside a transaction. - #[must_use = "A change was registered, so this value MUST be modified."] - pub fn modify( + pub fn set(&mut self, key: StorageKey, value: Option, at_extrinsic: Option) { + let overlayed = self.changes.entry(key.clone()).or_default(); + overlayed.set(value, insert_dirty(&mut self.dirty_keys, key), at_extrinsic); + } + + /// Append bytes to an existing content. + pub fn append_storage( &mut self, key: StorageKey, + value: StorageValue, init: impl Fn() -> StorageValue, at_extrinsic: Option, - ) -> &mut Option { + ) { let overlayed = self.changes.entry(key.clone()).or_default(); let first_write_in_tx = insert_dirty(&mut self.dirty_keys, key); - let clone_into_new_tx = if let Some(tx) = overlayed.transactions.last() { - if first_write_in_tx { - Some(tx.value.clone()) - } else { - None - } - } else { - Some(Some(init())) - }; - - if let Some(cloned) = clone_into_new_tx { - overlayed.set(cloned, first_write_in_tx, at_extrinsic); - } - overlayed.value_mut() + overlayed.append(value, first_write_in_tx, init, at_extrinsic); } /// Set all values to deleted which are matched by the predicate. @@ -436,7 +889,7 @@ impl OverlayedChangeSet { ) -> u32 { let mut count = 0; for (key, val) in self.changes.iter_mut().filter(|(k, v)| predicate(k, v)) { - if val.value_ref().is_some() { + if matches!(val.value_ref(), StorageEntry::Set(..) | StorageEntry::Append { .. }) { count += 1; } val.set(None, insert_dirty(&mut self.dirty_keys, key.clone()), at_extrinsic); @@ -445,10 +898,13 @@ impl OverlayedChangeSet { } /// Get the iterator over all changes that follow the supplied `key`. - pub fn changes_after(&self, key: &[u8]) -> impl Iterator { + pub fn changes_after( + &mut self, + key: &[u8], + ) -> impl Iterator { use core::ops::Bound; let range = (Bound::Excluded(key), Bound::Unbounded); - self.changes.range::<[u8], _>(range).map(|(k, v)| (k.as_slice(), v)) + self.changes.range_mut::<[u8], _>(range).map(|(k, v)| (k.as_slice(), v)) } } @@ -460,18 +916,19 @@ mod test { type Changes<'a> = Vec<(&'a [u8], (Option<&'a [u8]>, Vec))>; type Drained<'a> = Vec<(&'a [u8], Option<&'a [u8]>)>; - fn assert_changes(is: &OverlayedChangeSet, expected: &Changes) { + fn assert_changes(is: &mut OverlayedChangeSet, expected: &Changes) { let is: Changes = is - .changes() + .changes_mut() .map(|(k, v)| { - (k.as_ref(), (v.value().map(AsRef::as_ref), v.extrinsics().into_iter().collect())) + let extrinsics = v.extrinsics().into_iter().collect(); + (k.as_ref(), (v.value().map(AsRef::as_ref), extrinsics)) }) .collect(); assert_eq!(&is, expected); } fn assert_drained_changes(is: OverlayedChangeSet, expected: Changes) { - let is = is.drain_committed().collect::>(); + let is = is.drain_committed().map(|(k, v)| (k, v.to_option())).collect::>(); let expected = expected .iter() .map(|(k, v)| (k.to_vec(), v.0.map(From::from))) @@ -480,7 +937,7 @@ mod test { } fn assert_drained(is: OverlayedChangeSet, expected: Drained) { - let is = is.drain_committed().collect::>(); + let is = is.drain_committed().map(|(k, v)| (k, v.to_option())).collect::>(); let expected = expected .iter() .map(|(k, v)| (k.to_vec(), v.map(From::from))) @@ -535,7 +992,7 @@ mod test { (b"key7", (Some(b"val7-rolled"), vec![77])), (b"key99", (Some(b"val99"), vec![99])), ]; - assert_changes(&changeset, &all_changes); + assert_changes(&mut changeset, &all_changes); // this should be no-op changeset.start_transaction(); @@ -546,7 +1003,7 @@ mod test { assert_eq!(changeset.transaction_depth(), 3); changeset.commit_transaction().unwrap(); assert_eq!(changeset.transaction_depth(), 2); - assert_changes(&changeset, &all_changes); + assert_changes(&mut changeset, &all_changes); // roll back our first transactions that actually contains something changeset.rollback_transaction().unwrap(); @@ -558,11 +1015,11 @@ mod test { (b"key42", (Some(b"val42"), vec![42])), (b"key99", (Some(b"val99"), vec![99])), ]; - assert_changes(&changeset, &rolled_back); + assert_changes(&mut changeset, &rolled_back); changeset.commit_transaction().unwrap(); assert_eq!(changeset.transaction_depth(), 0); - assert_changes(&changeset, &rolled_back); + assert_changes(&mut changeset, &rolled_back); assert_drained_changes(changeset, rolled_back); } @@ -598,7 +1055,7 @@ mod test { (b"key7", (Some(b"val7-rolled"), vec![77])), (b"key99", (Some(b"val99"), vec![99])), ]; - assert_changes(&changeset, &all_changes); + assert_changes(&mut changeset, &all_changes); // this should be no-op changeset.start_transaction(); @@ -609,35 +1066,46 @@ mod test { assert_eq!(changeset.transaction_depth(), 3); changeset.commit_transaction().unwrap(); assert_eq!(changeset.transaction_depth(), 2); - assert_changes(&changeset, &all_changes); + assert_changes(&mut changeset, &all_changes); changeset.commit_transaction().unwrap(); assert_eq!(changeset.transaction_depth(), 1); - assert_changes(&changeset, &all_changes); + assert_changes(&mut changeset, &all_changes); changeset.rollback_transaction().unwrap(); assert_eq!(changeset.transaction_depth(), 0); let rolled_back: Changes = vec![(b"key0", (Some(b"val0-1"), vec![1, 10])), (b"key1", (Some(b"val1"), vec![1]))]; - assert_changes(&changeset, &rolled_back); + assert_changes(&mut changeset, &rolled_back); assert_drained_changes(changeset, rolled_back); } #[test] - fn modify_works() { + fn append_works() { + use codec::Encode; let mut changeset = OverlayedChangeSet::default(); assert_eq!(changeset.transaction_depth(), 0); - let init = || b"valinit".to_vec(); + let init = || vec![b"valinit".to_vec()].encode(); // committed set - changeset.set(b"key0".to_vec(), Some(b"val0".to_vec()), Some(0)); + let val0 = vec![b"val0".to_vec()].encode(); + changeset.set(b"key0".to_vec(), Some(val0.clone()), Some(0)); changeset.set(b"key1".to_vec(), None, Some(1)); - let val = changeset.modify(b"key3".to_vec(), init, Some(3)); - assert_eq!(val, &Some(b"valinit".to_vec())); - val.as_mut().unwrap().extend_from_slice(b"-modified"); + let all_changes: Changes = + vec![(b"key0", (Some(val0.as_slice()), vec![0])), (b"key1", (None, vec![1]))]; + + assert_changes(&mut changeset, &all_changes); + changeset.append_storage(b"key3".to_vec(), b"-modified".to_vec().encode(), init, Some(3)); + let val3 = vec![b"valinit".to_vec(), b"-modified".to_vec()].encode(); + let all_changes: Changes = vec![ + (b"key0", (Some(val0.as_slice()), vec![0])), + (b"key1", (None, vec![1])), + (b"key3", (Some(val3.as_slice()), vec![3])), + ]; + assert_changes(&mut changeset, &all_changes); changeset.start_transaction(); assert_eq!(changeset.transaction_depth(), 1); @@ -645,39 +1113,75 @@ mod test { assert_eq!(changeset.transaction_depth(), 2); // non existing value -> init value should be returned - let val = changeset.modify(b"key2".to_vec(), init, Some(2)); - assert_eq!(val, &Some(b"valinit".to_vec())); - val.as_mut().unwrap().extend_from_slice(b"-modified"); + changeset.append_storage(b"key3".to_vec(), b"-twice".to_vec().encode(), init, Some(15)); - // existing value should be returned by modify - let val = changeset.modify(b"key0".to_vec(), init, Some(10)); - assert_eq!(val, &Some(b"val0".to_vec())); - val.as_mut().unwrap().extend_from_slice(b"-modified"); + // non existing value -> init value should be returned + changeset.append_storage(b"key2".to_vec(), b"-modified".to_vec().encode(), init, Some(2)); + // existing value should be reuse on append + changeset.append_storage(b"key0".to_vec(), b"-modified".to_vec().encode(), init, Some(10)); // should work for deleted keys - let val = changeset.modify(b"key1".to_vec(), init, Some(20)); - assert_eq!(val, &None); - *val = Some(b"deleted-modified".to_vec()); + changeset.append_storage( + b"key1".to_vec(), + b"deleted-modified".to_vec().encode(), + init, + Some(20), + ); + let val0_2 = vec![b"val0".to_vec(), b"-modified".to_vec()].encode(); + let val3_2 = vec![b"valinit".to_vec(), b"-modified".to_vec(), b"-twice".to_vec()].encode(); + let val1 = vec![b"deleted-modified".to_vec()].encode(); + let all_changes: Changes = vec![ + (b"key0", (Some(val0_2.as_slice()), vec![0, 10])), + (b"key1", (Some(val1.as_slice()), vec![1, 20])), + (b"key2", (Some(val3.as_slice()), vec![2])), + (b"key3", (Some(val3_2.as_slice()), vec![3, 15])), + ]; + assert_changes(&mut changeset, &all_changes); + + changeset.start_transaction(); + let val3_3 = + vec![b"valinit".to_vec(), b"-modified".to_vec(), b"-twice".to_vec(), b"-2".to_vec()] + .encode(); + changeset.append_storage(b"key3".to_vec(), b"-2".to_vec().encode(), init, Some(21)); + let all_changes2: Changes = vec![ + (b"key0", (Some(val0_2.as_slice()), vec![0, 10])), + (b"key1", (Some(val1.as_slice()), vec![1, 20])), + (b"key2", (Some(val3.as_slice()), vec![2])), + (b"key3", (Some(val3_3.as_slice()), vec![3, 15, 21])), + ]; + assert_changes(&mut changeset, &all_changes2); + changeset.rollback_transaction().unwrap(); + assert_changes(&mut changeset, &all_changes); + changeset.start_transaction(); + let val3_4 = vec![ + b"valinit".to_vec(), + b"-modified".to_vec(), + b"-twice".to_vec(), + b"-thrice".to_vec(), + ] + .encode(); + changeset.append_storage(b"key3".to_vec(), b"-thrice".to_vec().encode(), init, Some(25)); let all_changes: Changes = vec![ - (b"key0", (Some(b"val0-modified"), vec![0, 10])), - (b"key1", (Some(b"deleted-modified"), vec![1, 20])), - (b"key2", (Some(b"valinit-modified"), vec![2])), - (b"key3", (Some(b"valinit-modified"), vec![3])), + (b"key0", (Some(val0_2.as_slice()), vec![0, 10])), + (b"key1", (Some(val1.as_slice()), vec![1, 20])), + (b"key2", (Some(val3.as_slice()), vec![2])), + (b"key3", (Some(val3_4.as_slice()), vec![3, 15, 25])), ]; - assert_changes(&changeset, &all_changes); + assert_changes(&mut changeset, &all_changes); + changeset.commit_transaction().unwrap(); changeset.commit_transaction().unwrap(); assert_eq!(changeset.transaction_depth(), 1); - assert_changes(&changeset, &all_changes); + assert_changes(&mut changeset, &all_changes); changeset.rollback_transaction().unwrap(); assert_eq!(changeset.transaction_depth(), 0); let rolled_back: Changes = vec![ - (b"key0", (Some(b"val0"), vec![0])), + (b"key0", (Some(val0.as_slice()), vec![0])), (b"key1", (None, vec![1])), - (b"key3", (Some(b"valinit-modified"), vec![3])), + (b"key3", (Some(val3.as_slice()), vec![3])), ]; - assert_changes(&changeset, &rolled_back); + assert_changes(&mut changeset, &rolled_back); assert_drained_changes(changeset, rolled_back); } @@ -695,7 +1199,7 @@ mod test { changeset.clear_where(|k, _| k.starts_with(b"del"), Some(5)); assert_changes( - &changeset, + &mut changeset, &vec![ (b"del1", (None, vec![3, 5])), (b"del2", (None, vec![4, 5])), @@ -707,7 +1211,7 @@ mod test { changeset.rollback_transaction().unwrap(); assert_changes( - &changeset, + &mut changeset, &vec![ (b"del1", (Some(b"delval1"), vec![3])), (b"del2", (Some(b"delval2"), vec![4])), @@ -850,4 +1354,72 @@ mod test { assert_eq!(changeset.exit_runtime(), Ok(())); assert_eq!(changeset.exit_runtime(), Err(NotInRuntime)); } + + #[test] + fn restore_append_to_parent() { + use codec::{Compact, Encode}; + let mut changeset = OverlayedChangeSet::default(); + let key: Vec = b"akey".into(); + + let from = 50; // 1 byte len + let to = 100; // 2 byte len + for i in 0..from { + changeset.append_storage(key.clone(), vec![i], Default::default, None); + } + + // materialized + let encoded = changeset.get(&key).unwrap().value().unwrap(); + let encoded_from_len = Compact(from as u32).encode(); + assert_eq!(encoded_from_len.len(), 1); + assert!(encoded.starts_with(&encoded_from_len[..])); + let encoded_from = encoded.clone(); + + changeset.start_transaction(); + + for i in from..to { + changeset.append_storage(key.clone(), vec![i], Default::default, None); + } + + // materialized + let encoded = changeset.get(&key).unwrap().value().unwrap(); + let encoded_to_len = Compact(to as u32).encode(); + assert_eq!(encoded_to_len.len(), 2); + assert!(encoded.starts_with(&encoded_to_len[..])); + + changeset.rollback_transaction().unwrap(); + + let encoded = changeset.get(&key).unwrap().value().unwrap(); + assert_eq!(&encoded_from, encoded); + } + + /// First we have some `Set` operation with a valid SCALE list. Then we append data and rollback + /// afterwards. + #[test] + fn restore_initial_set_after_append_to_parent() { + use codec::{Compact, Encode}; + let mut changeset = OverlayedChangeSet::default(); + let key: Vec = b"akey".into(); + + let initial_data = vec![1u8; 50].encode(); + + changeset.set(key.clone(), Some(initial_data.clone()), None); + + changeset.start_transaction(); + + // Append until we require 2 bytes for the length prefix. + for i in 0..50 { + changeset.append_storage(key.clone(), vec![i], Default::default, None); + } + + // Materialize the value. + let encoded = changeset.get(&key).unwrap().value().unwrap(); + let encoded_to_len = Compact(100u32).encode(); + assert_eq!(encoded_to_len.len(), 2); + assert!(encoded.starts_with(&encoded_to_len[..])); + + changeset.rollback_transaction().unwrap(); + + let encoded = changeset.get(&key).unwrap().value().unwrap(); + assert_eq!(&initial_data, encoded); + } } diff --git a/substrate/primitives/state-machine/src/overlayed_changes/mod.rs b/substrate/primitives/state-machine/src/overlayed_changes/mod.rs index d6fc404e84fb5256656c5849d8f52894f37bfa02..c2dc637bc71a70dbef3a55abf658dbd1dd889db5 100644 --- a/substrate/primitives/state-machine/src/overlayed_changes/mod.rs +++ b/substrate/primitives/state-machine/src/overlayed_changes/mod.rs @@ -289,7 +289,7 @@ impl OverlayedChanges { /// Returns a double-Option: None if the key is unknown (i.e. and the query should be referred /// to the backend); Some(None) if the key has been deleted. Some(Some(...)) for a key whose /// value has been set. - pub fn storage(&self, key: &[u8]) -> Option> { + pub fn storage(&mut self, key: &[u8]) -> Option> { self.top.get(key).map(|x| { let value = x.value(); let size_read = value.map(|x| x.len() as u64).unwrap_or(0); @@ -304,30 +304,11 @@ impl OverlayedChanges { self.storage_transaction_cache = None; } - /// Returns mutable reference to current value. - /// If there is no value in the overlay, the given callback is used to initiate the value. - /// Warning this function registers a change, so the mutable reference MUST be modified. - /// - /// Can be rolled back or committed when called inside a transaction. - #[must_use = "A change was registered, so this value MUST be modified."] - pub fn value_mut_or_insert_with( - &mut self, - key: &[u8], - init: impl Fn() -> StorageValue, - ) -> &mut StorageValue { - self.mark_dirty(); - - let value = self.top.modify(key.to_vec(), init, self.extrinsic_index()); - - // if the value was deleted initialise it back with an empty vec - value.get_or_insert_with(StorageValue::default) - } - /// Returns a double-Option: None if the key is unknown (i.e. and the query should be referred /// to the backend); Some(None) if the key has been deleted. Some(Some(...)) for a key whose /// value has been set. - pub fn child_storage(&self, child_info: &ChildInfo, key: &[u8]) -> Option> { - let map = self.children.get(child_info.storage_key())?; + pub fn child_storage(&mut self, child_info: &ChildInfo, key: &[u8]) -> Option> { + let map = self.children.get_mut(child_info.storage_key())?; let value = map.0.get(key)?.value(); let size_read = value.map(|x| x.len() as u64).unwrap_or(0); self.stats.tally_read_modified(size_read); @@ -342,7 +323,21 @@ impl OverlayedChanges { let size_write = val.as_ref().map(|x| x.len() as u64).unwrap_or(0); self.stats.tally_write_overlay(size_write); - self.top.set(key, val, self.extrinsic_index()); + let extrinsic_index = self.extrinsic_index(); + self.top.set(key, val, extrinsic_index); + } + + /// Append a element to storage, init with existing value if first write. + pub fn append_storage( + &mut self, + key: StorageKey, + element: StorageValue, + init: impl Fn() -> StorageValue, + ) { + let extrinsic_index = self.extrinsic_index(); + let size_write = element.len() as u64; + self.stats.tally_write_overlay(size_write); + self.top.append_storage(key, element, init, extrinsic_index); } /// Set a new value for the specified key and child. @@ -396,7 +391,8 @@ impl OverlayedChanges { pub fn clear_prefix(&mut self, prefix: &[u8]) -> u32 { self.mark_dirty(); - self.top.clear_where(|key, _| key.starts_with(prefix), self.extrinsic_index()) + let extrinsic_index = self.extrinsic_index(); + self.top.clear_where(|key, _| key.starts_with(prefix), extrinsic_index) } /// Removes all key-value pairs which keys share the given prefix. @@ -457,7 +453,7 @@ impl OverlayedChanges { }); self.offchain .overlay_mut() - .rollback_transaction() + .rollback_transaction_offchain() .expect("Top and offchain changesets are started in lockstep; qed"); Ok(()) } @@ -475,7 +471,7 @@ impl OverlayedChanges { } self.offchain .overlay_mut() - .commit_transaction() + .commit_transaction_offchain() .expect("Top and offchain changesets are started in lockstep; qed"); Ok(()) } @@ -511,7 +507,7 @@ impl OverlayedChanges { } self.offchain .overlay_mut() - .exit_runtime() + .exit_runtime_offchain() .expect("Top and offchain changesets are started in lockstep; qed"); Ok(()) } @@ -535,11 +531,24 @@ impl OverlayedChanges { self.children.values().map(|v| (v.0.changes(), &v.1)) } + /// Get an iterator over all child changes as seen by the current transaction. + pub fn children_mut( + &mut self, + ) -> impl Iterator, &ChildInfo)> + { + self.children.values_mut().map(|v| (v.0.changes_mut(), &v.1)) + } + /// Get an iterator over all top changes as been by the current transaction. pub fn changes(&self) -> impl Iterator { self.top.changes() } + /// Get an iterator over all top changes as been by the current transaction. + pub fn changes_mut(&mut self) -> impl Iterator { + self.top.changes_mut() + } + /// Get an optional iterator over all child changes stored under the supplied key. pub fn child_changes( &self, @@ -548,6 +557,16 @@ impl OverlayedChanges { self.children.get(key).map(|(overlay, info)| (overlay.changes(), info)) } + /// Get an optional iterator over all child changes stored under the supplied key. + pub fn child_changes_mut( + &mut self, + key: &[u8], + ) -> Option<(impl Iterator, &ChildInfo)> { + self.children + .get_mut(key) + .map(|(overlay, info)| (overlay.changes_mut(), &*info)) + } + /// Get an list of all index operations. pub fn transaction_index_ops(&self) -> &[IndexOperation] { &self.transaction_index_ops @@ -575,11 +594,12 @@ impl OverlayedChanges { }; use core::mem::take; - let main_storage_changes = take(&mut self.top).drain_committed(); - let child_storage_changes = take(&mut self.children) - .into_iter() - .map(|(key, (val, info))| (key, (val.drain_committed(), info))); - + let main_storage_changes = + take(&mut self.top).drain_committed().map(|(k, v)| (k, v.to_option())); + let child_storage_changes = + take(&mut self.children).into_iter().map(|(key, (val, info))| { + (key, (val.drain_committed().map(|(k, v)| (k, v.to_option())), info)) + }); let offchain_storage_changes = self.offchain_drain_committed().collect(); #[cfg(feature = "std")] @@ -610,7 +630,7 @@ impl OverlayedChanges { /// set this index before first and unset after last extrinsic is executed. /// Changes that are made outside of extrinsics, are marked with /// `NO_EXTRINSIC_INDEX` index. - fn extrinsic_index(&self) -> Option { + fn extrinsic_index(&mut self) -> Option { self.collect_extrinsics.then(|| { self.storage(EXTRINSIC_INDEX) .and_then(|idx| idx.and_then(|idx| Decode::decode(&mut &*idx).ok())) @@ -634,10 +654,12 @@ impl OverlayedChanges { return (cache.transaction_storage_root, true) } - let delta = self.changes().map(|(k, v)| (&k[..], v.value().map(|v| &v[..]))); - let child_delta = self.children().map(|(changes, info)| { - (info, changes.map(|(k, v)| (&k[..], v.value().map(|v| &v[..])))) - }); + let delta = self.top.changes_mut().map(|(k, v)| (&k[..], v.value().map(|v| &v[..]))); + + let child_delta = self + .children + .values_mut() + .map(|v| (&v.1, v.0.changes_mut().map(|(k, v)| (&k[..], v.value().map(|v| &v[..]))))); let (root, transaction) = backend.full_storage_root(delta, child_delta, state_version); @@ -677,7 +699,7 @@ impl OverlayedChanges { return Ok((root, true)) } - let root = if let Some((changes, info)) = self.child_changes(storage_key) { + let root = if let Some((changes, info)) = self.child_changes_mut(storage_key) { let delta = changes.map(|(k, v)| (k.as_ref(), v.value().map(AsRef::as_ref))); Some(backend.child_storage_root(info, delta, state_version)) } else { @@ -711,19 +733,19 @@ impl OverlayedChanges { /// Returns an iterator over the keys (in lexicographic order) following `key` (excluding `key`) /// alongside its value. - pub fn iter_after(&self, key: &[u8]) -> impl Iterator { + pub fn iter_after(&mut self, key: &[u8]) -> impl Iterator { self.top.changes_after(key) } /// Returns an iterator over the keys (in lexicographic order) following `key` (excluding `key`) /// alongside its value for the given `storage_key` child. pub fn child_iter_after( - &self, + &mut self, storage_key: &[u8], key: &[u8], - ) -> impl Iterator { + ) -> impl Iterator { self.children - .get(storage_key) + .get_mut(storage_key) .map(|(overlay, _)| overlay.changes_after(key)) .into_iter() .flatten() @@ -858,7 +880,11 @@ mod tests { use sp_core::{traits::Externalities, Blake2Hasher}; use std::collections::BTreeMap; - fn assert_extrinsics(overlay: &OverlayedChangeSet, key: impl AsRef<[u8]>, expected: Vec) { + fn assert_extrinsics( + overlay: &mut OverlayedChangeSet, + key: impl AsRef<[u8]>, + expected: Vec, + ) { assert_eq!( overlay.get(key.as_ref()).unwrap().extrinsics().into_iter().collect::>(), expected @@ -1049,9 +1075,9 @@ mod tests { overlay.set_extrinsic_index(2); overlay.set_storage(vec![1], Some(vec![6])); - assert_extrinsics(&overlay.top, vec![1], vec![0, 2]); - assert_extrinsics(&overlay.top, vec![3], vec![1]); - assert_extrinsics(&overlay.top, vec![100], vec![NO_EXTRINSIC_INDEX]); + assert_extrinsics(&mut overlay.top, vec![1], vec![0, 2]); + assert_extrinsics(&mut overlay.top, vec![3], vec![1]); + assert_extrinsics(&mut overlay.top, vec![100], vec![NO_EXTRINSIC_INDEX]); overlay.start_transaction(); @@ -1061,15 +1087,15 @@ mod tests { overlay.set_extrinsic_index(4); overlay.set_storage(vec![1], Some(vec![8])); - assert_extrinsics(&overlay.top, vec![1], vec![0, 2, 4]); - assert_extrinsics(&overlay.top, vec![3], vec![1, 3]); - assert_extrinsics(&overlay.top, vec![100], vec![NO_EXTRINSIC_INDEX]); + assert_extrinsics(&mut overlay.top, vec![1], vec![0, 2, 4]); + assert_extrinsics(&mut overlay.top, vec![3], vec![1, 3]); + assert_extrinsics(&mut overlay.top, vec![100], vec![NO_EXTRINSIC_INDEX]); overlay.rollback_transaction().unwrap(); - assert_extrinsics(&overlay.top, vec![1], vec![0, 2]); - assert_extrinsics(&overlay.top, vec![3], vec![1]); - assert_extrinsics(&overlay.top, vec![100], vec![NO_EXTRINSIC_INDEX]); + assert_extrinsics(&mut overlay.top, vec![1], vec![0, 2]); + assert_extrinsics(&mut overlay.top, vec![3], vec![1]); + assert_extrinsics(&mut overlay.top, vec![100], vec![NO_EXTRINSIC_INDEX]); } #[test] diff --git a/substrate/primitives/state-machine/src/overlayed_changes/offchain.rs b/substrate/primitives/state-machine/src/overlayed_changes/offchain.rs index 1e6965e874759e30b415783a560192af8412027d..517a51b02693c0528cf9475972a259ab72fd5f59 100644 --- a/substrate/primitives/state-machine/src/overlayed_changes/offchain.rs +++ b/substrate/primitives/state-machine/src/overlayed_changes/offchain.rs @@ -42,7 +42,7 @@ impl OffchainOverlayedChanges { } /// Iterate over all key value pairs by reference. - pub fn iter(&self) -> impl Iterator { + pub fn iter(&mut self) -> impl Iterator { self.0.changes().map(|kv| (kv.0, kv.1.value_ref())) } @@ -53,14 +53,16 @@ impl OffchainOverlayedChanges { /// Remove a key and its associated value from the offchain database. pub fn remove(&mut self, prefix: &[u8], key: &[u8]) { - let _ = self - .0 - .set((prefix.to_vec(), key.to_vec()), OffchainOverlayedChange::Remove, None); + let _ = self.0.set_offchain( + (prefix.to_vec(), key.to_vec()), + OffchainOverlayedChange::Remove, + None, + ); } /// Set the value associated with a key under a prefix to the value provided. pub fn set(&mut self, prefix: &[u8], key: &[u8], value: &[u8]) { - let _ = self.0.set( + let _ = self.0.set_offchain( (prefix.to_vec(), key.to_vec()), OffchainOverlayedChange::SetValue(value.to_vec()), None, @@ -68,7 +70,7 @@ impl OffchainOverlayedChanges { } /// Obtain a associated value to the given key in storage with prefix. - pub fn get(&self, prefix: &[u8], key: &[u8]) -> Option { + pub fn get(&mut self, prefix: &[u8], key: &[u8]) -> Option { let key = (prefix.to_vec(), key.to_vec()); self.0.get(&key).map(|entry| entry.value_ref()).cloned() } diff --git a/substrate/primitives/state-machine/src/read_only.rs b/substrate/primitives/state-machine/src/read_only.rs index 2056bf9866358d4d5086fbdf67a7385e7532092f..b78d17138b0ff5c968a858ab7515b5d82a9673c3 100644 --- a/substrate/primitives/state-machine/src/read_only.rs +++ b/substrate/primitives/state-machine/src/read_only.rs @@ -88,39 +88,39 @@ where panic!("Should not be used in read-only externalities!") } - fn storage(&self, key: &[u8]) -> Option { + fn storage(&mut self, key: &[u8]) -> Option { self.backend .storage(key) .expect("Backed failed for storage in ReadOnlyExternalities") } - fn storage_hash(&self, key: &[u8]) -> Option> { + fn storage_hash(&mut self, key: &[u8]) -> Option> { self.backend .storage_hash(key) .expect("Backed failed for storage_hash in ReadOnlyExternalities") .map(|h| h.encode()) } - fn child_storage(&self, child_info: &ChildInfo, key: &[u8]) -> Option { + fn child_storage(&mut self, child_info: &ChildInfo, key: &[u8]) -> Option { self.backend .child_storage(child_info, key) .expect("Backed failed for child_storage in ReadOnlyExternalities") } - fn child_storage_hash(&self, child_info: &ChildInfo, key: &[u8]) -> Option> { + fn child_storage_hash(&mut self, child_info: &ChildInfo, key: &[u8]) -> Option> { self.backend .child_storage_hash(child_info, key) .expect("Backed failed for child_storage_hash in ReadOnlyExternalities") .map(|h| h.encode()) } - fn next_storage_key(&self, key: &[u8]) -> Option { + fn next_storage_key(&mut self, key: &[u8]) -> Option { self.backend .next_storage_key(key) .expect("Backed failed for next_storage_key in ReadOnlyExternalities") } - fn next_child_storage_key(&self, child_info: &ChildInfo, key: &[u8]) -> Option { + fn next_child_storage_key(&mut self, child_info: &ChildInfo, key: &[u8]) -> Option { self.backend .next_child_storage_key(child_info, key) .expect("Backed failed for next_child_storage_key in ReadOnlyExternalities") diff --git a/substrate/primitives/state-machine/src/testing.rs b/substrate/primitives/state-machine/src/testing.rs index e19ba95755c1b16f5cc6a2d59a8ede48997707f0..e9d64a891e819094d8a2c4d49265d01d6b7fc965 100644 --- a/substrate/primitives/state-machine/src/testing.rs +++ b/substrate/primitives/state-machine/src/testing.rs @@ -209,12 +209,15 @@ where /// /// In contrast to [`commit_all`](Self::commit_all) this will not panic if there are open /// transactions. - pub fn as_backend(&self) -> InMemoryBackend { - let top: Vec<_> = - self.overlay.changes().map(|(k, v)| (k.clone(), v.value().cloned())).collect(); + pub fn as_backend(&mut self) -> InMemoryBackend { + let top: Vec<_> = self + .overlay + .changes_mut() + .map(|(k, v)| (k.clone(), v.value().cloned())) + .collect(); let mut transaction = vec![(None, top)]; - for (child_changes, child_info) in self.overlay.children() { + for (child_changes, child_info) in self.overlay.children_mut() { transaction.push(( Some(child_info.clone()), child_changes.map(|(k, v)| (k.clone(), v.value().cloned())).collect(), @@ -293,13 +296,14 @@ where } } -impl PartialEq for TestExternalities +impl TestExternalities where + H: Hasher, H::Out: Ord + 'static + codec::Codec, { /// This doesn't test if they are in the same state, only if they contains the /// same data at this state - fn eq(&self, other: &TestExternalities) -> bool { + pub fn eq(&mut self, other: &mut TestExternalities) -> bool { self.as_backend().eq(&other.as_backend()) } } diff --git a/substrate/primitives/statement-store/Cargo.toml b/substrate/primitives/statement-store/Cargo.toml index bb893b25dc443f617ab5c0dd3d0d22c94646b689..c6f8491367c3009b4e494e1a340c3d2f3808f94b 100644 --- a/substrate/primitives/statement-store/Cargo.toml +++ b/substrate/primitives/statement-store/Cargo.toml @@ -16,25 +16,25 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -sp-core = { path = "../core", default-features = false } -sp-crypto-hashing = { path = "../crypto/hashing", default-features = false } -sp-runtime = { path = "../runtime", default-features = false } -sp-api = { path = "../api", default-features = false } -sp-application-crypto = { path = "../application-crypto", default-features = false } -sp-runtime-interface = { path = "../runtime-interface", default-features = false } -sp-externalities = { path = "../externalities", default-features = false } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } +sp-core = { workspace = true } +sp-crypto-hashing = { workspace = true } +sp-runtime = { workspace = true } +sp-api = { workspace = true } +sp-application-crypto = { workspace = true } +sp-runtime-interface = { workspace = true } +sp-externalities = { workspace = true } thiserror = { optional = true, workspace = true } # ECIES dependencies -ed25519-dalek = { version = "2.1", optional = true } -x25519-dalek = { version = "2.0", optional = true, features = ["static_secrets"] } -curve25519-dalek = { version = "4.1.1", optional = true } -aes-gcm = { version = "0.10", optional = true } -hkdf = { version = "0.12.0", optional = true } -sha2 = { version = "0.10.7", optional = true } -rand = { version = "0.8.5", features = ["small_rng"], optional = true } +ed25519-dalek = { optional = true, workspace = true, default-features = true } +x25519-dalek = { optional = true, features = ["static_secrets"], workspace = true } +curve25519-dalek = { optional = true, workspace = true } +aes-gcm = { optional = true, workspace = true } +hkdf = { optional = true, workspace = true } +sha2 = { optional = true, workspace = true, default-features = true } +rand = { features = ["small_rng"], optional = true, workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/primitives/storage/Cargo.toml b/substrate/primitives/storage/Cargo.toml index c3318943d0d481a430da46502cdcb3a3c8aa22a7..3184ec010930ae7321ee4dc183844b6c0ab91839 100644 --- a/substrate/primitives/storage/Cargo.toml +++ b/substrate/primitives/storage/Cargo.toml @@ -17,11 +17,11 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -impl-serde = { version = "0.4.0", optional = true, default-features = false } -ref-cast = "1.0.0" +codec = { features = ["derive"], workspace = true } +impl-serde = { optional = true, workspace = true } +ref-cast = { workspace = true } serde = { features = ["alloc", "derive"], optional = true, workspace = true } -sp-debug-derive = { path = "../debug-derive", default-features = false } +sp-debug-derive = { workspace = true } [features] default = ["std"] diff --git a/substrate/primitives/storage/src/lib.rs b/substrate/primitives/storage/src/lib.rs index 197994f574719ec0b000b8dbd79f333c71291708..3b9afae4ca078d1e69f5e33e9b3cfeee76b4a328 100644 --- a/substrate/primitives/storage/src/lib.rs +++ b/substrate/primitives/storage/src/lib.rs @@ -293,7 +293,7 @@ impl ChildInfo { } } - /// Return a the full location in the direct parent of + /// Return the full location in the direct parent of /// this trie. pub fn prefixed_storage_key(&self) -> PrefixedStorageKey { match self { @@ -302,7 +302,7 @@ impl ChildInfo { } } - /// Returns a the full location in the direct parent of + /// Returns the full location in the direct parent of /// this trie. pub fn into_prefixed_storage_key(self) -> PrefixedStorageKey { match self { diff --git a/substrate/primitives/test-primitives/Cargo.toml b/substrate/primitives/test-primitives/Cargo.toml index b7be614860910eb63f12eadaa3676f69b0e65ada..e223e8937653c0449e27e5b0e34a94fa03711982 100644 --- a/substrate/primitives/test-primitives/Cargo.toml +++ b/substrate/primitives/test-primitives/Cargo.toml @@ -15,12 +15,12 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } serde = { features = ["derive"], optional = true, workspace = true } -sp-application-crypto = { path = "../application-crypto", default-features = false } -sp-core = { path = "../core", default-features = false } -sp-runtime = { path = "../runtime", default-features = false } +sp-application-crypto = { workspace = true } +sp-core = { workspace = true } +sp-runtime = { workspace = true } [features] default = ["std"] diff --git a/substrate/primitives/timestamp/Cargo.toml b/substrate/primitives/timestamp/Cargo.toml index c1bf9b3255eab83dea9eb9f80b93aa5440e816e1..7dccf741cd068c299a539c6a20550e4ebe4e9006 100644 --- a/substrate/primitives/timestamp/Cargo.toml +++ b/substrate/primitives/timestamp/Cargo.toml @@ -16,11 +16,11 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -async-trait = { version = "0.1.79", optional = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } +async-trait = { optional = true, workspace = true } +codec = { features = ["derive"], workspace = true } thiserror = { optional = true, workspace = true } -sp-inherents = { path = "../inherents", default-features = false } -sp-runtime = { path = "../runtime", default-features = false } +sp-inherents = { workspace = true } +sp-runtime = { workspace = true } [features] default = ["std"] diff --git a/substrate/primitives/tracing/Cargo.toml b/substrate/primitives/tracing/Cargo.toml index 8adec1670dc2da99c315f58dbc37a92a3cf947f5..c434016604ac9eff0752d3924ce01b67acba15c0 100644 --- a/substrate/primitives/tracing/Cargo.toml +++ b/substrate/primitives/tracing/Cargo.toml @@ -21,11 +21,11 @@ features = ["with-tracing"] targets = ["wasm32-unknown-unknown", "x86_64-unknown-linux-gnu"] [dependencies] -codec = { version = "3.6.12", package = "parity-scale-codec", default-features = false, features = [ +codec = { features = [ "derive", -] } -tracing = { version = "0.1.29", default-features = false } -tracing-core = { version = "0.1.32", default-features = false } +], workspace = true } +tracing = { workspace = true } +tracing-core = { workspace = true } tracing-subscriber = { workspace = true, optional = true, features = [ "env-filter", "tracing-log", diff --git a/substrate/primitives/transaction-pool/Cargo.toml b/substrate/primitives/transaction-pool/Cargo.toml index a7deda64efce46f57e84826fbef8ce76598ab73b..964fb18b533eeb5a28fe3b6f0cafba5150528ec4 100644 --- a/substrate/primitives/transaction-pool/Cargo.toml +++ b/substrate/primitives/transaction-pool/Cargo.toml @@ -17,8 +17,8 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-api = { path = "../api", default-features = false } -sp-runtime = { path = "../runtime", default-features = false } +sp-api = { workspace = true } +sp-runtime = { workspace = true } [features] default = ["std"] diff --git a/substrate/primitives/transaction-storage-proof/Cargo.toml b/substrate/primitives/transaction-storage-proof/Cargo.toml index 1e874c3595acd4723e34c0cb8568256ae2444317..f12b9ef118cbaa7447e9d8405d654312bc72bcc6 100644 --- a/substrate/primitives/transaction-storage-proof/Cargo.toml +++ b/substrate/primitives/transaction-storage-proof/Cargo.toml @@ -16,13 +16,13 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -async-trait = { version = "0.1.79", optional = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -sp-core = { path = "../core", optional = true, default-features = false } -sp-inherents = { path = "../inherents", default-features = false } -sp-runtime = { path = "../runtime", default-features = false } -sp-trie = { path = "../trie", optional = true, default-features = false } +async-trait = { optional = true, workspace = true } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } +sp-core = { optional = true, workspace = true } +sp-inherents = { workspace = true } +sp-runtime = { workspace = true } +sp-trie = { optional = true, workspace = true } [features] default = ["std"] diff --git a/substrate/primitives/trie/Cargo.toml b/substrate/primitives/trie/Cargo.toml index 45459c180d40d076b0d7b59232e9dc76cd0b2d27..1fe29f72014aa8ca078a33aa5e936a3308b20c2e 100644 --- a/substrate/primitives/trie/Cargo.toml +++ b/substrate/primitives/trie/Cargo.toml @@ -21,29 +21,29 @@ name = "bench" harness = false [dependencies] -ahash = { version = "0.8.2", optional = true } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -hash-db = { version = "0.16.0", default-features = false } -lazy_static = { version = "1.4.0", optional = true } -memory-db = { version = "0.32.0", default-features = false } -nohash-hasher = { version = "0.2.0", optional = true } -parking_lot = { version = "0.12.1", optional = true } -rand = { version = "0.8", optional = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +ahash = { optional = true, workspace = true } +codec = { workspace = true } +hash-db = { workspace = true } +lazy_static = { optional = true, workspace = true } +memory-db = { workspace = true } +nohash-hasher = { optional = true, workspace = true } +parking_lot = { optional = true, workspace = true, default-features = true } +rand = { optional = true, workspace = true, default-features = true } +scale-info = { features = ["derive"], workspace = true } thiserror = { optional = true, workspace = true } -tracing = { version = "0.1.29", optional = true } -trie-db = { version = "0.29.0", default-features = false } -trie-root = { version = "0.18.0", default-features = false } -sp-core = { path = "../core", default-features = false } -sp-externalities = { path = "../externalities", default-features = false } -schnellru = { version = "0.2.1", optional = true } +tracing = { optional = true, workspace = true, default-features = true } +trie-db = { workspace = true } +trie-root = { workspace = true } +sp-core = { workspace = true } +sp-externalities = { workspace = true } +schnellru = { optional = true, workspace = true } [dev-dependencies] -array-bytes = "6.2.2" -criterion = "0.5.1" -trie-bench = "0.39.0" -trie-standardmap = "0.16.0" -sp-runtime = { path = "../runtime" } +array-bytes = { workspace = true, default-features = true } +criterion = { workspace = true, default-features = true } +trie-bench = { workspace = true } +trie-standardmap = { workspace = true } +sp-runtime = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/primitives/trie/src/lib.rs b/substrate/primitives/trie/src/lib.rs index 54f202eda0c9ac3d3991c094b3f406f8d78d4c4d..0c14e3af196d062e08f86ee8b6a7fa370a2a28bd 100644 --- a/substrate/primitives/trie/src/lib.rs +++ b/substrate/primitives/trie/src/lib.rs @@ -195,11 +195,11 @@ pub type MemoryDB = memory_db::MemoryDB, trie_db::DB /// Reexport from `hash_db`, with genericity set for `Hasher` trait. pub type GenericMemoryDB = memory_db::MemoryDB; -/// Persistent trie database read-access interface for the a given hasher. +/// Persistent trie database read-access interface for a given hasher. pub type TrieDB<'a, 'cache, L> = trie_db::TrieDB<'a, 'cache, L>; /// Builder for creating a [`TrieDB`]. pub type TrieDBBuilder<'a, 'cache, L> = trie_db::TrieDBBuilder<'a, 'cache, L>; -/// Persistent trie database write-access interface for the a given hasher. +/// Persistent trie database write-access interface for a given hasher. pub type TrieDBMut<'a, L> = trie_db::TrieDBMut<'a, L>; /// Builder for creating a [`TrieDBMut`]. pub type TrieDBMutBuilder<'a, L> = trie_db::TrieDBMutBuilder<'a, L>; @@ -212,17 +212,17 @@ pub type TrieHash = <::Hash as Hasher>::Out; pub mod trie_types { use super::*; - /// Persistent trie database read-access interface for the a given hasher. + /// Persistent trie database read-access interface for a given hasher. /// /// Read only V1 and V0 are compatible, thus we always use V1. pub type TrieDB<'a, 'cache, H> = super::TrieDB<'a, 'cache, LayoutV1>; /// Builder for creating a [`TrieDB`]. pub type TrieDBBuilder<'a, 'cache, H> = super::TrieDBBuilder<'a, 'cache, LayoutV1>; - /// Persistent trie database write-access interface for the a given hasher. + /// Persistent trie database write-access interface for a given hasher. pub type TrieDBMutV0<'a, H> = super::TrieDBMut<'a, LayoutV0>; /// Builder for creating a [`TrieDBMutV0`]. pub type TrieDBMutBuilderV0<'a, H> = super::TrieDBMutBuilder<'a, LayoutV0>; - /// Persistent trie database write-access interface for the a given hasher. + /// Persistent trie database write-access interface for a given hasher. pub type TrieDBMutV1<'a, H> = super::TrieDBMut<'a, LayoutV1>; /// Builder for creating a [`TrieDBMutV1`]. pub type TrieDBMutBuilderV1<'a, H> = super::TrieDBMutBuilder<'a, LayoutV1>; diff --git a/substrate/primitives/version/Cargo.toml b/substrate/primitives/version/Cargo.toml index f8ef8f66c5355634dbb4a7e1f08adbdb2f035766..65a7c63f432ddb119897f26bd398d671f18ea70a 100644 --- a/substrate/primitives/version/Cargo.toml +++ b/substrate/primitives/version/Cargo.toml @@ -17,16 +17,16 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -impl-serde = { version = "0.4.0", default-features = false, optional = true } -parity-wasm = { version = "0.45", optional = true } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +codec = { features = ["derive"], workspace = true } +impl-serde = { optional = true, workspace = true } +parity-wasm = { optional = true, workspace = true } +scale-info = { features = ["derive"], workspace = true } serde = { features = ["alloc", "derive"], optional = true, workspace = true } thiserror = { optional = true, workspace = true } -sp-crypto-hashing-proc-macro = { path = "../crypto/hashing/proc-macro" } -sp-runtime = { path = "../runtime", default-features = false } -sp-std = { path = "../std", default-features = false } -sp-version-proc-macro = { path = "proc-macro", default-features = false } +sp-crypto-hashing-proc-macro = { workspace = true, default-features = true } +sp-runtime = { workspace = true } +sp-std = { workspace = true } +sp-version-proc-macro = { workspace = true } [features] default = ["std"] diff --git a/substrate/primitives/version/proc-macro/Cargo.toml b/substrate/primitives/version/proc-macro/Cargo.toml index 3abd5c0910694cf14a8885ecebf4cc855e9e8266..1feea15b9fcdb84a5608ae6cb8739e4d5e9e8e0c 100644 --- a/substrate/primitives/version/proc-macro/Cargo.toml +++ b/substrate/primitives/version/proc-macro/Cargo.toml @@ -19,10 +19,10 @@ targets = ["x86_64-unknown-linux-gnu"] proc-macro = true [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } -proc-macro2 = "1.0.56" +codec = { features = ["derive"], workspace = true, default-features = true } +proc-macro2 = { workspace = true } quote = { workspace = true } syn = { features = ["extra-traits", "fold", "full", "visit"], workspace = true } [dev-dependencies] -sp-version = { path = ".." } +sp-version = { workspace = true, default-features = true } diff --git a/substrate/primitives/wasm-interface/Cargo.toml b/substrate/primitives/wasm-interface/Cargo.toml index a0c8342d2d3c5014527487faf187fc48fd5344e1..f7a1d25d16bf37827df65c74a89fe3bf2232c0fc 100644 --- a/substrate/primitives/wasm-interface/Cargo.toml +++ b/substrate/primitives/wasm-interface/Cargo.toml @@ -17,11 +17,11 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -impl-trait-for-tuples = "0.2.2" +codec = { features = ["derive"], workspace = true } +impl-trait-for-tuples = { workspace = true } log = { optional = true, workspace = true, default-features = true } -wasmtime = { version = "8.0.1", default-features = false, optional = true } -anyhow = { version = "1.0.81", optional = true } +wasmtime = { optional = true, workspace = true } +anyhow = { optional = true, workspace = true } [features] default = ["std"] diff --git a/substrate/primitives/weights/Cargo.toml b/substrate/primitives/weights/Cargo.toml index d2d72a7cb019fa5ad5c8fd66a32e953f9076068f..c9f4f39d041c2f28b978578a9dd830ce7ae9ab68 100644 --- a/substrate/primitives/weights/Cargo.toml +++ b/substrate/primitives/weights/Cargo.toml @@ -16,14 +16,14 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -bounded-collections = { version = "0.2.0", default-features = false } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } +bounded-collections = { workspace = true } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } serde = { optional = true, features = ["alloc", "derive"], workspace = true } -smallvec = "1.11.0" -sp-arithmetic = { path = "../arithmetic", default-features = false } -sp-debug-derive = { path = "../debug-derive", default-features = false } -schemars = { version = "0.8.3", default-features = false, optional = true } +smallvec = { workspace = true, default-features = true } +sp-arithmetic = { workspace = true } +sp-debug-derive = { workspace = true } +schemars = { optional = true, workspace = true } [features] default = ["std"] diff --git a/substrate/scripts/ci/node-template-release/Cargo.toml b/substrate/scripts/ci/node-template-release/Cargo.toml index 8e3e6138b9a8dabdbd67589049e5273305d29a0a..5ec665de05ea9337b5f6a8824b13fca7a4c710cb 100644 --- a/substrate/scripts/ci/node-template-release/Cargo.toml +++ b/substrate/scripts/ci/node-template-release/Cargo.toml @@ -14,11 +14,11 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -clap = { version = "4.5.3", features = ["derive"] } -flate2 = "1.0" -fs_extra = "1.3" -glob = "0.3" -tar = "0.4" -tempfile = "3" -toml_edit = "0.19" -itertools = "0.11" +clap = { features = ["derive"], workspace = true } +flate2 = { workspace = true } +fs_extra = { workspace = true } +glob = { workspace = true } +tar = { workspace = true } +tempfile = { workspace = true } +toml_edit = { workspace = true } +itertools = { workspace = true } diff --git a/substrate/test-utils/Cargo.toml b/substrate/test-utils/Cargo.toml index 56b1c038199a81fb84c03474f0d7c5bbf5ab2c67..71aac02ba9b64260f50e0f0f832c9a85f6bc2f5b 100644 --- a/substrate/test-utils/Cargo.toml +++ b/substrate/test-utils/Cargo.toml @@ -16,9 +16,9 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -futures = "0.3.30" -tokio = { version = "1.22.0", features = ["macros", "time"] } +futures = { workspace = true } +tokio = { features = ["macros", "time"], workspace = true, default-features = true } [dev-dependencies] -trybuild = { version = "1.0.88", features = ["diff"] } -sc-service = { path = "../client/service" } +trybuild = { features = ["diff"], workspace = true } +sc-service = { workspace = true, default-features = true } diff --git a/substrate/test-utils/cli/Cargo.toml b/substrate/test-utils/cli/Cargo.toml index 87c595c66f3484cbbaa8d8a6d83ea09453ee99b9..52642b9f62bb96277a29fdb91894c34cfd043f64 100644 --- a/substrate/test-utils/cli/Cargo.toml +++ b/substrate/test-utils/cli/Cargo.toml @@ -16,17 +16,17 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -substrate-rpc-client = { path = "../../utils/frame/rpc/client" } -sp-rpc = { path = "../../primitives/rpc" } -assert_cmd = "2.0.10" -nix = { version = "0.28.0", features = ["signal"] } -regex = "1.7.3" -tokio = { version = "1.22.0", features = ["full"] } -node-primitives = { path = "../../bin/node/primitives" } -node-cli = { package = "staging-node-cli", path = "../../bin/node/cli" } -sc-cli = { path = "../../client/cli" } -sc-service = { path = "../../client/service" } -futures = "0.3.28" +substrate-rpc-client = { workspace = true, default-features = true } +sp-rpc = { workspace = true, default-features = true } +assert_cmd = { workspace = true } +nix = { features = ["signal"], workspace = true } +regex = { workspace = true } +tokio = { features = ["full"], workspace = true, default-features = true } +node-primitives = { workspace = true, default-features = true } +node-cli = { workspace = true } +sc-cli = { workspace = true, default-features = true } +sc-service = { workspace = true, default-features = true } +futures = { workspace = true } [features] try-runtime = ["node-cli/try-runtime"] diff --git a/substrate/test-utils/client/Cargo.toml b/substrate/test-utils/client/Cargo.toml index 5871f1bf5b4d05ad35f0998e7b4ab9fb3b953d58..ecf04dac1a67350d72aebc07c7af8499ee4145a7 100644 --- a/substrate/test-utils/client/Cargo.toml +++ b/substrate/test-utils/client/Cargo.toml @@ -16,27 +16,27 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -array-bytes = "6.2.2" -async-trait = "0.1.79" -codec = { package = "parity-scale-codec", version = "3.6.12" } -futures = "0.3.30" +array-bytes = { workspace = true, default-features = true } +async-trait = { workspace = true } +codec = { workspace = true, default-features = true } +futures = { workspace = true } serde = { workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } -sc-client-api = { path = "../../client/api" } -sc-client-db = { path = "../../client/db", default-features = false, features = [ +sc-client-api = { workspace = true, default-features = true } +sc-client-db = { features = [ "test-helpers", -] } -sc-consensus = { path = "../../client/consensus/common" } -sc-executor = { path = "../../client/executor" } -sc-offchain = { path = "../../client/offchain" } -sc-service = { path = "../../client/service", default-features = false, features = [ +], workspace = true } +sc-consensus = { workspace = true, default-features = true } +sc-executor = { workspace = true, default-features = true } +sc-offchain = { workspace = true, default-features = true } +sc-service = { features = [ "test-helpers", -] } -sp-blockchain = { path = "../../primitives/blockchain" } -sp-consensus = { path = "../../primitives/consensus/common" } -sp-core = { path = "../../primitives/core" } -sp-keyring = { path = "../../primitives/keyring" } -sp-keystore = { path = "../../primitives/keystore" } -sp-runtime = { path = "../../primitives/runtime" } -sp-state-machine = { path = "../../primitives/state-machine" } -tokio = { version = "1.22.0", features = ["sync"] } +], workspace = true } +sp-blockchain = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-state-machine = { workspace = true, default-features = true } +tokio = { features = ["sync"], workspace = true, default-features = true } diff --git a/substrate/test-utils/client/src/client_ext.rs b/substrate/test-utils/client/src/client_ext.rs index 73581a4f0efa31c195f3856a8894692a2f71bcfb..9dc4739eb795437cff17fae69e5a0181cf150510 100644 --- a/substrate/test-utils/client/src/client_ext.rs +++ b/substrate/test-utils/client/src/client_ext.rs @@ -153,7 +153,7 @@ where Self: BlockImport, RA: Send, B: Send + Sync, - E: Send, + E: Send + Sync, { async fn import(&mut self, origin: BlockOrigin, block: Block) -> Result<(), ConsensusError> { let (header, extrinsics) = block.deconstruct(); diff --git a/substrate/test-utils/runtime/Cargo.toml b/substrate/test-utils/runtime/Cargo.toml index 8733ff9fcebb36199c341cd6d90a96623212944c..e3282f8e598edd36662399424ad2e78999cf3f6e 100644 --- a/substrate/test-utils/runtime/Cargo.toml +++ b/substrate/test-utils/runtime/Cargo.toml @@ -16,59 +16,59 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -sp-application-crypto = { path = "../../primitives/application-crypto", default-features = false, features = ["serde"] } -sp-consensus-aura = { path = "../../primitives/consensus/aura", default-features = false, features = ["serde"] } -sp-consensus-babe = { path = "../../primitives/consensus/babe", default-features = false, features = ["serde"] } -sp-genesis-builder = { path = "../../primitives/genesis-builder", default-features = false } -sp-block-builder = { path = "../../primitives/block-builder", default-features = false } -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = ["derive"] } -scale-info = { version = "2.11.1", default-features = false, features = ["derive"] } -sp-inherents = { path = "../../primitives/inherents", default-features = false } -sp-keyring = { path = "../../primitives/keyring", default-features = false } -sp-offchain = { path = "../../primitives/offchain", default-features = false } -sp-core = { path = "../../primitives/core", default-features = false, features = ["serde"] } -sp-crypto-hashing = { path = "../../primitives/crypto/hashing", default-features = false } -sp-io = { path = "../../primitives/io", default-features = false } -frame-support = { path = "../../frame/support", default-features = false } -sp-version = { path = "../../primitives/version", default-features = false } -sp-session = { path = "../../primitives/session", default-features = false } -sp-api = { path = "../../primitives/api", default-features = false } -sp-runtime = { path = "../../primitives/runtime", default-features = false, features = ["serde"] } -pallet-babe = { path = "../../frame/babe", default-features = false } -pallet-balances = { path = "../../frame/balances", default-features = false } -frame-executive = { path = "../../frame/executive", default-features = false } -frame-metadata-hash-extension = { path = "../../frame/metadata-hash-extension", default-features = false } -frame-system = { path = "../../frame/system", default-features = false } -frame-system-rpc-runtime-api = { path = "../../frame/system/rpc/runtime-api", default-features = false } -pallet-timestamp = { path = "../../frame/timestamp", default-features = false } -sp-consensus-grandpa = { path = "../../primitives/consensus/grandpa", default-features = false, features = ["serde"] } -sp-trie = { path = "../../primitives/trie", default-features = false } -sp-transaction-pool = { path = "../../primitives/transaction-pool", default-features = false } -trie-db = { version = "0.29.0", default-features = false } -sc-service = { path = "../../client/service", default-features = false, features = ["test-helpers"], optional = true } -sp-state-machine = { path = "../../primitives/state-machine", default-features = false } -sp-externalities = { path = "../../primitives/externalities", default-features = false } +sp-application-crypto = { features = ["serde"], workspace = true } +sp-consensus-aura = { features = ["serde"], workspace = true } +sp-consensus-babe = { features = ["serde"], workspace = true } +sp-genesis-builder = { workspace = true } +sp-block-builder = { workspace = true } +codec = { features = ["derive"], workspace = true } +scale-info = { features = ["derive"], workspace = true } +sp-inherents = { workspace = true } +sp-keyring = { workspace = true } +sp-offchain = { workspace = true } +sp-core = { features = ["serde"], workspace = true } +sp-crypto-hashing = { workspace = true } +sp-io = { workspace = true } +frame-support = { workspace = true } +sp-version = { workspace = true } +sp-session = { workspace = true } +sp-api = { workspace = true } +sp-runtime = { features = ["serde"], workspace = true } +pallet-babe = { workspace = true } +pallet-balances = { workspace = true } +frame-executive = { workspace = true } +frame-metadata-hash-extension = { workspace = true } +frame-system = { workspace = true } +frame-system-rpc-runtime-api = { workspace = true } +pallet-timestamp = { workspace = true } +sp-consensus-grandpa = { features = ["serde"], workspace = true } +sp-trie = { workspace = true } +sp-transaction-pool = { workspace = true } +trie-db = { workspace = true } +sc-service = { features = ["test-helpers"], optional = true, workspace = true } +sp-state-machine = { workspace = true } +sp-externalities = { workspace = true } # 3rd party -array-bytes = { version = "6.2.2", optional = true } +array-bytes = { optional = true, workspace = true, default-features = true } serde_json = { workspace = true, features = ["alloc"] } log = { workspace = true } -hex-literal = { version = "0.4.1" } +hex-literal = { workspace = true, default-features = true } [dev-dependencies] -futures = "0.3.30" -sc-block-builder = { path = "../../client/block-builder" } -sc-chain-spec = { path = "../../client/chain-spec" } -sc-executor = { path = "../../client/executor" } -sc-executor-common = { path = "../../client/executor/common" } -sp-consensus = { path = "../../primitives/consensus/common" } -substrate-test-runtime-client = { path = "client" } -sp-tracing = { path = "../../primitives/tracing" } +futures = { workspace = true } +sc-block-builder = { workspace = true, default-features = true } +sc-chain-spec = { workspace = true, default-features = true } +sc-executor = { workspace = true, default-features = true } +sc-executor-common = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +substrate-test-runtime-client = { workspace = true } +sp-tracing = { workspace = true, default-features = true } serde = { features = ["alloc", "derive"], workspace = true } serde_json = { features = ["alloc"], workspace = true } [build-dependencies] -substrate-wasm-builder = { path = "../../utils/wasm-builder", optional = true, features = ["metadata-hash"] } +substrate-wasm-builder = { optional = true, features = ["metadata-hash"], workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/test-utils/runtime/client/Cargo.toml b/substrate/test-utils/runtime/client/Cargo.toml index 5ca24fea33edab61162ea1e98a20bf8eb7e2b2cf..3c628d1e764fda5a78dd497a81d9c17a2da7d465 100644 --- a/substrate/test-utils/runtime/client/Cargo.toml +++ b/substrate/test-utils/runtime/client/Cargo.toml @@ -15,14 +15,14 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -futures = "0.3.30" -sc-block-builder = { path = "../../../client/block-builder" } -sc-client-api = { path = "../../../client/api" } -sc-consensus = { path = "../../../client/consensus/common" } -sp-api = { path = "../../../primitives/api" } -sp-blockchain = { path = "../../../primitives/blockchain" } -sp-consensus = { path = "../../../primitives/consensus/common" } -sp-core = { path = "../../../primitives/core" } -sp-runtime = { path = "../../../primitives/runtime" } -substrate-test-client = { path = "../../client" } -substrate-test-runtime = { path = ".." } +futures = { workspace = true } +sc-block-builder = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-consensus = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +substrate-test-client = { workspace = true } +substrate-test-runtime = { workspace = true } diff --git a/substrate/test-utils/runtime/src/lib.rs b/substrate/test-utils/runtime/src/lib.rs index 0aab6d3f01ca075b85f1c43f879168e2a0e5280d..a5769b56dd5520ec7114eafe8ea9b7901e9b26ca 100644 --- a/substrate/test-utils/runtime/src/lib.rs +++ b/substrate/test-utils/runtime/src/lib.rs @@ -874,7 +874,7 @@ pub mod storage_key_generator { sp_crypto_hashing::twox_64(x).iter().chain(x.iter()).cloned().collect() } - /// Generate the hashed storage keys from the raw literals. These keys are expected to be be in + /// Generate the hashed storage keys from the raw literals. These keys are expected to be in /// storage with given substrate-test runtime. pub fn generate_expected_storage_hashed_keys(custom_heap_pages: bool) -> Vec { let mut literals: Vec<&[u8]> = vec![b":code", b":extrinsic_index"]; diff --git a/substrate/test-utils/runtime/transaction-pool/Cargo.toml b/substrate/test-utils/runtime/transaction-pool/Cargo.toml index 360e2b7b810d1f40d4ac4884eedb60266e41cc5c..073997da025d2af4863029e38b3db18520fea189 100644 --- a/substrate/test-utils/runtime/transaction-pool/Cargo.toml +++ b/substrate/test-utils/runtime/transaction-pool/Cargo.toml @@ -15,12 +15,12 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12" } -futures = "0.3.30" -parking_lot = "0.12.1" +codec = { workspace = true, default-features = true } +futures = { workspace = true } +parking_lot = { workspace = true, default-features = true } thiserror = { workspace = true } -sc-transaction-pool = { path = "../../../client/transaction-pool" } -sc-transaction-pool-api = { path = "../../../client/transaction-pool/api" } -sp-blockchain = { path = "../../../primitives/blockchain" } -sp-runtime = { path = "../../../primitives/runtime" } -substrate-test-runtime-client = { path = "../client" } +sc-transaction-pool = { workspace = true, default-features = true } +sc-transaction-pool-api = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +substrate-test-runtime-client = { workspace = true } diff --git a/substrate/utils/binary-merkle-tree/Cargo.toml b/substrate/utils/binary-merkle-tree/Cargo.toml index fd35e6b1e1a25ada0e3cbd7012708a66b3f940f5..c0b65d731f7a6121e1f1355f6a877786b3456b71 100644 --- a/substrate/utils/binary-merkle-tree/Cargo.toml +++ b/substrate/utils/binary-merkle-tree/Cargo.toml @@ -12,15 +12,15 @@ homepage = "https://substrate.io" workspace = true [dependencies] -array-bytes = { version = "6.2.2", optional = true } +array-bytes = { optional = true, workspace = true, default-features = true } log = { optional = true, workspace = true } -hash-db = { version = "0.16.0", default-features = false } +hash-db = { workspace = true } [dev-dependencies] -array-bytes = "6.2.2" -env_logger = "0.11" -sp-core = { path = "../../primitives/core" } -sp-runtime = { path = "../../primitives/runtime" } +array-bytes = { workspace = true, default-features = true } +env_logger = { workspace = true } +sp-core = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } [features] debug = ["array-bytes", "log"] diff --git a/substrate/utils/fork-tree/Cargo.toml b/substrate/utils/fork-tree/Cargo.toml index 275f44623bd1455cb34caa544fbfa4a6e140111b..2bb799c603c844acd1baf734a16da05787c9c8bc 100644 --- a/substrate/utils/fork-tree/Cargo.toml +++ b/substrate/utils/fork-tree/Cargo.toml @@ -17,4 +17,4 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", features = ["derive"] } +codec = { features = ["derive"], workspace = true, default-features = true } diff --git a/substrate/utils/frame/benchmarking-cli/Cargo.toml b/substrate/utils/frame/benchmarking-cli/Cargo.toml index 7cfacdc2e5edea443de8742fbe23cf9245872f08..bd1a22affd03b73218c6863ff62c64f58f935a86 100644 --- a/substrate/utils/frame/benchmarking-cli/Cargo.toml +++ b/substrate/utils/frame/benchmarking-cli/Cargo.toml @@ -16,49 +16,49 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -array-bytes = "6.2.2" -chrono = "0.4" -clap = { version = "4.5.3", features = ["derive"] } -codec = { package = "parity-scale-codec", version = "3.6.12" } -comfy-table = { version = "7.1.0", default-features = false } -handlebars = "5.1.0" -Inflector = "0.11.4" -itertools = "0.11" -lazy_static = "1.4.0" -linked-hash-map = "0.5.4" +array-bytes = { workspace = true, default-features = true } +chrono = { workspace = true } +clap = { features = ["derive"], workspace = true } +codec = { workspace = true, default-features = true } +comfy-table = { workspace = true } +handlebars = { workspace = true } +Inflector = { workspace = true } +itertools = { workspace = true } +lazy_static = { workspace = true } +linked-hash-map = { workspace = true } log = { workspace = true, default-features = true } -rand = { version = "0.8.5", features = ["small_rng"] } -rand_pcg = "0.3.1" +rand = { features = ["small_rng"], workspace = true, default-features = true } +rand_pcg = { workspace = true } serde = { workspace = true, default-features = true } serde_json = { workspace = true, default-features = true } thiserror = { workspace = true } -thousands = "0.2.0" -frame-benchmarking = { path = "../../../frame/benchmarking" } -frame-support = { path = "../../../frame/support" } -frame-system = { path = "../../../frame/system" } -sc-block-builder = { path = "../../../client/block-builder" } -sc-chain-spec = { path = "../../../client/chain-spec", default-features = false } -sc-cli = { path = "../../../client/cli", default-features = false } -sc-client-api = { path = "../../../client/api" } -sc-client-db = { path = "../../../client/db", default-features = false } -sc-executor = { path = "../../../client/executor" } -sc-service = { path = "../../../client/service", default-features = false } -sc-sysinfo = { path = "../../../client/sysinfo" } -sp-api = { path = "../../../primitives/api" } -sp-blockchain = { path = "../../../primitives/blockchain" } -sp-core = { path = "../../../primitives/core" } -sp-database = { path = "../../../primitives/database" } -sp-externalities = { path = "../../../primitives/externalities" } -sp-genesis-builder = { path = "../../../primitives/genesis-builder" } -sp-inherents = { path = "../../../primitives/inherents" } -sp-keystore = { path = "../../../primitives/keystore" } -sp-runtime = { path = "../../../primitives/runtime" } -sp-state-machine = { path = "../../../primitives/state-machine" } -sp-storage = { path = "../../../primitives/storage" } -sp-trie = { path = "../../../primitives/trie" } -sp-io = { path = "../../../primitives/io" } -sp-wasm-interface = { path = "../../../primitives/wasm-interface" } -gethostname = "0.2.3" +thousands = { workspace = true } +frame-benchmarking = { workspace = true, default-features = true } +frame-support = { workspace = true, default-features = true } +frame-system = { workspace = true, default-features = true } +sc-block-builder = { workspace = true, default-features = true } +sc-chain-spec = { workspace = true } +sc-cli = { workspace = true } +sc-client-api = { workspace = true, default-features = true } +sc-client-db = { workspace = true } +sc-executor = { workspace = true, default-features = true } +sc-service = { workspace = true } +sc-sysinfo = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-database = { workspace = true, default-features = true } +sp-externalities = { workspace = true, default-features = true } +sp-genesis-builder = { workspace = true, default-features = true } +sp-inherents = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-state-machine = { workspace = true, default-features = true } +sp-storage = { workspace = true, default-features = true } +sp-trie = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-wasm-interface = { workspace = true, default-features = true } +gethostname = { workspace = true } [features] default = ["rocksdb"] diff --git a/substrate/utils/frame/generate-bags/Cargo.toml b/substrate/utils/frame/generate-bags/Cargo.toml index 2688254bd5ea3e63b1634107d6f15d27c97843e2..934028c9608dc9f6aeee45e6bec48c3cd5e700c9 100644 --- a/substrate/utils/frame/generate-bags/Cargo.toml +++ b/substrate/utils/frame/generate-bags/Cargo.toml @@ -13,12 +13,12 @@ workspace = true [dependencies] # FRAME -frame-support = { path = "../../../frame/support" } -frame-election-provider-support = { path = "../../../frame/election-provider-support" } -frame-system = { path = "../../../frame/system" } -pallet-staking = { path = "../../../frame/staking" } -sp-staking = { path = "../../../primitives/staking" } +frame-support = { workspace = true, default-features = true } +frame-election-provider-support = { workspace = true, default-features = true } +frame-system = { workspace = true, default-features = true } +pallet-staking = { workspace = true, default-features = true } +sp-staking = { workspace = true, default-features = true } # third party -chrono = { version = "0.4.31" } -num-format = "0.4.3" +chrono = { workspace = true } +num-format = { workspace = true } diff --git a/substrate/utils/frame/generate-bags/node-runtime/Cargo.toml b/substrate/utils/frame/generate-bags/node-runtime/Cargo.toml index 37d96d7e12b963b7777ac4f21e70e5c419515d37..6dcbca4b97e2457693079afe0de3d5eed767572c 100644 --- a/substrate/utils/frame/generate-bags/node-runtime/Cargo.toml +++ b/substrate/utils/frame/generate-bags/node-runtime/Cargo.toml @@ -13,8 +13,8 @@ publish = false workspace = true [dependencies] -kitchensink-runtime = { path = "../../../../bin/node/runtime" } -generate-bags = { path = ".." } +kitchensink-runtime = { workspace = true } +generate-bags = { workspace = true, default-features = true } # third-party -clap = { version = "4.5.3", features = ["derive"] } +clap = { features = ["derive"], workspace = true } diff --git a/substrate/utils/frame/omni-bencher/Cargo.toml b/substrate/utils/frame/omni-bencher/Cargo.toml index 0c2d1a1b32b1f973955795a7d883a3ef72b268aa..f8f44cb4b4387077d9c787512d11727202e0ee82 100644 --- a/substrate/utils/frame/omni-bencher/Cargo.toml +++ b/substrate/utils/frame/omni-bencher/Cargo.toml @@ -11,11 +11,11 @@ license.workspace = true workspace = true [dependencies] -clap = { version = "4.5.2", features = ["derive"] } -cumulus-primitives-proof-size-hostfunction = { path = "../../../../cumulus/primitives/proof-size-hostfunction" } -frame-benchmarking-cli = { path = "../benchmarking-cli", default-features = false } -sc-cli = { path = "../../../client/cli" } -sp-runtime = { path = "../../../primitives/runtime" } -sp-statement-store = { path = "../../../primitives/statement-store" } -env_logger = "0.11.2" +clap = { features = ["derive"], workspace = true } +cumulus-primitives-proof-size-hostfunction = { workspace = true, default-features = true } +frame-benchmarking-cli = { workspace = true } +sc-cli = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-statement-store = { workspace = true, default-features = true } +env_logger = { workspace = true } log = { workspace = true } diff --git a/substrate/utils/frame/remote-externalities/Cargo.toml b/substrate/utils/frame/remote-externalities/Cargo.toml index 2911d5eef65902af9a0bec6a679a89db9eb6fb7a..cc075da68c276ddc895585e733bbfc1995d337ac 100644 --- a/substrate/utils/frame/remote-externalities/Cargo.toml +++ b/substrate/utils/frame/remote-externalities/Cargo.toml @@ -15,24 +15,24 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -jsonrpsee = { version = "0.22", features = ["http-client"] } -codec = { package = "parity-scale-codec", version = "3.6.12" } +jsonrpsee = { features = ["http-client"], workspace = true } +codec = { workspace = true, default-features = true } log = { workspace = true, default-features = true } serde = { workspace = true, default-features = true } -sp-core = { path = "../../../primitives/core" } -sp-crypto-hashing = { path = "../../../primitives/crypto/hashing" } -sp-state-machine = { path = "../../../primitives/state-machine" } -sp-io = { path = "../../../primitives/io" } -sp-runtime = { path = "../../../primitives/runtime" } -tokio = { version = "1.22.0", features = ["macros", "rt-multi-thread"] } -substrate-rpc-client = { path = "../rpc/client" } -futures = "0.3.30" -indicatif = "0.17.7" -spinners = "4.1.0" -tokio-retry = "0.3.0" +sp-core = { workspace = true, default-features = true } +sp-crypto-hashing = { workspace = true, default-features = true } +sp-state-machine = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +tokio = { features = ["macros", "rt-multi-thread"], workspace = true, default-features = true } +substrate-rpc-client = { workspace = true, default-features = true } +futures = { workspace = true } +indicatif = { workspace = true } +spinners = { workspace = true } +tokio-retry = { workspace = true } [dev-dependencies] -sp-tracing = { path = "../../../primitives/tracing" } +sp-tracing = { workspace = true, default-features = true } [features] remote-test = [] diff --git a/substrate/utils/frame/remote-externalities/src/lib.rs b/substrate/utils/frame/remote-externalities/src/lib.rs index 0ecb98f31343aa050d9daa8f33445e858631813d..40864085349b090a947743cfa32016e1bb016fc7 100644 --- a/substrate/utils/frame/remote-externalities/src/lib.rs +++ b/substrate/utils/frame/remote-externalities/src/lib.rs @@ -22,10 +22,7 @@ use codec::{Compact, Decode, Encode}; use indicatif::{ProgressBar, ProgressStyle}; -use jsonrpsee::{ - core::params::ArrayParams, - http_client::{HttpClient, HttpClientBuilder}, -}; +use jsonrpsee::{core::params::ArrayParams, http_client::HttpClient}; use log::*; use serde::de::DeserializeOwned; use sp_core::{ @@ -190,7 +187,7 @@ impl Transport { } else { uri.clone() }; - let http_client = HttpClientBuilder::default() + let http_client = HttpClient::builder() .max_request_size(u32::MAX) .max_response_size(u32::MAX) .request_timeout(std::time::Duration::from_secs(60 * 5)) @@ -1383,7 +1380,7 @@ mod remote_tests { init_logger(); // create an ext with children keys - let child_ext = Builder::::new() + let mut child_ext = Builder::::new() .mode(Mode::Online(OnlineConfig { transport: endpoint().clone().into(), pallets: vec!["Proxy".to_owned()], @@ -1396,7 +1393,7 @@ mod remote_tests { .unwrap(); // create an ext without children keys - let ext = Builder::::new() + let mut ext = Builder::::new() .mode(Mode::Online(OnlineConfig { transport: endpoint().clone().into(), pallets: vec!["Proxy".to_owned()], diff --git a/substrate/utils/frame/rpc/client/Cargo.toml b/substrate/utils/frame/rpc/client/Cargo.toml index 501bb95b257949f2b91678d361d210c440057906..1300fae9fff29e6a4b31e85f536913e2cbe6fa05 100644 --- a/substrate/utils/frame/rpc/client/Cargo.toml +++ b/substrate/utils/frame/rpc/client/Cargo.toml @@ -15,13 +15,13 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -jsonrpsee = { version = "0.22", features = ["ws-client"] } -sc-rpc-api = { path = "../../../../client/rpc-api" } -async-trait = "0.1.79" +jsonrpsee = { features = ["ws-client"], workspace = true } +sc-rpc-api = { workspace = true, default-features = true } +async-trait = { workspace = true } serde = { workspace = true, default-features = true } -sp-runtime = { path = "../../../../primitives/runtime" } +sp-runtime = { workspace = true, default-features = true } log = { workspace = true, default-features = true } [dev-dependencies] -tokio = { version = "1.22.0", features = ["macros", "rt-multi-thread", "sync"] } -sp-core = { path = "../../../../primitives/core" } +tokio = { features = ["macros", "rt-multi-thread", "sync"], workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } diff --git a/substrate/utils/frame/rpc/state-trie-migration-rpc/Cargo.toml b/substrate/utils/frame/rpc/state-trie-migration-rpc/Cargo.toml index ee3bf5eb68d716548a4a738f80254cfe811c651f..c8ff281301e36b5d00a941550a89fc24ca87e80f 100644 --- a/substrate/utils/frame/rpc/state-trie-migration-rpc/Cargo.toml +++ b/substrate/utils/frame/rpc/state-trie-migration-rpc/Cargo.toml @@ -16,20 +16,20 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } +codec = { workspace = true } serde = { features = ["derive"], workspace = true, default-features = true } -sp-core = { path = "../../../../primitives/core" } -sp-state-machine = { path = "../../../../primitives/state-machine" } -sp-trie = { path = "../../../../primitives/trie" } -trie-db = "0.29.0" +sp-core = { workspace = true, default-features = true } +sp-state-machine = { workspace = true, default-features = true } +sp-trie = { workspace = true, default-features = true } +trie-db = { workspace = true, default-features = true } -jsonrpsee = { version = "0.22.5", features = ["client-core", "macros", "server-core"] } +jsonrpsee = { features = ["client-core", "macros", "server-core"], workspace = true } # Substrate Dependencies -sc-client-api = { path = "../../../../client/api" } -sc-rpc-api = { path = "../../../../client/rpc-api" } -sp-runtime = { path = "../../../../primitives/runtime" } +sc-client-api = { workspace = true, default-features = true } +sc-rpc-api = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } [dev-dependencies] serde_json = { workspace = true, default-features = true } diff --git a/substrate/utils/frame/rpc/support/Cargo.toml b/substrate/utils/frame/rpc/support/Cargo.toml index bf566f909ecb712d8b00a26717739243adb06129..e20bae730c7eeb98c35ac1105316b30f8c3058c3 100644 --- a/substrate/utils/frame/rpc/support/Cargo.toml +++ b/substrate/utils/frame/rpc/support/Cargo.toml @@ -15,17 +15,17 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12" } -jsonrpsee = { version = "0.22", features = ["jsonrpsee-types"] } +codec = { workspace = true, default-features = true } +jsonrpsee = { features = ["jsonrpsee-types"], workspace = true } serde = { workspace = true, default-features = true } -frame-support = { path = "../../../../frame/support" } -sc-rpc-api = { path = "../../../../client/rpc-api" } -sp-storage = { path = "../../../../primitives/storage" } +frame-support = { workspace = true, default-features = true } +sc-rpc-api = { workspace = true, default-features = true } +sp-storage = { workspace = true, default-features = true } [dev-dependencies] -scale-info = "2.11.1" -jsonrpsee = { version = "0.22", features = ["jsonrpsee-types", "ws-client"] } -tokio = "1.37" -sp-core = { path = "../../../../primitives/core" } -sp-runtime = { path = "../../../../primitives/runtime" } -frame-system = { path = "../../../../frame/system" } +scale-info = { workspace = true, default-features = true } +jsonrpsee = { features = ["jsonrpsee-types", "ws-client"], workspace = true } +tokio = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +frame-system = { workspace = true, default-features = true } diff --git a/substrate/utils/frame/rpc/system/Cargo.toml b/substrate/utils/frame/rpc/system/Cargo.toml index 75d24e8e210fcde7822b6c53079a2f958f1d956a..4e866113fd2ee09e0e63c73eecc82c5cdd8191c1 100644 --- a/substrate/utils/frame/rpc/system/Cargo.toml +++ b/substrate/utils/frame/rpc/system/Cargo.toml @@ -16,27 +16,27 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -futures = "0.3.30" -codec = { package = "parity-scale-codec", version = "3.6.12" } -docify = "0.2.0" -jsonrpsee = { version = "0.22.5", features = [ +futures = { workspace = true } +codec = { workspace = true, default-features = true } +docify = { workspace = true } +jsonrpsee = { features = [ "client-core", "macros", "server-core", -] } +], workspace = true } log = { workspace = true, default-features = true } -frame-system-rpc-runtime-api = { path = "../../../../frame/system/rpc/runtime-api" } -sc-rpc-api = { path = "../../../../client/rpc-api" } -sc-transaction-pool-api = { path = "../../../../client/transaction-pool/api" } -sp-api = { path = "../../../../primitives/api" } -sp-block-builder = { path = "../../../../primitives/block-builder" } -sp-blockchain = { path = "../../../../primitives/blockchain" } -sp-core = { path = "../../../../primitives/core" } -sp-runtime = { path = "../../../../primitives/runtime" } +frame-system-rpc-runtime-api = { workspace = true, default-features = true } +sc-rpc-api = { workspace = true, default-features = true } +sc-transaction-pool-api = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-block-builder = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } [dev-dependencies] -sc-transaction-pool = { path = "../../../../client/transaction-pool" } -tokio = "1.37" -assert_matches = "1.3.0" -sp-tracing = { path = "../../../../primitives/tracing" } -substrate-test-runtime-client = { path = "../../../../test-utils/runtime/client" } +sc-transaction-pool = { workspace = true, default-features = true } +tokio = { workspace = true, default-features = true } +assert_matches = { workspace = true } +sp-tracing = { workspace = true, default-features = true } +substrate-test-runtime-client = { workspace = true } diff --git a/substrate/utils/prometheus/Cargo.toml b/substrate/utils/prometheus/Cargo.toml index 36527ac6183bb921266023320345afb9f6a89246..4b566c79ff901127d514509a6b2258ed621283a0 100644 --- a/substrate/utils/prometheus/Cargo.toml +++ b/substrate/utils/prometheus/Cargo.toml @@ -16,12 +16,12 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -hyper = { version = "0.14.16", default-features = false, features = ["http1", "server", "tcp"] } +hyper = { features = ["http1", "server", "tcp"], workspace = true } log = { workspace = true, default-features = true } -prometheus = { version = "0.13.0", default-features = false } +prometheus = { workspace = true } thiserror = { workspace = true } -tokio = { version = "1.22.0", features = ["parking_lot"] } +tokio = { features = ["parking_lot"], workspace = true, default-features = true } [dev-dependencies] -hyper = { version = "0.14.16", features = ["client"] } -tokio = { version = "1.22.0", features = ["rt-multi-thread"] } +hyper = { features = ["client"], workspace = true, default-features = true } +tokio = { features = ["rt-multi-thread"], workspace = true, default-features = true } diff --git a/substrate/utils/substrate-bip39/Cargo.toml b/substrate/utils/substrate-bip39/Cargo.toml index a46f81ee24d96d666495ee5cea5ca58b415a9cb0..e5270ea62f4c8d557ac538f0e02327209e7d403f 100644 --- a/substrate/utils/substrate-bip39/Cargo.toml +++ b/substrate/utils/substrate-bip39/Cargo.toml @@ -9,15 +9,15 @@ edition.workspace = true repository.workspace = true [dependencies] -hmac = "0.12.1" -pbkdf2 = { version = "0.12.2", default-features = false } -schnorrkel = { version = "0.11.4", default-features = false } -sha2 = { version = "0.10.7", default-features = false } -zeroize = { version = "1.4.3", default-features = false } +hmac = { workspace = true } +pbkdf2 = { workspace = true } +schnorrkel = { workspace = true } +sha2 = { workspace = true } +zeroize = { workspace = true } [dev-dependencies] -bip39 = "2.0.0" -rustc-hex = "2.1.0" +bip39 = { workspace = true } +rustc-hex = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/substrate/utils/wasm-builder/Cargo.toml b/substrate/utils/wasm-builder/Cargo.toml index 090955494f0a7572a08407c2aed26919863b3837..f084400c12e8daf5dc571a16e4df97ea26230a58 100644 --- a/substrate/utils/wasm-builder/Cargo.toml +++ b/substrate/utils/wasm-builder/Cargo.toml @@ -15,29 +15,29 @@ workspace = true targets = ["x86_64-unknown-linux-gnu"] [dependencies] -build-helper = "0.1.1" -cargo_metadata = "0.15.4" -console = "0.15.8" -strum = { version = "0.26.2", features = ["derive"] } -tempfile = "3.1.0" -toml = "0.8.8" -walkdir = "2.4.0" -sp-maybe-compressed-blob = { path = "../../primitives/maybe-compressed-blob" } -filetime = "0.2.16" -wasm-opt = "0.116" -parity-wasm = "0.45" +build-helper = { workspace = true } +cargo_metadata = { workspace = true } +console = { workspace = true } +strum = { features = ["derive"], workspace = true, default-features = true } +tempfile = { workspace = true } +toml = { workspace = true } +walkdir = { workspace = true } +sp-maybe-compressed-blob = { workspace = true, default-features = true } +filetime = { workspace = true } +wasm-opt = { workspace = true } +parity-wasm = { workspace = true } polkavm-linker = { workspace = true } # Dependencies required for the `metadata-hash` feature. -merkleized-metadata = { version = "0.1.0", optional = true } -sc-executor = { path = "../../client/executor", optional = true } -sp-core = { path = "../../primitives/core", optional = true } -sp-io = { path = "../../primitives/io", optional = true } -sp-version = { path = "../../primitives/version", optional = true } -frame-metadata = { version = "16.0.0", features = ["current"], optional = true } -codec = { package = "parity-scale-codec", version = "3.1.5", optional = true } -array-bytes = { version = "6.1", optional = true } -sp-tracing = { path = "../../primitives/tracing", optional = true } +merkleized-metadata = { optional = true, workspace = true } +sc-executor = { optional = true, workspace = true, default-features = true } +sp-core = { optional = true, workspace = true, default-features = true } +sp-io = { optional = true, workspace = true, default-features = true } +sp-version = { optional = true, workspace = true, default-features = true } +frame-metadata = { features = ["current"], optional = true, workspace = true, default-features = true } +codec = { optional = true, workspace = true, default-features = true } +array-bytes = { optional = true, workspace = true, default-features = true } +sp-tracing = { optional = true, workspace = true, default-features = true } [features] # Enable support for generating the metadata hash. diff --git a/templates/minimal/Cargo.toml b/templates/minimal/Cargo.toml index ca00cb84284524fc7d43d3b95f9cf4bb795ec506..ba96e139bcf194694aea029ca67825f948f30624 100644 --- a/templates/minimal/Cargo.toml +++ b/templates/minimal/Cargo.toml @@ -10,13 +10,13 @@ edition.workspace = true publish = false [dependencies] -minimal-template-node = { path = "./node" } -minimal-template-runtime = { path = "./runtime" } -pallet-minimal-template = { path = "./pallets/template" } -polkadot-sdk-docs = { path = "../../docs/sdk" } +minimal-template-node = { workspace = true } +minimal-template-runtime = { workspace = true } +pallet-minimal-template = { workspace = true, default-features = true } +polkadot-sdk-docs = { workspace = true } -frame = { package = "polkadot-sdk-frame", path = "../../substrate/frame" } +frame = { workspace = true, default-features = true } # How we build docs in rust-docs simple-mermaid = "0.1.1" -docify = "0.2.7" +docify = { workspace = true } diff --git a/templates/minimal/README.md b/templates/minimal/README.md index 583ba62420401cd3384e9200d51157f7b70e36e3..f00bfd4d48772ba7df8a035df757eb59d23626ca 100644 --- a/templates/minimal/README.md +++ b/templates/minimal/README.md @@ -11,12 +11,13 @@ -๐Ÿค This template is a minimal (in terms of complexity and the number of components) template for building a blockchain node. +* ๐Ÿค This template is a minimal (in terms of complexity and the number of components) +template for building a blockchain node. -๐Ÿ”ง Its runtime is configured of a single custom pallet as a starting point, and a handful of ready-made pallets +* ๐Ÿ”ง Its runtime is configured of a single custom pallet as a starting point, and a handful of ready-made pallets such as a [Balances pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_balances/index.html). -๐Ÿ‘ค The template has no consensus configured - it is best for experimenting with a single node network. +* ๐Ÿ‘ค The template has no consensus configured - it is best for experimenting with a single node network. ## Template Structure @@ -28,12 +29,12 @@ A Polkadot SDK based project such as this one consists of: ## Getting Started -๐Ÿฆ€ The template is using the Rust language. +* ๐Ÿฆ€ The template is using the Rust language. -๐Ÿ‘‰ Check the +* ๐Ÿ‘‰ Check the [Rust installation instructions](https://www.rust-lang.org/tools/install) for your system. -๐Ÿ› ๏ธ Depending on your operating system and Rust version, there might be additional +* ๐Ÿ› ๏ธ Depending on your operating system and Rust version, there might be additional packages required to compile this template - please take note of the Rust compiler output. ### Build @@ -69,32 +70,32 @@ Development chains: ### Connect with the Polkadot-JS Apps Front-End -๐ŸŒ You can interact with your local node using the +* ๐ŸŒ You can interact with your local node using the hosted version of the [Polkadot/Substrate Portal](https://polkadot.js.org/apps/#/explorer?rpc=ws://localhost:9944). -๐Ÿช A hosted version is also +* ๐Ÿช A hosted version is also available on [IPFS](https://dotapps.io/). -๐Ÿง‘โ€๐Ÿ”ง You can also find the source code and instructions for hosting your own instance in the +* ๐Ÿง‘โ€๐Ÿ”ง You can also find the source code and instructions for hosting your own instance in the [`polkadot-js/apps`](https://github.com/polkadot-js/apps) repository. ## Contributing -๐Ÿ”„ This template is automatically updated after releases in the main [Polkadot SDK monorepo](https://github.com/paritytech/polkadot-sdk). +* ๐Ÿ”„ This template is automatically updated after releases in the main [Polkadot SDK monorepo](https://github.com/paritytech/polkadot-sdk). -โžก๏ธ Any pull requests should be directed to this [source](https://github.com/paritytech/polkadot-sdk/tree/master/templates/minimal). +* โžก๏ธ Any pull requests should be directed to this [source](https://github.com/paritytech/polkadot-sdk/tree/master/templates/minimal). -๐Ÿ˜‡ Please refer to the monorepo's +* ๐Ÿ˜‡ Please refer to the monorepo's [contribution guidelines](https://github.com/paritytech/polkadot-sdk/blob/master/docs/contributor/CONTRIBUTING.md) and [Code of Conduct](https://github.com/paritytech/polkadot-sdk/blob/master/docs/contributor/CODE_OF_CONDUCT.md). ## Getting Help -๐Ÿง‘โ€๐Ÿซ To learn about Polkadot in general, [Polkadot.network](https://polkadot.network/) website is a good starting point. +* ๐Ÿง‘โ€๐Ÿซ To learn about Polkadot in general, [Polkadot.network](https://polkadot.network/) website is a good starting point. -๐Ÿง‘โ€๐Ÿ”ง For technical introduction, [here](https://github.com/paritytech/polkadot-sdk#-documentation) are +* ๐Ÿง‘โ€๐Ÿ”ง For technical introduction, [here](https://github.com/paritytech/polkadot-sdk#-documentation) are the Polkadot SDK documentation resources. -๐Ÿ‘ฅ Additionally, there are [GitHub issues](https://github.com/paritytech/polkadot-sdk/issues) and +* ๐Ÿ‘ฅ Additionally, there are [GitHub issues](https://github.com/paritytech/polkadot-sdk/issues) and [Substrate StackExchange](https://substrate.stackexchange.com/). diff --git a/templates/minimal/node/Cargo.toml b/templates/minimal/node/Cargo.toml index a10364a2854a9acfa9f7bf69ee885bc155facb79..70b24c19f8e7ce1b02f4570e5f34b974d7be0d8a 100644 --- a/templates/minimal/node/Cargo.toml +++ b/templates/minimal/node/Cargo.toml @@ -14,47 +14,47 @@ build = "build.rs" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -docify = "0.2.0" -clap = { version = "4.5.3", features = ["derive"] } -futures = { version = "0.3.30", features = ["thread-pool"] } -futures-timer = "3.0.1" -jsonrpsee = { version = "0.22", features = ["server"] } +docify = { workspace = true } +clap = { features = ["derive"], workspace = true } +futures = { features = ["thread-pool"], workspace = true } +futures-timer = { workspace = true } +jsonrpsee = { features = ["server"], workspace = true } serde_json = { workspace = true, default-features = true } -sc-cli = { path = "../../../substrate/client/cli" } -sc-executor = { path = "../../../substrate/client/executor" } -sc-network = { path = "../../../substrate/client/network" } -sc-service = { path = "../../../substrate/client/service" } -sc-telemetry = { path = "../../../substrate/client/telemetry" } -sc-transaction-pool = { path = "../../../substrate/client/transaction-pool" } -sc-transaction-pool-api = { path = "../../../substrate/client/transaction-pool/api" } -sc-consensus = { path = "../../../substrate/client/consensus/common" } -sc-consensus-manual-seal = { path = "../../../substrate/client/consensus/manual-seal" } -sc-rpc-api = { path = "../../../substrate/client/rpc-api" } -sc-basic-authorship = { path = "../../../substrate/client/basic-authorship" } -sc-offchain = { path = "../../../substrate/client/offchain" } -sc-client-api = { path = "../../../substrate/client/api" } - -sp-timestamp = { path = "../../../substrate/primitives/timestamp" } -sp-keyring = { path = "../../../substrate/primitives/keyring" } -sp-api = { path = "../../../substrate/primitives/api" } -sp-blockchain = { path = "../../../substrate/primitives/blockchain" } -sp-block-builder = { path = "../../../substrate/primitives/block-builder" } -sp-io = { path = "../../../substrate/primitives/io" } -sp-runtime = { path = "../../../substrate/primitives/runtime" } - -substrate-frame-rpc-system = { path = "../../../substrate/utils/frame/rpc/system" } +sc-cli = { workspace = true, default-features = true } +sc-executor = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sc-service = { workspace = true, default-features = true } +sc-telemetry = { workspace = true, default-features = true } +sc-transaction-pool = { workspace = true, default-features = true } +sc-transaction-pool-api = { workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } +sc-consensus-manual-seal = { workspace = true, default-features = true } +sc-rpc-api = { workspace = true, default-features = true } +sc-basic-authorship = { workspace = true, default-features = true } +sc-offchain = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } + +sp-timestamp = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-block-builder = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } + +substrate-frame-rpc-system = { workspace = true, default-features = true } # Once the native runtime is gone, there should be little to no dependency on FRAME here, and # certainly no dependency on the runtime. -frame = { package = "polkadot-sdk-frame", path = "../../../substrate/frame", features = [ +frame = { features = [ "experimental", "runtime", -] } -runtime = { package = "minimal-template-runtime", path = "../runtime" } +], workspace = true, default-features = true } +minimal-template-runtime = { workspace = true } [build-dependencies] -substrate-build-script-utils = { path = "../../../substrate/utils/build-script-utils" } +substrate-build-script-utils = { workspace = true, default-features = true } [features] default = [] diff --git a/templates/minimal/node/src/chain_spec.rs b/templates/minimal/node/src/chain_spec.rs index 7a3475bb167334e05f570ad4b46e8d471ec5a9a8..5b53b0f80ac00ec8315f449c62283da195ab89e5 100644 --- a/templates/minimal/node/src/chain_spec.rs +++ b/templates/minimal/node/src/chain_spec.rs @@ -15,7 +15,7 @@ // See the License for the specific language governing permissions and // limitations under the License. -use runtime::{BalancesConfig, SudoConfig, WASM_BINARY}; +use minimal_template_runtime::{BalancesConfig, SudoConfig, WASM_BINARY}; use sc_service::{ChainType, Properties}; use serde_json::{json, Value}; use sp_keyring::AccountKeyring; @@ -43,7 +43,7 @@ pub fn development_config() -> Result { /// Configure initial storage state for FRAME pallets. fn testnet_genesis() -> Value { use frame::traits::Get; - use runtime::interface::{Balance, MinimumBalance}; + use minimal_template_runtime::interface::{Balance, MinimumBalance}; let endowment = >::get().max(1) * 1000; let balances = AccountKeyring::iter() .map(|a| (a.to_account_id(), endowment)) diff --git a/templates/minimal/node/src/command.rs b/templates/minimal/node/src/command.rs index 432add922a7b585bba9be071a0a82dcd34e02dd7..c17f9bc55927ba46e0bb9ecad35b344229aff3c7 100644 --- a/templates/minimal/node/src/command.rs +++ b/templates/minimal/node/src/command.rs @@ -114,7 +114,9 @@ pub fn run() -> sc_cli::Result<()> { }, Some(Subcommand::ChainInfo(cmd)) => { let runner = cli.create_runner(cmd)?; - runner.sync_run(|config| cmd.run::(&config)) + runner.sync_run(|config| { + cmd.run::(&config) + }) }, None => { let runner = cli.create_runner(&cli.run)?; diff --git a/templates/minimal/node/src/rpc.rs b/templates/minimal/node/src/rpc.rs index 4b283bb2a66f4e18a6dffdbd2d387be93f8ff6a7..451e7b21dd0c1ce34ae5fa51a10271e699b56e88 100644 --- a/templates/minimal/node/src/rpc.rs +++ b/templates/minimal/node/src/rpc.rs @@ -23,7 +23,7 @@ #![warn(missing_docs)] use jsonrpsee::RpcModule; -use runtime::interface::{AccountId, Nonce, OpaqueBlock}; +use minimal_template_runtime::interface::{AccountId, Nonce, OpaqueBlock}; use sc_transaction_pool_api::TransactionPool; use sp_blockchain::{Error as BlockChainError, HeaderBackend, HeaderMetadata}; use std::sync::Arc; diff --git a/templates/minimal/node/src/service.rs b/templates/minimal/node/src/service.rs index 5a92627621bfcba71667ed198786a8f5e5aa9b5a..71b1ef65b6cad91d33039b13130abdcef414d5bd 100644 --- a/templates/minimal/node/src/service.rs +++ b/templates/minimal/node/src/service.rs @@ -16,7 +16,7 @@ // limitations under the License. use futures::FutureExt; -use runtime::{self, interface::OpaqueBlock as Block, RuntimeApi}; +use minimal_template_runtime::{interface::OpaqueBlock as Block, RuntimeApi}; use sc_client_api::backend::Backend; use sc_executor::WasmExecutor; use sc_service::{error::Error as ServiceError, Configuration, TaskManager}; @@ -34,8 +34,10 @@ type HostFunctions = #[cfg(not(feature = "runtime-benchmarks"))] type HostFunctions = sp_io::SubstrateHostFunctions; +#[docify::export] pub(crate) type FullClient = sc_service::TFullClient>; + type FullBackend = sc_service::TFullBackend; type FullSelectChain = sc_consensus::LongestChain; diff --git a/templates/minimal/pallets/template/Cargo.toml b/templates/minimal/pallets/template/Cargo.toml index f0abe3c6942de634e603f939aaa5ad8c19bcd20d..9d231fe7d7d45d3c4d1f35bee98d2bf7a57203a7 100644 --- a/templates/minimal/pallets/template/Cargo.toml +++ b/templates/minimal/pallets/template/Cargo.toml @@ -13,16 +13,16 @@ publish = false targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", features = [ +codec = { features = [ "derive", -], default-features = false } -scale-info = { version = "2.11.1", default-features = false, features = [ +], workspace = true } +scale-info = { features = [ "derive", -] } -frame = { package = "polkadot-sdk-frame", path = "../../../../substrate/frame", default-features = false, features = [ +], workspace = true } +frame = { features = [ "experimental", "runtime", -] } +], workspace = true } [features] diff --git a/templates/minimal/runtime/Cargo.toml b/templates/minimal/runtime/Cargo.toml index 42ea49ff404628ba1d2768302dc252c652a0ddaa..5d3cf8492e5227f2af4945d328acec216f1a5752 100644 --- a/templates/minimal/runtime/Cargo.toml +++ b/templates/minimal/runtime/Cargo.toml @@ -10,31 +10,31 @@ edition.workspace = true publish = false [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false } -scale-info = { version = "2.6.0", default-features = false } +codec = { workspace = true } +scale-info = { workspace = true } # this is a frame-based runtime, thus importing `frame` with runtime feature enabled. -frame = { package = "polkadot-sdk-frame", path = "../../../substrate/frame", default-features = false, features = [ +frame = { features = [ "experimental", "runtime", -] } +], workspace = true } # pallets that we want to use -pallet-balances = { path = "../../../substrate/frame/balances", default-features = false } -pallet-sudo = { path = "../../../substrate/frame/sudo", default-features = false } -pallet-timestamp = { path = "../../../substrate/frame/timestamp", default-features = false } -pallet-transaction-payment = { path = "../../../substrate/frame/transaction-payment", default-features = false } -pallet-transaction-payment-rpc-runtime-api = { path = "../../../substrate/frame/transaction-payment/rpc/runtime-api", default-features = false } +pallet-balances = { workspace = true } +pallet-sudo = { workspace = true } +pallet-timestamp = { workspace = true } +pallet-transaction-payment = { workspace = true } +pallet-transaction-payment-rpc-runtime-api = { workspace = true } # genesis builder that allows us to interact with runtime genesis config -sp-genesis-builder = { path = "../../../substrate/primitives/genesis-builder", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false, features = ["serde"] } +sp-genesis-builder = { workspace = true } +sp-runtime = { features = ["serde"], workspace = true } # local pallet templates -pallet-minimal-template = { path = "../pallets/template", default-features = false } +pallet-minimal-template = { workspace = true } [build-dependencies] -substrate-wasm-builder = { path = "../../../substrate/utils/wasm-builder", optional = true } +substrate-wasm-builder = { optional = true, workspace = true, default-features = true } [features] default = ["std"] diff --git a/templates/minimal/runtime/src/lib.rs b/templates/minimal/runtime/src/lib.rs index d2debbf5689fdf41b8436fb33eac52db5f573a3e..8c7867f4cc8cd1ec8b8435ec3c038e45da1a5700 100644 --- a/templates/minimal/runtime/src/lib.rs +++ b/templates/minimal/runtime/src/lib.rs @@ -99,27 +99,27 @@ mod runtime { /// Mandatory system pallet that should always be included in a FRAME runtime. #[runtime::pallet_index(0)] - pub type System = frame_system; + pub type System = frame_system::Pallet; /// Provides a way for consensus systems to set and check the onchain time. #[runtime::pallet_index(1)] - pub type Timestamp = pallet_timestamp; + pub type Timestamp = pallet_timestamp::Pallet; /// Provides the ability to keep track of balances. #[runtime::pallet_index(2)] - pub type Balances = pallet_balances; + pub type Balances = pallet_balances::Pallet; /// Provides a way to execute privileged functions. #[runtime::pallet_index(3)] - pub type Sudo = pallet_sudo; + pub type Sudo = pallet_sudo::Pallet; /// Provides the ability to charge for extrinsic execution. #[runtime::pallet_index(4)] - pub type TransactionPayment = pallet_transaction_payment; + pub type TransactionPayment = pallet_transaction_payment::Pallet; /// A minimal pallet template. #[runtime::pallet_index(5)] - pub type Template = pallet_minimal_template; + pub type Template = pallet_minimal_template::Pallet; } parameter_types! { diff --git a/templates/parachain/README.md b/templates/parachain/README.md index 01e9cc26d9af3e8c437486b6785d6f5eb8d6047c..a6ac91799b77728c4116c3e98554d5dca66e9929 100644 --- a/templates/parachain/README.md +++ b/templates/parachain/README.md @@ -1,22 +1,121 @@ -# Substrate Cumulus Parachain Template +

-A new [Cumulus](https://github.com/paritytech/polkadot-sdk/tree/master/cumulus)-based Substrate node, ready for hacking โ˜๏ธ.. +# Polkadot SDK's Parachain Template -This project is originally a fork of the -[Substrate Node Template](https://github.com/substrate-developer-hub/substrate-node-template) -modified to include dependencies required for registering this node as a **parathread** or -**parachain** to a **relay chain**. +Polkadot SDK Logo +Polkadot SDK Logo -The stand-alone version of this template is hosted on the -[Substrate Devhub Parachain Template](https://github.com/substrate-developer-hub/substrate-parachain-template/) -for each release of Polkadot. It is generated directly to the upstream -[Parachain Template in Cumulus](https://github.com/paritytech/polkadot-sdk/tree/master/cumulus/parachain-template) -at each release branch using the -[Substrate Template Generator](https://github.com/paritytech/substrate-template-generator/). +> This is a template for creating a [parachain](https://wiki.polkadot.network/docs/learn-parachains) based on Polkadot SDK. +> +> This template is automatically updated after releases in the main [Polkadot SDK monorepo](https://github.com/paritytech/polkadot-sdk). -๐Ÿ‘‰ Learn more about parachains [here](https://wiki.polkadot.network/docs/learn-parachains), and -parathreads [here](https://wiki.polkadot.network/docs/learn-parathreads). +
+* โซ This template provides a starting point to build a [parachain](https://wiki.polkadot.network/docs/learn-parachains). -๐Ÿง™ Learn about how to use this template and run your own parachain testnet for it in the -[Devhub Cumulus Tutorial](https://docs.substrate.io/tutorials/v3/cumulus/start-relay/). +* โ˜๏ธ It is based on the +[Cumulus](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/cumulus/index.html) framework. + +* ๐Ÿ”ง Its runtime is configured of a single custom pallet as a starting point, and a handful of ready-made pallets +such as a [Balances pallet](https://paritytech.github.io/polkadot-sdk/master/pallet_balances/index.html). + +* ๐Ÿ‘‰ Learn more about parachains [here](https://wiki.polkadot.network/docs/learn-parachains) + +## Template Structure + +A Polkadot SDK based project such as this one consists of: + +* ๐Ÿ’ฟ a [Node](./node/README.md) - the binary application. +* ๐Ÿงฎ the [Runtime](./runtime/README.md) - the core logic of the parachain. +* ๐ŸŽจ the [Pallets](./pallets/README.md) - from which the runtime is constructed. + +## Getting Started + +* ๐Ÿฆ€ The template is using the Rust language. + +* ๐Ÿ‘‰ Check the +[Rust installation instructions](https://www.rust-lang.org/tools/install) for your system. + +* ๐Ÿ› ๏ธ Depending on your operating system and Rust version, there might be additional +packages required to compile this template - please take note of the Rust compiler output. + +### Build + +๐Ÿ”จ Use the following command to build the node without launching it: + +```sh +cargo build --release +``` + +๐Ÿณ Alternatively, build the docker image: + +```sh +docker build . -t polkadot-sdk-parachain-template +``` + +### Local Development Chain + +๐ŸงŸ This project uses [Zombienet](https://github.com/paritytech/zombienet) to orchestrate the relaychain and parachain nodes. +You can grab a [released binary](https://github.com/paritytech/zombienet/releases/latest) or use an [npm version](https://www.npmjs.com/package/@zombienet/cli). + +This template produces a parachain node. +You still need a relaychain node - you can download the `polkadot` +(and the accompanying `polkadot-prepare-worker` and `polkadot-execute-worker`) +binaries from [Polkadot SDK releases](https://github.com/paritytech/polkadot-sdk/releases/latest). + +Make sure to bring the parachain node - as well as `polkadot`, `polkadot-prepare-worker`, `polkadot-execute-worker`, +and `zombienet` - into `PATH` like so: + +```sh +export PATH="./target/release/:$PATH" +``` + +This way, we can conveniently use them un the following steps. + +๐Ÿ‘ฅ The following command starts a local development chain, with a single relay chain node and a single parachain collator: + +```sh +zombienet --provider native spawn ./zombienet.toml + +# Alternatively, the npm version: +npx --yes @zombienet/cli --provider native spawn ./zombienet.toml +``` + +Development chains: + +* ๐Ÿงน Do not persist the state. +* ๐Ÿ’ฐ Are preconfigured with a genesis state that includes several prefunded development accounts. +* ๐Ÿง‘โ€โš–๏ธ Development accounts are used as validators, collators, and `sudo` accounts. + +### Connect with the Polkadot-JS Apps Front-End + +* ๐ŸŒ You can interact with your local node using the +hosted version of the Polkadot/Substrate Portal: +[relay chain](https://polkadot.js.org/apps/#/explorer?rpc=ws://localhost:9944) +and [parachain](https://polkadot.js.org/apps/#/explorer?rpc=ws://localhost:9988). + +* ๐Ÿช A hosted version is also +available on [IPFS](https://dotapps.io/). + +* ๐Ÿง‘โ€๐Ÿ”ง You can also find the source code and instructions for hosting your own instance in the +[`polkadot-js/apps`](https://github.com/polkadot-js/apps) repository. + +## Contributing + +* ๐Ÿ”„ This template is automatically updated after releases in the main [Polkadot SDK monorepo](https://github.com/paritytech/polkadot-sdk). + +* โžก๏ธ Any pull requests should be directed to this [source](https://github.com/paritytech/polkadot-sdk/tree/master/templates/parachain). + +* ๐Ÿ˜‡ Please refer to the monorepo's +[contribution guidelines](https://github.com/paritytech/polkadot-sdk/blob/master/docs/contributor/CONTRIBUTING.md) and +[Code of Conduct](https://github.com/paritytech/polkadot-sdk/blob/master/docs/contributor/CODE_OF_CONDUCT.md). + +## Getting Help + +* ๐Ÿง‘โ€๐Ÿซ To learn about Polkadot in general, [Polkadot.network](https://polkadot.network/) website is a good starting point. + +* ๐Ÿง‘โ€๐Ÿ”ง For technical introduction, [here](https://github.com/paritytech/polkadot-sdk#-documentation) are +the Polkadot SDK documentation resources. + +* ๐Ÿ‘ฅ Additionally, there are [GitHub issues](https://github.com/paritytech/polkadot-sdk/issues) and +[Substrate StackExchange](https://substrate.stackexchange.com/). diff --git a/templates/parachain/node/Cargo.toml b/templates/parachain/node/Cargo.toml index 1737c6a9df75e41b6d8252d8966c1464bfdc5bfb..7cf1f1fddc7b31e4adbb69f7e54f35cbcad28399 100644 --- a/templates/parachain/node/Cargo.toml +++ b/templates/parachain/node/Cargo.toml @@ -14,69 +14,69 @@ build = "build.rs" # name = "parachain-template-node" [dependencies] -clap = { version = "4.5.3", features = ["derive"] } +clap = { features = ["derive"], workspace = true } log = { workspace = true, default-features = true } -codec = { package = "parity-scale-codec", version = "3.6.12" } +codec = { workspace = true, default-features = true } serde = { features = ["derive"], workspace = true, default-features = true } -jsonrpsee = { version = "0.22", features = ["server"] } -futures = "0.3.28" +jsonrpsee = { features = ["server"], workspace = true } +futures = { workspace = true } serde_json = { workspace = true, default-features = true } -docify = "0.2.8" +docify = { workspace = true } # Local -parachain-template-runtime = { path = "../runtime" } +parachain-template-runtime = { workspace = true } # Substrate -frame-benchmarking = { path = "../../../substrate/frame/benchmarking" } -frame-benchmarking-cli = { path = "../../../substrate/utils/frame/benchmarking-cli" } -pallet-transaction-payment-rpc = { path = "../../../substrate/frame/transaction-payment/rpc" } -sc-basic-authorship = { path = "../../../substrate/client/basic-authorship" } -sc-chain-spec = { path = "../../../substrate/client/chain-spec" } -sc-cli = { path = "../../../substrate/client/cli" } -sc-client-api = { path = "../../../substrate/client/api" } -sc-offchain = { path = "../../../substrate/client/offchain" } -sc-consensus = { path = "../../../substrate/client/consensus/common" } -sc-executor = { path = "../../../substrate/client/executor" } -sc-network = { path = "../../../substrate/client/network" } -sc-network-sync = { path = "../../../substrate/client/network/sync" } -sc-rpc = { path = "../../../substrate/client/rpc" } -sc-service = { path = "../../../substrate/client/service" } -sc-sysinfo = { path = "../../../substrate/client/sysinfo" } -sc-telemetry = { path = "../../../substrate/client/telemetry" } -sc-tracing = { path = "../../../substrate/client/tracing" } -sc-transaction-pool = { path = "../../../substrate/client/transaction-pool" } -sc-transaction-pool-api = { path = "../../../substrate/client/transaction-pool/api" } -sp-api = { path = "../../../substrate/primitives/api" } -sp-block-builder = { path = "../../../substrate/primitives/block-builder" } -sp-blockchain = { path = "../../../substrate/primitives/blockchain" } -sp-consensus-aura = { path = "../../../substrate/primitives/consensus/aura" } -sp-core = { path = "../../../substrate/primitives/core" } -sp-keystore = { path = "../../../substrate/primitives/keystore" } -sp-io = { path = "../../../substrate/primitives/io" } -sp-runtime = { path = "../../../substrate/primitives/runtime" } -sp-timestamp = { path = "../../../substrate/primitives/timestamp" } -substrate-frame-rpc-system = { path = "../../../substrate/utils/frame/rpc/system" } -prometheus-endpoint = { package = "substrate-prometheus-endpoint", path = "../../../substrate/utils/prometheus" } +frame-benchmarking = { workspace = true, default-features = true } +frame-benchmarking-cli = { workspace = true, default-features = true } +pallet-transaction-payment-rpc = { workspace = true, default-features = true } +sc-basic-authorship = { workspace = true, default-features = true } +sc-chain-spec = { workspace = true, default-features = true } +sc-cli = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-offchain = { workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } +sc-executor = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sc-network-sync = { workspace = true, default-features = true } +sc-rpc = { workspace = true, default-features = true } +sc-service = { workspace = true, default-features = true } +sc-sysinfo = { workspace = true, default-features = true } +sc-telemetry = { workspace = true, default-features = true } +sc-tracing = { workspace = true, default-features = true } +sc-transaction-pool = { workspace = true, default-features = true } +sc-transaction-pool-api = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-block-builder = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-consensus-aura = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sp-keystore = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } +sp-timestamp = { workspace = true, default-features = true } +substrate-frame-rpc-system = { workspace = true, default-features = true } +prometheus-endpoint = { workspace = true, default-features = true } # Polkadot -polkadot-cli = { path = "../../../polkadot/cli", features = ["rococo-native"] } -polkadot-primitives = { path = "../../../polkadot/primitives" } -xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false } +polkadot-cli = { features = ["rococo-native"], workspace = true, default-features = true } +polkadot-primitives = { workspace = true, default-features = true } +xcm = { workspace = true } # Cumulus -cumulus-client-cli = { path = "../../../cumulus/client/cli" } -cumulus-client-collator = { path = "../../../cumulus/client/collator" } -cumulus-client-consensus-aura = { path = "../../../cumulus/client/consensus/aura" } -cumulus-client-consensus-common = { path = "../../../cumulus/client/consensus/common" } -cumulus-client-consensus-proposer = { path = "../../../cumulus/client/consensus/proposer" } -cumulus-client-service = { path = "../../../cumulus/client/service" } -cumulus-primitives-core = { path = "../../../cumulus/primitives/core" } -cumulus-primitives-parachain-inherent = { path = "../../../cumulus/primitives/parachain-inherent" } -cumulus-relay-chain-interface = { path = "../../../cumulus/client/relay-chain-interface" } -color-print = "0.3.4" +cumulus-client-cli = { workspace = true, default-features = true } +cumulus-client-collator = { workspace = true, default-features = true } +cumulus-client-consensus-aura = { workspace = true, default-features = true } +cumulus-client-consensus-common = { workspace = true, default-features = true } +cumulus-client-consensus-proposer = { workspace = true, default-features = true } +cumulus-client-service = { workspace = true, default-features = true } +cumulus-primitives-core = { workspace = true, default-features = true } +cumulus-primitives-parachain-inherent = { workspace = true, default-features = true } +cumulus-relay-chain-interface = { workspace = true, default-features = true } +color-print = { workspace = true } [build-dependencies] -substrate-build-script-utils = { path = "../../../substrate/utils/build-script-utils" } +substrate-build-script-utils = { workspace = true, default-features = true } [features] default = [] diff --git a/templates/parachain/node/README.md b/templates/parachain/node/README.md new file mode 100644 index 0000000000000000000000000000000000000000..350272c7b6efe1e53b4ed13296a00c89a8cf0639 --- /dev/null +++ b/templates/parachain/node/README.md @@ -0,0 +1,18 @@ +# Node + +โ„น๏ธ A node - in Polkadot - is a binary executable, whose primary purpose is to execute the [runtime](../runtime/README.md). + +๐Ÿ”— It communicates with other nodes in the network, and aims for +[consensus](https://wiki.polkadot.network/docs/learn-consensus) among them. + +โš™๏ธ It acts as a remote procedure call (RPC) server, allowing interaction with the blockchain. + +๐Ÿ‘‰ Learn more about the architecture, and a difference between a node and a runtime +[here](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/reference_docs/wasm_meta_protocol/index.html). + +๐Ÿ‘‡ Here are the most important files in this node template: + +- [`chain_spec.rs`](./src/chain_spec.rs): A chain specification is a source code file that defines the chain's +initial (genesis) state. +- [`service.rs`](./src/service.rs): This file defines the node implementation. +It's a place to configure consensus-related topics. diff --git a/templates/parachain/pallets/README.md b/templates/parachain/pallets/README.md new file mode 100644 index 0000000000000000000000000000000000000000..9fabe64a3e79a495a455b0f87b0957d364df5f30 --- /dev/null +++ b/templates/parachain/pallets/README.md @@ -0,0 +1,13 @@ +# Pallets + +โ„น๏ธ A pallet is a unit of encapsulated logic, with a clearly defined responsibility. A pallet is analogous to a +module in the runtime. + +๐Ÿ’ In this template, there is a simple custom pallet based on the FRAME framework. + +๐Ÿ‘‰ Learn more about FRAME +[here](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html). + +๐Ÿง‘โ€๐Ÿซ Please refer to +[this guide](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/guides/your_first_pallet/index.html) +to learn how to write a basic pallet. diff --git a/templates/parachain/pallets/template/Cargo.toml b/templates/parachain/pallets/template/Cargo.toml index 6c549c2c4a9b64f7bffd07f27bde04bcdb32442d..250895843e4f94705fe317779b75c96dab90c87a 100644 --- a/templates/parachain/pallets/template/Cargo.toml +++ b/templates/parachain/pallets/template/Cargo.toml @@ -13,22 +13,22 @@ publish = false targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", -] } -scale-info = { version = "2.11.1", default-features = false, features = [ +], workspace = true } +scale-info = { features = [ "derive", -] } +], workspace = true } # frame deps -frame-benchmarking = { path = "../../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-support = { path = "../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../substrate/frame/system", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } [dev-dependencies] -sp-core = { path = "../../../../substrate/primitives/core" } -sp-io = { path = "../../../../substrate/primitives/io" } -sp-runtime = { path = "../../../../substrate/primitives/runtime" } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/templates/parachain/pallets/template/README.md b/templates/parachain/pallets/template/README.md deleted file mode 100644 index 9e4dc55267d69c47fff971cb0427bcb2e0ff871c..0000000000000000000000000000000000000000 --- a/templates/parachain/pallets/template/README.md +++ /dev/null @@ -1 +0,0 @@ -License: MIT-0 diff --git a/templates/parachain/pallets/template/src/lib.rs b/templates/parachain/pallets/template/src/lib.rs index 11587d1df426f485139eab9e333b292768c6c571..0420e2b908215120d97c0849a798cc5dbc07ea84 100644 --- a/templates/parachain/pallets/template/src/lib.rs +++ b/templates/parachain/pallets/template/src/lib.rs @@ -1,8 +1,5 @@ #![cfg_attr(not(feature = "std"), no_std)] -/// Edit this file to define custom logic or remove it if it is not needed. -/// Learn more about FRAME and the core library of Substrate FRAME pallets: -/// pub use pallet::*; #[cfg(test)] @@ -16,6 +13,12 @@ pub mod weights; #[cfg(feature = "runtime-benchmarks")] mod benchmarking; +// +// +// +// To see a full list of `pallet` macros and their use cases, see: +// +// #[frame_support::pallet] pub mod pallet { use frame_support::{dispatch::DispatchResultWithPostInfo, pallet_prelude::*}; @@ -25,7 +28,9 @@ pub mod pallet { #[pallet::config] pub trait Config: frame_system::Config { /// Because this pallet emits events, it depends on the runtime's definition of an event. + /// type RuntimeEvent: From> + IsType<::RuntimeEvent>; + /// A type representing the weights required by the dispatchables of this pallet. type WeightInfo: crate::weights::WeightInfo; } @@ -33,24 +38,23 @@ pub mod pallet { #[pallet::pallet] pub struct Pallet(_); - // The pallet's runtime storage items. - // https://docs.substrate.io/v3/runtime/storage + /// The pallet's storage items. + /// + /// #[pallet::storage] - // Learn more about declaring storage items: - // https://docs.substrate.io/v3/runtime/storage#declaring-storage-items pub type Something = StorageValue<_, u32>; - // Pallets use events to inform users when important changes are made. - // https://docs.substrate.io/v3/runtime/events-and-errors + /// Pallets use events to inform users when important changes are made. + /// #[pallet::event] #[pallet::generate_deposit(pub(super) fn deposit_event)] pub enum Event { - /// Event documentation should end with an array that provides descriptive names for event - /// parameters. [something, who] - SomethingStored(u32, T::AccountId), + /// We usually use passive tense for events. + SomethingStored { something: u32, who: T::AccountId }, } - // Errors inform users that something went wrong. + /// Errors inform users that something went wrong. + /// #[pallet::error] pub enum Error { /// Error names should be descriptive. @@ -62,9 +66,10 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet {} - // Dispatchable functions allows users to interact with the pallet and invoke state changes. - // These functions materialize as "extrinsics", which are often compared to transactions. - // Dispatchable functions must be annotated with a weight and must return a DispatchResult. + /// Dispatchable functions allows users to interact with the pallet and invoke state changes. + /// These functions materialize as "extrinsics", which are often compared to transactions. + /// Dispatchable functions must be annotated with a weight and must return a DispatchResult. + /// #[pallet::call] impl Pallet { /// An example dispatchable that takes a singles value as a parameter, writes the value to @@ -74,14 +79,15 @@ pub mod pallet { pub fn do_something(origin: OriginFor, something: u32) -> DispatchResultWithPostInfo { // Check that the extrinsic was signed and get the signer. // This function will return an error if the extrinsic is not signed. - // https://docs.substrate.io/v3/runtime/origins + // let who = ensure_signed(origin)?; // Update storage. >::put(something); // Emit an event. - Self::deposit_event(Event::SomethingStored(something, who)); + Self::deposit_event(Event::SomethingStored { something, who }); + // Return a successful DispatchResultWithPostInfo Ok(().into()) } diff --git a/templates/parachain/pallets/template/src/mock.rs b/templates/parachain/pallets/template/src/mock.rs index ebb0598df97bf215321583a8cb0821ecddce1262..46e3117596f599ca923425dd72be7c01421b4ffa 100644 --- a/templates/parachain/pallets/template/src/mock.rs +++ b/templates/parachain/pallets/template/src/mock.rs @@ -1,25 +1,36 @@ -use frame_support::{derive_impl, parameter_types}; -use frame_system as system; -use sp_runtime::BuildStorage; - -type Block = frame_system::mocking::MockBlock; +use frame_support::{derive_impl, weights::constants::RocksDbWeight}; +use frame_system::{mocking::MockBlock, GenesisConfig}; +use sp_runtime::{traits::ConstU64, BuildStorage}; // Configure a mock runtime to test the pallet. -frame_support::construct_runtime!( - pub enum Test - { - System: frame_system::{Pallet, Call, Config, Storage, Event}, - TemplateModule: crate::{Pallet, Call, Storage, Event}, - } -); +#[frame_support::runtime] +mod test_runtime { + #[runtime::runtime] + #[runtime::derive( + RuntimeCall, + RuntimeEvent, + RuntimeError, + RuntimeOrigin, + RuntimeFreezeReason, + RuntimeHoldReason, + RuntimeSlashReason, + RuntimeLockId, + RuntimeTask + )] + pub struct Test; -parameter_types! { - pub const SS58Prefix: u8 = 42; + #[runtime::pallet_index(0)] + pub type System = frame_system; + #[runtime::pallet_index(1)] + pub type TemplateModule = crate; } #[derive_impl(frame_system::config_preludes::TestDefaultConfig)] -impl system::Config for Test { - type Block = Block; +impl frame_system::Config for Test { + type Nonce = u64; + type Block = MockBlock; + type BlockHashCount = ConstU64<250>; + type DbWeight = RocksDbWeight; } impl crate::Config for Test { @@ -29,5 +40,5 @@ impl crate::Config for Test { // Build genesis storage according to the mock runtime. pub fn new_test_ext() -> sp_io::TestExternalities { - system::GenesisConfig::::default().build_storage().unwrap().into() + GenesisConfig::::default().build_storage().unwrap().into() } diff --git a/templates/parachain/pallets/template/src/weights.rs b/templates/parachain/pallets/template/src/weights.rs index 7c42936e09f292de831d28460a3bc39436c3323f..5bfe28e8b71e36d7ee06127b3c1f769617e96494 100644 --- a/templates/parachain/pallets/template/src/weights.rs +++ b/templates/parachain/pallets/template/src/weights.rs @@ -4,7 +4,7 @@ //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev //! DATE: 2023-04-06, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` -//! HOSTNAME: `Alexs-MacBook-Pro-2.local`, CPU: `` +//! HOSTNAME: `_`, CPU: `` //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("dev"), DB CACHE: 1024 // Executed Command: diff --git a/templates/parachain/polkadot-launch/config.json b/templates/parachain/polkadot-launch/config.json deleted file mode 100644 index f03f983a4975e3289adcf8922f70cb12d7c9b084..0000000000000000000000000000000000000000 --- a/templates/parachain/polkadot-launch/config.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "relaychain": { - "bin": "../../polkadot/target/release/polkadot", - "chain": "rococo-local", - "nodes": [ - { - "name": "alice", - "wsPort": 9944, - "port": 30444 - }, - { - "name": "bob", - "wsPort": 9955, - "port": 30555 - } - ] - }, - "parachains": [ - { - "bin": "../target/release/polkadot-parachain", - "id": "200", - "balance": "1000000000000000000000", - "nodes": [ - { - "wsPort": 9988, - "name": "alice", - "port": 31200, - "flags": [ - "--force-authoring", - "--", - "--execution=wasm" - ] - } - ] - } - ], - "types": { - } -} diff --git a/templates/parachain/runtime/Cargo.toml b/templates/parachain/runtime/Cargo.toml index 059c793679694bd9c11b10384383f6e20301e5c5..de0ecad9b06ee4543aaf1e7072c3d0362e81977f 100644 --- a/templates/parachain/runtime/Cargo.toml +++ b/templates/parachain/runtime/Cargo.toml @@ -13,80 +13,80 @@ publish = false targets = ["x86_64-unknown-linux-gnu"] [build-dependencies] -substrate-wasm-builder = { path = "../../../substrate/utils/wasm-builder", optional = true } -docify = "0.2.8" +substrate-wasm-builder = { optional = true, workspace = true, default-features = true } +docify = { workspace = true } [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", -] } -hex-literal = { version = "0.4.1", optional = true } +], workspace = true } +hex-literal = { optional = true, workspace = true, default-features = true } log = { workspace = true } -scale-info = { version = "2.11.1", default-features = false, features = [ +scale-info = { features = [ "derive", -] } -smallvec = "1.11.0" -docify = "0.2.8" +], workspace = true } +smallvec = { workspace = true, default-features = true } +docify = { workspace = true } # Local -pallet-parachain-template = { path = "../pallets/template", default-features = false } +pallet-parachain-template = { workspace = true } # Substrate / FRAME -frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-executive = { path = "../../../substrate/frame/executive", default-features = false } -frame-metadata-hash-extension = { path = "../../../substrate/frame/metadata-hash-extension", default-features = false } -frame-support = { path = "../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -frame-system-benchmarking = { path = "../../../substrate/frame/system/benchmarking", default-features = false, optional = true } -frame-system-rpc-runtime-api = { path = "../../../substrate/frame/system/rpc/runtime-api", default-features = false } -frame-try-runtime = { path = "../../../substrate/frame/try-runtime", default-features = false, optional = true } +frame-benchmarking = { optional = true, workspace = true } +frame-executive = { workspace = true } +frame-metadata-hash-extension = { workspace = true } +frame-support = { features = ["experimental"], workspace = true } +frame-system = { workspace = true } +frame-system-benchmarking = { optional = true, workspace = true } +frame-system-rpc-runtime-api = { workspace = true } +frame-try-runtime = { optional = true, workspace = true } # FRAME Pallets -pallet-aura = { path = "../../../substrate/frame/aura", default-features = false } -pallet-authorship = { path = "../../../substrate/frame/authorship", default-features = false } -pallet-balances = { path = "../../../substrate/frame/balances", default-features = false } -pallet-message-queue = { path = "../../../substrate/frame/message-queue", default-features = false } -pallet-session = { path = "../../../substrate/frame/session", default-features = false } -pallet-sudo = { path = "../../../substrate/frame/sudo", default-features = false } -pallet-timestamp = { path = "../../../substrate/frame/timestamp", default-features = false } -pallet-transaction-payment = { path = "../../../substrate/frame/transaction-payment", default-features = false } -pallet-transaction-payment-rpc-runtime-api = { path = "../../../substrate/frame/transaction-payment/rpc/runtime-api", default-features = false } +pallet-aura = { workspace = true } +pallet-authorship = { workspace = true } +pallet-balances = { workspace = true } +pallet-message-queue = { workspace = true } +pallet-session = { workspace = true } +pallet-sudo = { workspace = true } +pallet-timestamp = { workspace = true } +pallet-transaction-payment = { workspace = true } +pallet-transaction-payment-rpc-runtime-api = { workspace = true } # Substrate Primitives -sp-api = { path = "../../../substrate/primitives/api", default-features = false } -sp-block-builder = { path = "../../../substrate/primitives/block-builder", default-features = false } -sp-consensus-aura = { path = "../../../substrate/primitives/consensus/aura", default-features = false } -sp-core = { path = "../../../substrate/primitives/core", default-features = false } -sp-genesis-builder = { path = "../../../substrate/primitives/genesis-builder", default-features = false } -sp-inherents = { path = "../../../substrate/primitives/inherents", default-features = false } -sp-offchain = { path = "../../../substrate/primitives/offchain", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false } -sp-session = { path = "../../../substrate/primitives/session", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } -sp-transaction-pool = { path = "../../../substrate/primitives/transaction-pool", default-features = false } -sp-version = { path = "../../../substrate/primitives/version", default-features = false } +sp-api = { workspace = true } +sp-block-builder = { workspace = true } +sp-consensus-aura = { workspace = true } +sp-core = { workspace = true } +sp-genesis-builder = { workspace = true } +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 } # Polkadot -pallet-xcm = { path = "../../../polkadot/xcm/pallet-xcm", default-features = false } -polkadot-parachain-primitives = { path = "../../../polkadot/parachain", default-features = false } -polkadot-runtime-common = { path = "../../../polkadot/runtime/common", default-features = false } -xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false } -xcm-builder = { package = "staging-xcm-builder", path = "../../../polkadot/xcm/xcm-builder", default-features = false } -xcm-executor = { package = "staging-xcm-executor", path = "../../../polkadot/xcm/xcm-executor", default-features = false } +pallet-xcm = { workspace = true } +polkadot-parachain-primitives = { workspace = true } +polkadot-runtime-common = { workspace = true } +xcm = { workspace = true } +xcm-builder = { workspace = true } +xcm-executor = { workspace = true } # Cumulus -cumulus-pallet-aura-ext = { path = "../../../cumulus/pallets/aura-ext", default-features = false } -cumulus-pallet-parachain-system = { path = "../../../cumulus/pallets/parachain-system", default-features = false } -cumulus-pallet-session-benchmarking = { path = "../../../cumulus/pallets/session-benchmarking", default-features = false } -cumulus-pallet-xcm = { path = "../../../cumulus/pallets/xcm", default-features = false } -cumulus-pallet-xcmp-queue = { path = "../../../cumulus/pallets/xcmp-queue", default-features = false } -cumulus-primitives-aura = { path = "../../../cumulus/primitives/aura", default-features = false } -cumulus-primitives-core = { path = "../../../cumulus/primitives/core", default-features = false } -cumulus-primitives-utility = { path = "../../../cumulus/primitives/utility", default-features = false } -cumulus-primitives-storage-weight-reclaim = { path = "../../../cumulus/primitives/storage-weight-reclaim", default-features = false } -pallet-collator-selection = { path = "../../../cumulus/pallets/collator-selection", default-features = false } -parachains-common = { path = "../../../cumulus/parachains/common", default-features = false } -parachain-info = { package = "staging-parachain-info", path = "../../../cumulus/parachains/pallets/parachain-info", default-features = false } +cumulus-pallet-aura-ext = { workspace = true } +cumulus-pallet-parachain-system = { workspace = true } +cumulus-pallet-session-benchmarking = { workspace = true } +cumulus-pallet-xcm = { workspace = true } +cumulus-pallet-xcmp-queue = { workspace = true } +cumulus-primitives-aura = { workspace = true } +cumulus-primitives-core = { workspace = true } +cumulus-primitives-utility = { workspace = true } +cumulus-primitives-storage-weight-reclaim = { workspace = true } +pallet-collator-selection = { workspace = true } +parachains-common = { workspace = true } +parachain-info = { workspace = true } [features] default = ["std"] diff --git a/templates/parachain/runtime/README.md b/templates/parachain/runtime/README.md new file mode 100644 index 0000000000000000000000000000000000000000..acd5939fc54226774f01ca9d52d1830218dcd18d --- /dev/null +++ b/templates/parachain/runtime/README.md @@ -0,0 +1,10 @@ +# Runtime + +โ„น๏ธ The runtime (in other words, a state transition function), refers to the core logic of the parachain that is +responsible for validating blocks and executing the state changes they define. + +๐Ÿ’ The runtime in this template is constructed using ready-made FRAME pallets that ship with +[Polkadot SDK](https://github.com/paritytech/polkadot-sdk), and a [template for a custom pallet](../pallets/README.md). + +๐Ÿ‘‰ Learn more about FRAME +[here](https://paritytech.github.io/polkadot-sdk/master/polkadot_sdk_docs/polkadot_sdk/frame_runtime/index.html). diff --git a/templates/parachain/runtime/src/configs/mod.rs b/templates/parachain/runtime/src/configs/mod.rs index 63e6a67a90638266820bce44e8aee75a544681bc..8a410a27e4a7bd270f661ec0b7cd99c8ef1416f9 100644 --- a/templates/parachain/runtime/src/configs/mod.rs +++ b/templates/parachain/runtime/src/configs/mod.rs @@ -32,7 +32,9 @@ use frame_support::{ derive_impl, dispatch::DispatchClass, parameter_types, - traits::{ConstBool, ConstU32, ConstU64, ConstU8, EitherOfDiverse, TransformOrigin}, + traits::{ + ConstBool, ConstU32, ConstU64, ConstU8, EitherOfDiverse, TransformOrigin, VariantCountOf, + }, weights::{ConstantMultiplier, Weight}, PalletId, }; @@ -154,8 +156,8 @@ impl pallet_balances::Config for Runtime { type ReserveIdentifier = [u8; 8]; type RuntimeHoldReason = RuntimeHoldReason; type RuntimeFreezeReason = RuntimeFreezeReason; - type FreezeIdentifier = (); - type MaxFreezes = ConstU32<0>; + type FreezeIdentifier = RuntimeFreezeReason; + type MaxFreezes = VariantCountOf; } parameter_types! { diff --git a/templates/parachain/runtime/src/lib.rs b/templates/parachain/runtime/src/lib.rs index 987b88af8444dac73fa1b8972e78973f35ea869d..6e6491a19adf6b41f4fcfa28aa62f6bf97e12b3e 100644 --- a/templates/parachain/runtime/src/lib.rs +++ b/templates/parachain/runtime/src/lib.rs @@ -7,6 +7,8 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); pub mod apis; +#[cfg(feature = "runtime-benchmarks")] +mod benchmarks; mod configs; mod weights; @@ -22,12 +24,9 @@ use sp_std::prelude::*; use sp_version::NativeVersion; use sp_version::RuntimeVersion; -use frame_support::{ - construct_runtime, - weights::{ - constants::WEIGHT_REF_TIME_PER_SECOND, Weight, WeightToFeeCoefficient, - WeightToFeeCoefficients, WeightToFeePolynomial, - }, +use frame_support::weights::{ + constants::WEIGHT_REF_TIME_PER_SECOND, Weight, WeightToFeeCoefficient, WeightToFeeCoefficients, + WeightToFeePolynomial, }; pub use sp_consensus_aura::sr25519::AuthorityId as AuraId; pub use sp_runtime::{MultiAddress, Perbill, Permill}; @@ -232,43 +231,69 @@ pub fn native_version() -> NativeVersion { } // Create the runtime by composing the FRAME pallets that were previously configured. -construct_runtime!( - pub enum Runtime { - // System support stuff. - System: frame_system = 0, - ParachainSystem: cumulus_pallet_parachain_system = 1, - Timestamp: pallet_timestamp = 2, - ParachainInfo: parachain_info = 3, - - // Monetary stuff. - Balances: pallet_balances = 10, - TransactionPayment: pallet_transaction_payment = 11, - - // Governance - Sudo: pallet_sudo = 15, - - // Collator support. The order of these 4 are important and shall not change. - Authorship: pallet_authorship = 20, - CollatorSelection: pallet_collator_selection = 21, - Session: pallet_session = 22, - Aura: pallet_aura = 23, - AuraExt: cumulus_pallet_aura_ext = 24, - - // XCM helpers. - XcmpQueue: cumulus_pallet_xcmp_queue = 30, - PolkadotXcm: pallet_xcm = 31, - CumulusXcm: cumulus_pallet_xcm = 32, - MessageQueue: pallet_message_queue = 33, - - // Template - TemplatePallet: pallet_parachain_template = 50, - } -); +#[frame_support::runtime] +mod runtime { + #[runtime::runtime] + #[runtime::derive( + RuntimeCall, + RuntimeEvent, + RuntimeError, + RuntimeOrigin, + RuntimeFreezeReason, + RuntimeHoldReason, + RuntimeSlashReason, + RuntimeLockId, + RuntimeTask + )] + pub struct Runtime; + + #[runtime::pallet_index(0)] + pub type System = frame_system; + #[runtime::pallet_index(1)] + pub type ParachainSystem = cumulus_pallet_parachain_system; + #[runtime::pallet_index(2)] + pub type Timestamp = pallet_timestamp; + #[runtime::pallet_index(3)] + pub type ParachainInfo = parachain_info; + + // Monetary stuff. + #[runtime::pallet_index(10)] + pub type Balances = pallet_balances; + #[runtime::pallet_index(11)] + pub type TransactionPayment = pallet_transaction_payment; + + // Governance + #[runtime::pallet_index(15)] + pub type Sudo = pallet_sudo; + + // Collator support. The order of these 4 are important and shall not change. + #[runtime::pallet_index(20)] + pub type Authorship = pallet_authorship; + #[runtime::pallet_index(21)] + pub type CollatorSelection = pallet_collator_selection; + #[runtime::pallet_index(22)] + pub type Session = pallet_session; + #[runtime::pallet_index(23)] + pub type Aura = pallet_aura; + #[runtime::pallet_index(24)] + pub type AuraExt = cumulus_pallet_aura_ext; + + // XCM helpers. + #[runtime::pallet_index(30)] + pub type XcmpQueue = cumulus_pallet_xcmp_queue; + #[runtime::pallet_index(31)] + pub type PolkadotXcm = pallet_xcm; + #[runtime::pallet_index(32)] + pub type CumulusXcm = cumulus_pallet_xcm; + #[runtime::pallet_index(33)] + pub type MessageQueue = pallet_message_queue; + + // Template + #[runtime::pallet_index(50)] + pub type TemplatePallet = pallet_parachain_template; +} cumulus_pallet_parachain_system::register_validate_block! { Runtime = Runtime, BlockExecutor = cumulus_pallet_aura_ext::BlockExecutor::, } - -#[cfg(feature = "runtime-benchmarks")] -mod benchmarks; diff --git a/templates/parachain/zombienet.toml b/templates/parachain/zombienet.toml new file mode 100644 index 0000000000000000000000000000000000000000..336ba1af4dde56a78208e555fdad1d732696db27 --- /dev/null +++ b/templates/parachain/zombienet.toml @@ -0,0 +1,16 @@ +[relaychain] +default_command = "polkadot" +chain = "dev" + +[[relaychain.nodes]] +name = "alice" +validator = true +ws_port = 9944 + +[[parachains]] +id = 1000 + +[parachains.collator] +name = "alice" +ws_port = 9988 +command = "parachain-template-node" diff --git a/templates/solochain/node/Cargo.toml b/templates/solochain/node/Cargo.toml index 4e8b81840900d3365f569ce96ecb642eb560d6d9..068284c6c3ea7c63e57a9c9039e091488e31a6a8 100644 --- a/templates/solochain/node/Cargo.toml +++ b/templates/solochain/node/Cargo.toml @@ -15,54 +15,54 @@ build = "build.rs" targets = ["x86_64-unknown-linux-gnu"] [dependencies] -clap = { version = "4.5.3", features = ["derive"] } -futures = { version = "0.3.30", features = ["thread-pool"] } +clap = { features = ["derive"], workspace = true } +futures = { features = ["thread-pool"], workspace = true } serde_json = { workspace = true, default-features = true } -jsonrpsee = { version = "0.22", features = ["server"] } +jsonrpsee = { features = ["server"], workspace = true } # substrate client -sc-cli = { path = "../../../substrate/client/cli" } -sp-core = { path = "../../../substrate/primitives/core" } -sc-executor = { path = "../../../substrate/client/executor" } -sc-network = { path = "../../../substrate/client/network" } -sc-service = { path = "../../../substrate/client/service" } -sc-telemetry = { path = "../../../substrate/client/telemetry" } -sc-transaction-pool = { path = "../../../substrate/client/transaction-pool" } -sc-transaction-pool-api = { path = "../../../substrate/client/transaction-pool/api" } -sc-offchain = { path = "../../../substrate/client/offchain" } -sc-consensus-aura = { path = "../../../substrate/client/consensus/aura" } -sp-consensus-aura = { path = "../../../substrate/primitives/consensus/aura" } -sc-consensus = { path = "../../../substrate/client/consensus/common" } -sc-consensus-grandpa = { path = "../../../substrate/client/consensus/grandpa" } -sp-consensus-grandpa = { path = "../../../substrate/primitives/consensus/grandpa" } -sc-client-api = { path = "../../../substrate/client/api" } -sc-rpc-api = { path = "../../../substrate/client/rpc-api" } -sc-basic-authorship = { path = "../../../substrate/client/basic-authorship" } +sc-cli = { workspace = true, default-features = true } +sp-core = { workspace = true, default-features = true } +sc-executor = { workspace = true, default-features = true } +sc-network = { workspace = true, default-features = true } +sc-service = { workspace = true, default-features = true } +sc-telemetry = { workspace = true, default-features = true } +sc-transaction-pool = { workspace = true, default-features = true } +sc-transaction-pool-api = { workspace = true, default-features = true } +sc-offchain = { workspace = true, default-features = true } +sc-consensus-aura = { workspace = true, default-features = true } +sp-consensus-aura = { workspace = true, default-features = true } +sc-consensus = { workspace = true, default-features = true } +sc-consensus-grandpa = { workspace = true, default-features = true } +sp-consensus-grandpa = { workspace = true, default-features = true } +sc-client-api = { workspace = true, default-features = true } +sc-rpc-api = { workspace = true, default-features = true } +sc-basic-authorship = { workspace = true, default-features = true } # substrate primitives -sp-runtime = { path = "../../../substrate/primitives/runtime" } -sp-io = { path = "../../../substrate/primitives/io" } -sp-timestamp = { path = "../../../substrate/primitives/timestamp" } -sp-inherents = { path = "../../../substrate/primitives/inherents" } -sp-keyring = { path = "../../../substrate/primitives/keyring" } -sp-api = { path = "../../../substrate/primitives/api" } -sp-blockchain = { path = "../../../substrate/primitives/blockchain" } -sp-block-builder = { path = "../../../substrate/primitives/block-builder" } +sp-runtime = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-timestamp = { workspace = true, default-features = true } +sp-inherents = { workspace = true, default-features = true } +sp-keyring = { workspace = true, default-features = true } +sp-api = { workspace = true, default-features = true } +sp-blockchain = { workspace = true, default-features = true } +sp-block-builder = { workspace = true, default-features = true } # frame and pallets -frame-system = { path = "../../../substrate/frame/system" } -pallet-transaction-payment = { path = "../../../substrate/frame/transaction-payment", default-features = false } -pallet-transaction-payment-rpc = { path = "../../../substrate/frame/transaction-payment/rpc" } -substrate-frame-rpc-system = { path = "../../../substrate/utils/frame/rpc/system" } +frame-system = { workspace = true, default-features = true } +pallet-transaction-payment = { workspace = true } +pallet-transaction-payment-rpc = { workspace = true, default-features = true } +substrate-frame-rpc-system = { workspace = true, default-features = true } # These dependencies are used for runtime benchmarking -frame-benchmarking-cli = { path = "../../../substrate/utils/frame/benchmarking-cli" } +frame-benchmarking-cli = { workspace = true, default-features = true } # Local Dependencies -solochain-template-runtime = { path = "../runtime" } +solochain-template-runtime = { workspace = true } [build-dependencies] -substrate-build-script-utils = { path = "../../../substrate/utils/build-script-utils" } +substrate-build-script-utils = { workspace = true, default-features = true } [features] default = [] diff --git a/templates/solochain/pallets/template/Cargo.toml b/templates/solochain/pallets/template/Cargo.toml index 5b8349b5d678cdcf72befebf77b8d4598d61b261..e658a30d368483d81aa343d6a4a7d2a7a416e000 100644 --- a/templates/solochain/pallets/template/Cargo.toml +++ b/templates/solochain/pallets/template/Cargo.toml @@ -13,22 +13,22 @@ publish = false targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", -] } -scale-info = { version = "2.11.1", default-features = false, features = [ +], workspace = true } +scale-info = { features = [ "derive", -] } +], workspace = true } # frame deps -frame-benchmarking = { path = "../../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-support = { path = "../../../../substrate/frame/support", default-features = false } -frame-system = { path = "../../../../substrate/frame/system", default-features = false } +frame-benchmarking = { optional = true, workspace = true } +frame-support = { workspace = true } +frame-system = { workspace = true } [dev-dependencies] -sp-core = { path = "../../../../substrate/primitives/core" } -sp-io = { path = "../../../../substrate/primitives/io" } -sp-runtime = { path = "../../../../substrate/primitives/runtime" } +sp-core = { workspace = true, default-features = true } +sp-io = { workspace = true, default-features = true } +sp-runtime = { workspace = true, default-features = true } [features] default = ["std"] diff --git a/templates/solochain/runtime/Cargo.toml b/templates/solochain/runtime/Cargo.toml index 0af3899a666995120738459be823a70debd23168..af1cd466ea00ffee6f12886665f02728a6e3a8f2 100644 --- a/templates/solochain/runtime/Cargo.toml +++ b/templates/solochain/runtime/Cargo.toml @@ -13,67 +13,67 @@ publish = false targets = ["x86_64-unknown-linux-gnu"] [dependencies] -codec = { package = "parity-scale-codec", version = "3.6.12", default-features = false, features = [ +codec = { features = [ "derive", -] } -scale-info = { version = "2.11.1", default-features = false, features = [ +], workspace = true } +scale-info = { features = [ "derive", "serde", -] } +], workspace = true } # frame -frame-support = { path = "../../../substrate/frame/support", default-features = false, features = ["experimental"] } -frame-system = { path = "../../../substrate/frame/system", default-features = false } -frame-try-runtime = { path = "../../../substrate/frame/try-runtime", default-features = false, optional = true } -frame-executive = { path = "../../../substrate/frame/executive", default-features = false } +frame-support = { features = ["experimental"], workspace = true } +frame-system = { workspace = true } +frame-try-runtime = { optional = true, workspace = true } +frame-executive = { workspace = true } # frame pallets -pallet-aura = { path = "../../../substrate/frame/aura", default-features = false } -pallet-balances = { path = "../../../substrate/frame/balances", default-features = false } -pallet-grandpa = { path = "../../../substrate/frame/grandpa", default-features = false } -pallet-sudo = { path = "../../../substrate/frame/sudo", default-features = false } -pallet-timestamp = { path = "../../../substrate/frame/timestamp", default-features = false } -pallet-transaction-payment = { path = "../../../substrate/frame/transaction-payment", default-features = false } +pallet-aura = { workspace = true } +pallet-balances = { workspace = true } +pallet-grandpa = { workspace = true } +pallet-sudo = { workspace = true } +pallet-timestamp = { workspace = true } +pallet-transaction-payment = { workspace = true } # primitives -sp-api = { path = "../../../substrate/primitives/api", default-features = false } -sp-block-builder = { path = "../../../substrate/primitives/block-builder", default-features = false } -sp-consensus-aura = { path = "../../../substrate/primitives/consensus/aura", default-features = false, features = [ +sp-api = { workspace = true } +sp-block-builder = { workspace = true } +sp-consensus-aura = { features = [ "serde", -] } -sp-consensus-grandpa = { path = "../../../substrate/primitives/consensus/grandpa", default-features = false, features = [ +], workspace = true } +sp-consensus-grandpa = { features = [ "serde", -] } -sp-core = { path = "../../../substrate/primitives/core", default-features = false, features = [ +], workspace = true } +sp-core = { features = [ "serde", -] } -sp-inherents = { path = "../../../substrate/primitives/inherents", default-features = false } -sp-offchain = { path = "../../../substrate/primitives/offchain", default-features = false } -sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false, features = [ +], workspace = true } +sp-inherents = { workspace = true } +sp-offchain = { workspace = true } +sp-runtime = { features = [ "serde", -] } -sp-session = { path = "../../../substrate/primitives/session", default-features = false } -sp-std = { path = "../../../substrate/primitives/std", default-features = false } -sp-storage = { path = "../../../substrate/primitives/storage", default-features = false } -sp-transaction-pool = { path = "../../../substrate/primitives/transaction-pool", default-features = false } -sp-version = { path = "../../../substrate/primitives/version", default-features = false, features = [ +], workspace = true } +sp-session = { workspace = true } +sp-std = { workspace = true } +sp-storage = { workspace = true } +sp-transaction-pool = { workspace = true } +sp-version = { features = [ "serde", -] } -sp-genesis-builder = { path = "../../../substrate/primitives/genesis-builder", default-features = false } +], workspace = true } +sp-genesis-builder = { workspace = true } # RPC related -frame-system-rpc-runtime-api = { path = "../../../substrate/frame/system/rpc/runtime-api", default-features = false } -pallet-transaction-payment-rpc-runtime-api = { path = "../../../substrate/frame/transaction-payment/rpc/runtime-api", default-features = false } +frame-system-rpc-runtime-api = { workspace = true } +pallet-transaction-payment-rpc-runtime-api = { workspace = true } # Used for runtime benchmarking -frame-benchmarking = { path = "../../../substrate/frame/benchmarking", default-features = false, optional = true } -frame-system-benchmarking = { path = "../../../substrate/frame/system/benchmarking", default-features = false, optional = true } +frame-benchmarking = { optional = true, workspace = true } +frame-system-benchmarking = { optional = true, workspace = true } # The pallet in this template. -pallet-template = { path = "../pallets/template", default-features = false } +pallet-template = { workspace = true } [build-dependencies] -substrate-wasm-builder = { path = "../../../substrate/utils/wasm-builder", optional = true } +substrate-wasm-builder = { optional = true, workspace = true, default-features = true } [features] default = ["std"] diff --git a/templates/solochain/runtime/src/lib.rs b/templates/solochain/runtime/src/lib.rs index 93a56fb0ad78f738e12b5172d96d8188ca0b00e8..c147845fe2fe8f37693435a45b8084a78b253667 100644 --- a/templates/solochain/runtime/src/lib.rs +++ b/templates/solochain/runtime/src/lib.rs @@ -18,7 +18,6 @@ use sp_std::prelude::*; use sp_version::NativeVersion; use sp_version::RuntimeVersion; -use frame_support::genesis_builder_helper::{build_state, get_preset}; pub use frame_support::{ construct_runtime, derive_impl, parameter_types, traits::{ @@ -33,6 +32,10 @@ pub use frame_support::{ }, StorageValue, }; +use frame_support::{ + genesis_builder_helper::{build_state, get_preset}, + traits::VariantCountOf, +}; pub use frame_system::Call as SystemCall; pub use pallet_balances::Call as BalancesCall; pub use pallet_timestamp::Call as TimestampCall; @@ -218,10 +221,10 @@ impl pallet_balances::Config for Runtime { type ExistentialDeposit = ConstU128; type AccountStore = System; type WeightInfo = pallet_balances::weights::SubstrateWeight; - type FreezeIdentifier = (); - type MaxFreezes = (); - type RuntimeHoldReason = (); - type RuntimeFreezeReason = (); + type FreezeIdentifier = RuntimeFreezeReason; + type MaxFreezes = VariantCountOf; + type RuntimeHoldReason = RuntimeHoldReason; + type RuntimeFreezeReason = RuntimeHoldReason; } parameter_types! { diff --git a/umbrella/Cargo.toml b/umbrella/Cargo.toml index d790b4f5949ca5259bc4749636b90f5f33f1412c..94ba09421d409e5a2daee0c702499be3df2d4dcd 100644 --- a/umbrella/Cargo.toml +++ b/umbrella/Cargo.toml @@ -68,6 +68,7 @@ std = [ "pallet-asset-conversion?/std", "pallet-asset-rate?/std", "pallet-asset-tx-payment?/std", + "pallet-assets-freezer?/std", "pallet-assets?/std", "pallet-atomic-swap?/std", "pallet-aura?/std", @@ -239,7 +240,7 @@ std = [ "substrate-bip39?/std", "testnet-parachains-constants?/std", "westend-runtime-constants?/std", - "xcm-fee-payment-runtime-api?/std", + "xcm-runtime-apis?/std", ] runtime-benchmarks = [ "assets-common?/runtime-benchmarks", @@ -263,6 +264,7 @@ runtime-benchmarks = [ "pallet-asset-conversion?/runtime-benchmarks", "pallet-asset-rate?/runtime-benchmarks", "pallet-asset-tx-payment?/runtime-benchmarks", + "pallet-assets-freezer?/runtime-benchmarks", "pallet-assets?/runtime-benchmarks", "pallet-babe?/runtime-benchmarks", "pallet-bags-list?/runtime-benchmarks", @@ -363,7 +365,7 @@ runtime-benchmarks = [ "staging-node-inspect?/runtime-benchmarks", "staging-xcm-builder?/runtime-benchmarks", "staging-xcm-executor?/runtime-benchmarks", - "xcm-fee-payment-runtime-api?/runtime-benchmarks", + "xcm-runtime-apis?/runtime-benchmarks", ] try-runtime = [ "cumulus-pallet-aura-ext?/try-runtime", @@ -385,6 +387,7 @@ try-runtime = [ "pallet-asset-conversion?/try-runtime", "pallet-asset-rate?/try-runtime", "pallet-asset-tx-payment?/try-runtime", + "pallet-assets-freezer?/try-runtime", "pallet-assets?/try-runtime", "pallet-atomic-swap?/try-runtime", "pallet-aura?/try-runtime", @@ -536,7 +539,7 @@ with-tracing = [ "sp-tracing?/with-tracing", "sp-tracing?/with-tracing", ] -runtime = ["assets-common", "binary-merkle-tree", "bp-asset-hub-rococo", "bp-asset-hub-westend", "bp-bridge-hub-cumulus", "bp-bridge-hub-kusama", "bp-bridge-hub-polkadot", "bp-bridge-hub-rococo", "bp-bridge-hub-westend", "bp-header-chain", "bp-kusama", "bp-messages", "bp-parachains", "bp-polkadot", "bp-polkadot-bulletin", "bp-polkadot-core", "bp-relayers", "bp-rococo", "bp-runtime", "bp-test-utils", "bp-westend", "bp-xcm-bridge-hub", "bp-xcm-bridge-hub-router", "bridge-hub-common", "bridge-runtime-common", "cumulus-pallet-aura-ext", "cumulus-pallet-dmp-queue", "cumulus-pallet-parachain-system", "cumulus-pallet-parachain-system-proc-macro", "cumulus-pallet-session-benchmarking", "cumulus-pallet-solo-to-para", "cumulus-pallet-xcm", "cumulus-pallet-xcmp-queue", "cumulus-ping", "cumulus-primitives-aura", "cumulus-primitives-core", "cumulus-primitives-parachain-inherent", "cumulus-primitives-proof-size-hostfunction", "cumulus-primitives-storage-weight-reclaim", "cumulus-primitives-timestamp", "cumulus-primitives-utility", "frame-benchmarking", "frame-benchmarking-pallet-pov", "frame-election-provider-solution-type", "frame-election-provider-support", "frame-executive", "frame-metadata-hash-extension", "frame-support", "frame-support-procedural", "frame-support-procedural-tools-derive", "frame-system", "frame-system-benchmarking", "frame-system-rpc-runtime-api", "frame-try-runtime", "pallet-alliance", "pallet-asset-conversion", "pallet-asset-conversion-ops", "pallet-asset-conversion-tx-payment", "pallet-asset-rate", "pallet-asset-tx-payment", "pallet-assets", "pallet-atomic-swap", "pallet-aura", "pallet-authority-discovery", "pallet-authorship", "pallet-babe", "pallet-bags-list", "pallet-balances", "pallet-beefy", "pallet-beefy-mmr", "pallet-bounties", "pallet-bridge-grandpa", "pallet-bridge-messages", "pallet-bridge-parachains", "pallet-bridge-relayers", "pallet-broker", "pallet-child-bounties", "pallet-collator-selection", "pallet-collective", "pallet-collective-content", "pallet-contracts", "pallet-contracts-proc-macro", "pallet-contracts-uapi", "pallet-conviction-voting", "pallet-core-fellowship", "pallet-delegated-staking", "pallet-democracy", "pallet-dev-mode", "pallet-election-provider-multi-phase", "pallet-election-provider-support-benchmarking", "pallet-elections-phragmen", "pallet-fast-unstake", "pallet-glutton", "pallet-grandpa", "pallet-identity", "pallet-im-online", "pallet-indices", "pallet-insecure-randomness-collective-flip", "pallet-lottery", "pallet-membership", "pallet-message-queue", "pallet-migrations", "pallet-mixnet", "pallet-mmr", "pallet-multisig", "pallet-nft-fractionalization", "pallet-nfts", "pallet-nfts-runtime-api", "pallet-nis", "pallet-node-authorization", "pallet-nomination-pools", "pallet-nomination-pools-benchmarking", "pallet-nomination-pools-runtime-api", "pallet-offences", "pallet-offences-benchmarking", "pallet-paged-list", "pallet-parameters", "pallet-preimage", "pallet-proxy", "pallet-ranked-collective", "pallet-recovery", "pallet-referenda", "pallet-remark", "pallet-root-offences", "pallet-root-testing", "pallet-safe-mode", "pallet-salary", "pallet-scheduler", "pallet-scored-pool", "pallet-session", "pallet-session-benchmarking", "pallet-skip-feeless-payment", "pallet-society", "pallet-staking", "pallet-staking-reward-curve", "pallet-staking-reward-fn", "pallet-staking-runtime-api", "pallet-state-trie-migration", "pallet-statement", "pallet-sudo", "pallet-timestamp", "pallet-tips", "pallet-transaction-payment", "pallet-transaction-payment-rpc-runtime-api", "pallet-transaction-storage", "pallet-treasury", "pallet-tx-pause", "pallet-uniques", "pallet-utility", "pallet-vesting", "pallet-whitelist", "pallet-xcm", "pallet-xcm-benchmarks", "pallet-xcm-bridge-hub", "pallet-xcm-bridge-hub-router", "parachains-common", "polkadot-core-primitives", "polkadot-parachain-primitives", "polkadot-primitives", "polkadot-runtime-common", "polkadot-runtime-metrics", "polkadot-runtime-parachains", "polkadot-sdk-frame", "rococo-runtime-constants", "sc-chain-spec-derive", "sc-tracing-proc-macro", "slot-range-helper", "snowbridge-beacon-primitives", "snowbridge-core", "snowbridge-ethereum", "snowbridge-outbound-queue-merkle-tree", "snowbridge-outbound-queue-runtime-api", "snowbridge-pallet-ethereum-client", "snowbridge-pallet-ethereum-client-fixtures", "snowbridge-pallet-inbound-queue", "snowbridge-pallet-inbound-queue-fixtures", "snowbridge-pallet-outbound-queue", "snowbridge-pallet-system", "snowbridge-router-primitives", "snowbridge-runtime-common", "snowbridge-system-runtime-api", "sp-api", "sp-api-proc-macro", "sp-application-crypto", "sp-arithmetic", "sp-authority-discovery", "sp-block-builder", "sp-consensus-aura", "sp-consensus-babe", "sp-consensus-beefy", "sp-consensus-grandpa", "sp-consensus-pow", "sp-consensus-slots", "sp-core", "sp-crypto-ec-utils", "sp-crypto-hashing", "sp-crypto-hashing-proc-macro", "sp-debug-derive", "sp-externalities", "sp-genesis-builder", "sp-inherents", "sp-io", "sp-keyring", "sp-keystore", "sp-metadata-ir", "sp-mixnet", "sp-mmr-primitives", "sp-npos-elections", "sp-offchain", "sp-runtime", "sp-runtime-interface", "sp-runtime-interface-proc-macro", "sp-session", "sp-staking", "sp-state-machine", "sp-statement-store", "sp-std", "sp-storage", "sp-timestamp", "sp-tracing", "sp-transaction-pool", "sp-transaction-storage-proof", "sp-trie", "sp-version", "sp-version-proc-macro", "sp-wasm-interface", "sp-weights", "staging-parachain-info", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", "substrate-bip39", "testnet-parachains-constants", "tracing-gum-proc-macro", "westend-runtime-constants", "xcm-fee-payment-runtime-api", "xcm-procedural"] +runtime = ["assets-common", "binary-merkle-tree", "bp-asset-hub-rococo", "bp-asset-hub-westend", "bp-bridge-hub-cumulus", "bp-bridge-hub-kusama", "bp-bridge-hub-polkadot", "bp-bridge-hub-rococo", "bp-bridge-hub-westend", "bp-header-chain", "bp-kusama", "bp-messages", "bp-parachains", "bp-polkadot", "bp-polkadot-bulletin", "bp-polkadot-core", "bp-relayers", "bp-rococo", "bp-runtime", "bp-test-utils", "bp-westend", "bp-xcm-bridge-hub", "bp-xcm-bridge-hub-router", "bridge-hub-common", "bridge-runtime-common", "cumulus-pallet-aura-ext", "cumulus-pallet-dmp-queue", "cumulus-pallet-parachain-system", "cumulus-pallet-parachain-system-proc-macro", "cumulus-pallet-session-benchmarking", "cumulus-pallet-solo-to-para", "cumulus-pallet-xcm", "cumulus-pallet-xcmp-queue", "cumulus-ping", "cumulus-primitives-aura", "cumulus-primitives-core", "cumulus-primitives-parachain-inherent", "cumulus-primitives-proof-size-hostfunction", "cumulus-primitives-storage-weight-reclaim", "cumulus-primitives-timestamp", "cumulus-primitives-utility", "frame-benchmarking", "frame-benchmarking-pallet-pov", "frame-election-provider-solution-type", "frame-election-provider-support", "frame-executive", "frame-metadata-hash-extension", "frame-support", "frame-support-procedural", "frame-support-procedural-tools-derive", "frame-system", "frame-system-benchmarking", "frame-system-rpc-runtime-api", "frame-try-runtime", "pallet-alliance", "pallet-asset-conversion", "pallet-asset-conversion-ops", "pallet-asset-conversion-tx-payment", "pallet-asset-rate", "pallet-asset-tx-payment", "pallet-assets", "pallet-assets-freezer", "pallet-atomic-swap", "pallet-aura", "pallet-authority-discovery", "pallet-authorship", "pallet-babe", "pallet-bags-list", "pallet-balances", "pallet-beefy", "pallet-beefy-mmr", "pallet-bounties", "pallet-bridge-grandpa", "pallet-bridge-messages", "pallet-bridge-parachains", "pallet-bridge-relayers", "pallet-broker", "pallet-child-bounties", "pallet-collator-selection", "pallet-collective", "pallet-collective-content", "pallet-contracts", "pallet-contracts-proc-macro", "pallet-contracts-uapi", "pallet-conviction-voting", "pallet-core-fellowship", "pallet-delegated-staking", "pallet-democracy", "pallet-dev-mode", "pallet-election-provider-multi-phase", "pallet-election-provider-support-benchmarking", "pallet-elections-phragmen", "pallet-fast-unstake", "pallet-glutton", "pallet-grandpa", "pallet-identity", "pallet-im-online", "pallet-indices", "pallet-insecure-randomness-collective-flip", "pallet-lottery", "pallet-membership", "pallet-message-queue", "pallet-migrations", "pallet-mixnet", "pallet-mmr", "pallet-multisig", "pallet-nft-fractionalization", "pallet-nfts", "pallet-nfts-runtime-api", "pallet-nis", "pallet-node-authorization", "pallet-nomination-pools", "pallet-nomination-pools-benchmarking", "pallet-nomination-pools-runtime-api", "pallet-offences", "pallet-offences-benchmarking", "pallet-paged-list", "pallet-parameters", "pallet-preimage", "pallet-proxy", "pallet-ranked-collective", "pallet-recovery", "pallet-referenda", "pallet-remark", "pallet-root-offences", "pallet-root-testing", "pallet-safe-mode", "pallet-salary", "pallet-scheduler", "pallet-scored-pool", "pallet-session", "pallet-session-benchmarking", "pallet-skip-feeless-payment", "pallet-society", "pallet-staking", "pallet-staking-reward-curve", "pallet-staking-reward-fn", "pallet-staking-runtime-api", "pallet-state-trie-migration", "pallet-statement", "pallet-sudo", "pallet-timestamp", "pallet-tips", "pallet-transaction-payment", "pallet-transaction-payment-rpc-runtime-api", "pallet-transaction-storage", "pallet-treasury", "pallet-tx-pause", "pallet-uniques", "pallet-utility", "pallet-vesting", "pallet-whitelist", "pallet-xcm", "pallet-xcm-benchmarks", "pallet-xcm-bridge-hub", "pallet-xcm-bridge-hub-router", "parachains-common", "polkadot-core-primitives", "polkadot-parachain-primitives", "polkadot-primitives", "polkadot-runtime-common", "polkadot-runtime-metrics", "polkadot-runtime-parachains", "polkadot-sdk-frame", "rococo-runtime-constants", "sc-chain-spec-derive", "sc-tracing-proc-macro", "slot-range-helper", "snowbridge-beacon-primitives", "snowbridge-core", "snowbridge-ethereum", "snowbridge-outbound-queue-merkle-tree", "snowbridge-outbound-queue-runtime-api", "snowbridge-pallet-ethereum-client", "snowbridge-pallet-ethereum-client-fixtures", "snowbridge-pallet-inbound-queue", "snowbridge-pallet-inbound-queue-fixtures", "snowbridge-pallet-outbound-queue", "snowbridge-pallet-system", "snowbridge-router-primitives", "snowbridge-runtime-common", "snowbridge-system-runtime-api", "sp-api", "sp-api-proc-macro", "sp-application-crypto", "sp-arithmetic", "sp-authority-discovery", "sp-block-builder", "sp-consensus-aura", "sp-consensus-babe", "sp-consensus-beefy", "sp-consensus-grandpa", "sp-consensus-pow", "sp-consensus-slots", "sp-core", "sp-crypto-ec-utils", "sp-crypto-hashing", "sp-crypto-hashing-proc-macro", "sp-debug-derive", "sp-externalities", "sp-genesis-builder", "sp-inherents", "sp-io", "sp-keyring", "sp-keystore", "sp-metadata-ir", "sp-mixnet", "sp-mmr-primitives", "sp-npos-elections", "sp-offchain", "sp-runtime", "sp-runtime-interface", "sp-runtime-interface-proc-macro", "sp-session", "sp-staking", "sp-state-machine", "sp-statement-store", "sp-std", "sp-storage", "sp-timestamp", "sp-tracing", "sp-transaction-pool", "sp-transaction-storage-proof", "sp-trie", "sp-version", "sp-version-proc-macro", "sp-wasm-interface", "sp-weights", "staging-parachain-info", "staging-xcm", "staging-xcm-builder", "staging-xcm-executor", "substrate-bip39", "testnet-parachains-constants", "tracing-gum-proc-macro", "westend-runtime-constants", "xcm-procedural", "xcm-runtime-apis"] node = ["asset-test-utils", "bridge-hub-test-utils", "cumulus-client-cli", "cumulus-client-collator", "cumulus-client-consensus-aura", "cumulus-client-consensus-common", "cumulus-client-consensus-proposer", "cumulus-client-consensus-relay-chain", "cumulus-client-network", "cumulus-client-parachain-inherent", "cumulus-client-pov-recovery", "cumulus-client-service", "cumulus-relay-chain-inprocess-interface", "cumulus-relay-chain-interface", "cumulus-relay-chain-minimal-node", "cumulus-relay-chain-rpc-interface", "cumulus-test-relay-sproof-builder", "emulated-integration-tests-common", "fork-tree", "frame-benchmarking-cli", "frame-remote-externalities", "frame-support-procedural-tools", "generate-bags", "mmr-gadget", "mmr-rpc", "pallet-contracts-mock-network", "pallet-transaction-payment-rpc", "parachains-runtimes-test-utils", "polkadot-approval-distribution", "polkadot-availability-bitfield-distribution", "polkadot-availability-distribution", "polkadot-availability-recovery", "polkadot-cli", "polkadot-collator-protocol", "polkadot-dispute-distribution", "polkadot-erasure-coding", "polkadot-gossip-support", "polkadot-network-bridge", "polkadot-node-collation-generation", "polkadot-node-core-approval-voting", "polkadot-node-core-av-store", "polkadot-node-core-backing", "polkadot-node-core-bitfield-signing", "polkadot-node-core-candidate-validation", "polkadot-node-core-chain-api", "polkadot-node-core-chain-selection", "polkadot-node-core-dispute-coordinator", "polkadot-node-core-parachains-inherent", "polkadot-node-core-prospective-parachains", "polkadot-node-core-provisioner", "polkadot-node-core-pvf", "polkadot-node-core-pvf-checker", "polkadot-node-core-pvf-common", "polkadot-node-core-pvf-execute-worker", "polkadot-node-core-pvf-prepare-worker", "polkadot-node-core-runtime-api", "polkadot-node-jaeger", "polkadot-node-metrics", "polkadot-node-network-protocol", "polkadot-node-primitives", "polkadot-node-subsystem", "polkadot-node-subsystem-types", "polkadot-node-subsystem-util", "polkadot-overseer", "polkadot-rpc", "polkadot-service", "polkadot-statement-distribution", "polkadot-statement-table", "sc-allocator", "sc-authority-discovery", "sc-basic-authorship", "sc-block-builder", "sc-chain-spec", "sc-cli", "sc-client-api", "sc-client-db", "sc-consensus", "sc-consensus-aura", "sc-consensus-babe", "sc-consensus-babe-rpc", "sc-consensus-beefy", "sc-consensus-beefy-rpc", "sc-consensus-epochs", "sc-consensus-grandpa", "sc-consensus-grandpa-rpc", "sc-consensus-manual-seal", "sc-consensus-pow", "sc-consensus-slots", "sc-executor", "sc-executor-common", "sc-executor-polkavm", "sc-executor-wasmtime", "sc-informant", "sc-keystore", "sc-mixnet", "sc-network", "sc-network-common", "sc-network-gossip", "sc-network-light", "sc-network-statement", "sc-network-sync", "sc-network-transactions", "sc-network-types", "sc-offchain", "sc-proposer-metrics", "sc-rpc", "sc-rpc-api", "sc-rpc-server", "sc-rpc-spec-v2", "sc-service", "sc-state-db", "sc-statement-store", "sc-storage-monitor", "sc-sync-state-rpc", "sc-sysinfo", "sc-telemetry", "sc-tracing", "sc-transaction-pool", "sc-transaction-pool-api", "sc-utils", "snowbridge-runtime-test-common", "sp-blockchain", "sp-consensus", "sp-core-hashing", "sp-core-hashing-proc-macro", "sp-database", "sp-maybe-compressed-blob", "sp-panic-handler", "sp-rpc", "staging-chain-spec-builder", "staging-node-inspect", "staging-tracking-allocator", "std", "subkey", "substrate-build-script-utils", "substrate-frame-rpc-support", "substrate-frame-rpc-system", "substrate-prometheus-endpoint", "substrate-rpc-client", "substrate-state-trie-migration-rpc", "substrate-wasm-builder", "tracing-gum", "xcm-emulator", "xcm-simulator"] tuples-96 = [ "frame-support-procedural?/tuples-96", @@ -854,6 +857,11 @@ path = "../substrate/frame/assets" default-features = false optional = true +[dependencies.pallet-assets-freezer] +path = "../substrate/frame/assets-freezer" +default-features = false +optional = true + [dependencies.pallet-atomic-swap] path = "../substrate/frame/atomic-swap" default-features = false @@ -1724,13 +1732,13 @@ path = "../polkadot/runtime/westend/constants" default-features = false optional = true -[dependencies.xcm-fee-payment-runtime-api] -path = "../polkadot/xcm/xcm-fee-payment-runtime-api" +[dependencies.xcm-procedural] +path = "../polkadot/xcm/procedural" default-features = false optional = true -[dependencies.xcm-procedural] -path = "../polkadot/xcm/procedural" +[dependencies.xcm-runtime-apis] +path = "../polkadot/xcm/xcm-runtime-apis" default-features = false optional = true diff --git a/umbrella/src/lib.rs b/umbrella/src/lib.rs index 78b34ba179b7dd7fd7b08980d14e58d624c480dc..58a5691961d9b8abc01098ef75065d92881127db 100644 --- a/umbrella/src/lib.rs +++ b/umbrella/src/lib.rs @@ -360,6 +360,10 @@ pub use pallet_asset_tx_payment; #[cfg(feature = "pallet-assets")] pub use pallet_assets; +/// Provides freezing features to `pallet-assets`. +#[cfg(feature = "pallet-assets-freezer")] +pub use pallet_assets_freezer; + /// FRAME atomic swap pallet. #[cfg(feature = "pallet-atomic-swap")] pub use pallet_atomic_swap; @@ -1556,14 +1560,14 @@ pub use westend_runtime_constants; #[cfg(feature = "xcm-emulator")] pub use xcm_emulator; -/// XCM fee payment runtime API. -#[cfg(feature = "xcm-fee-payment-runtime-api")] -pub use xcm_fee_payment_runtime_api; - /// Procedural macros for XCM. #[cfg(feature = "xcm-procedural")] pub use xcm_procedural; +/// XCM runtime APIs. +#[cfg(feature = "xcm-runtime-apis")] +pub use xcm_runtime_apis; + /// Test kit to simulate cross-chain message passing and XCM execution. #[cfg(feature = "xcm-simulator")] pub use xcm_simulator;